1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (hasVectorIntrinsicScalarOpd(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Gets reordering data for the given tree entry. If the entry is vectorized
933   /// - just return ReorderIndices, otherwise check if the scalars can be
934   /// reordered and return the most optimal order.
935   /// \param TopToBottom If true, include the order of vectorized stores and
936   /// insertelement nodes, otherwise skip them.
937   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
938 
939   /// Reorders the current graph to the most profitable order starting from the
940   /// root node to the leaf nodes. The best order is chosen only from the nodes
941   /// of the same size (vectorization factor). Smaller nodes are considered
942   /// parts of subgraph with smaller VF and they are reordered independently. We
943   /// can make it because we still need to extend smaller nodes to the wider VF
944   /// and we can merge reordering shuffles with the widening shuffles.
945   void reorderTopToBottom();
946 
947   /// Reorders the current graph to the most profitable order starting from
948   /// leaves to the root. It allows to rotate small subgraphs and reduce the
949   /// number of reshuffles if the leaf nodes use the same order. In this case we
950   /// can merge the orders and just shuffle user node instead of shuffling its
951   /// operands. Plus, even the leaf nodes have different orders, it allows to
952   /// sink reordering in the graph closer to the root node and merge it later
953   /// during analysis.
954   void reorderBottomToTop(bool IgnoreReorder = false);
955 
956   /// \return The vector element size in bits to use when vectorizing the
957   /// expression tree ending at \p V. If V is a store, the size is the width of
958   /// the stored value. Otherwise, the size is the width of the largest loaded
959   /// value reaching V. This method is used by the vectorizer to calculate
960   /// vectorization factors.
961   unsigned getVectorElementSize(Value *V);
962 
963   /// Compute the minimum type sizes required to represent the entries in a
964   /// vectorizable tree.
965   void computeMinimumValueSizes();
966 
967   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
968   unsigned getMaxVecRegSize() const {
969     return MaxVecRegSize;
970   }
971 
972   // \returns minimum vector register size as set by cl::opt.
973   unsigned getMinVecRegSize() const {
974     return MinVecRegSize;
975   }
976 
977   unsigned getMinVF(unsigned Sz) const {
978     return std::max(2U, getMinVecRegSize() / Sz);
979   }
980 
981   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
982     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
983       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
984     return MaxVF ? MaxVF : UINT_MAX;
985   }
986 
987   /// Check if homogeneous aggregate is isomorphic to some VectorType.
988   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
989   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
990   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
991   ///
992   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
993   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
994 
995   /// \returns True if the VectorizableTree is both tiny and not fully
996   /// vectorizable. We do not vectorize such trees.
997   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
998 
999   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1007 
1008   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1009   /// can be load combined in the backend. Load combining may not be allowed in
1010   /// the IR optimizer, so we do not want to alter the pattern. For example,
1011   /// partially transforming a scalar bswap() pattern into vector code is
1012   /// effectively impossible for the backend to undo.
1013   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1014   ///       may not be necessary.
1015   bool isLoadCombineCandidate() const;
1016 
1017   OptimizationRemarkEmitter *getORE() { return ORE; }
1018 
1019   /// This structure holds any data we need about the edges being traversed
1020   /// during buildTree_rec(). We keep track of:
1021   /// (i) the user TreeEntry index, and
1022   /// (ii) the index of the edge.
1023   struct EdgeInfo {
1024     EdgeInfo() = default;
1025     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1026         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1027     /// The user TreeEntry.
1028     TreeEntry *UserTE = nullptr;
1029     /// The operand index of the use.
1030     unsigned EdgeIdx = UINT_MAX;
1031 #ifndef NDEBUG
1032     friend inline raw_ostream &operator<<(raw_ostream &OS,
1033                                           const BoUpSLP::EdgeInfo &EI) {
1034       EI.dump(OS);
1035       return OS;
1036     }
1037     /// Debug print.
1038     void dump(raw_ostream &OS) const {
1039       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1040          << " EdgeIdx:" << EdgeIdx << "}";
1041     }
1042     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1043 #endif
1044   };
1045 
1046   /// A helper class used for scoring candidates for two consecutive lanes.
1047   class LookAheadHeuristics {
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051     int NumLanes; // Total number of lanes (aka vectorization factor).
1052     int MaxLevel; // The maximum recursion depth for accumulating score.
1053 
1054   public:
1055     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1056                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1057         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1058 
1059     // The hard-coded scores listed here are not very important, though it shall
1060     // be higher for better matches to improve the resulting cost. When
1061     // computing the scores of matching one sub-tree with another, we are
1062     // basically counting the number of values that are matching. So even if all
1063     // scores are set to 1, we would still get a decent matching result.
1064     // However, sometimes we have to break ties. For example we may have to
1065     // choose between matching loads vs matching opcodes. This is what these
1066     // scores are helping us with: they provide the order of preference. Also,
1067     // this is important if the scalar is externally used or used in another
1068     // tree entry node in the different lane.
1069 
1070     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1071     static const int ScoreConsecutiveLoads = 4;
1072     /// The same load multiple times. This should have a better score than
1073     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1074     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1075     /// a vector load and 1.0 for a broadcast.
1076     static const int ScoreSplatLoads = 3;
1077     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1078     static const int ScoreReversedLoads = 3;
1079     /// ExtractElementInst from same vector and consecutive indexes.
1080     static const int ScoreConsecutiveExtracts = 4;
1081     /// ExtractElementInst from same vector and reversed indices.
1082     static const int ScoreReversedExtracts = 3;
1083     /// Constants.
1084     static const int ScoreConstants = 2;
1085     /// Instructions with the same opcode.
1086     static const int ScoreSameOpcode = 2;
1087     /// Instructions with alt opcodes (e.g, add + sub).
1088     static const int ScoreAltOpcodes = 1;
1089     /// Identical instructions (a.k.a. splat or broadcast).
1090     static const int ScoreSplat = 1;
1091     /// Matching with an undef is preferable to failing.
1092     static const int ScoreUndef = 1;
1093     /// Score for failing to find a decent match.
1094     static const int ScoreFail = 0;
1095     /// Score if all users are vectorized.
1096     static const int ScoreAllUserVectorized = 1;
1097 
1098     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1099     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1100     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1101     /// MainAltOps.
1102     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1103                         ArrayRef<Value *> MainAltOps) const {
1104       if (V1 == V2) {
1105         if (isa<LoadInst>(V1)) {
1106           // Retruns true if the users of V1 and V2 won't need to be extracted.
1107           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1108             // Bail out if we have too many uses to save compilation time.
1109             static constexpr unsigned Limit = 8;
1110             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1111               return false;
1112 
1113             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1114               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1115                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1116               });
1117             };
1118             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1119           };
1120           // A broadcast of a load can be cheaper on some targets.
1121           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1122                                           ElementCount::getFixed(NumLanes)) &&
1123               ((int)V1->getNumUses() == NumLanes ||
1124                AllUsersAreInternal(V1, V2)))
1125             return LookAheadHeuristics::ScoreSplatLoads;
1126         }
1127         return LookAheadHeuristics::ScoreSplat;
1128       }
1129 
1130       auto *LI1 = dyn_cast<LoadInst>(V1);
1131       auto *LI2 = dyn_cast<LoadInst>(V2);
1132       if (LI1 && LI2) {
1133         if (LI1->getParent() != LI2->getParent())
1134           return LookAheadHeuristics::ScoreFail;
1135 
1136         Optional<int> Dist = getPointersDiff(
1137             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1138             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1139         if (!Dist || *Dist == 0)
1140           return LookAheadHeuristics::ScoreFail;
1141         // The distance is too large - still may be profitable to use masked
1142         // loads/gathers.
1143         if (std::abs(*Dist) > NumLanes / 2)
1144           return LookAheadHeuristics::ScoreAltOpcodes;
1145         // This still will detect consecutive loads, but we might have "holes"
1146         // in some cases. It is ok for non-power-2 vectorization and may produce
1147         // better results. It should not affect current vectorization.
1148         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1149                            : LookAheadHeuristics::ScoreReversedLoads;
1150       }
1151 
1152       auto *C1 = dyn_cast<Constant>(V1);
1153       auto *C2 = dyn_cast<Constant>(V2);
1154       if (C1 && C2)
1155         return LookAheadHeuristics::ScoreConstants;
1156 
1157       // Extracts from consecutive indexes of the same vector better score as
1158       // the extracts could be optimized away.
1159       Value *EV1;
1160       ConstantInt *Ex1Idx;
1161       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1162         // Undefs are always profitable for extractelements.
1163         if (isa<UndefValue>(V2))
1164           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1165         Value *EV2 = nullptr;
1166         ConstantInt *Ex2Idx = nullptr;
1167         if (match(V2,
1168                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1169                                                          m_Undef())))) {
1170           // Undefs are always profitable for extractelements.
1171           if (!Ex2Idx)
1172             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1173           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1174             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1175           if (EV2 == EV1) {
1176             int Idx1 = Ex1Idx->getZExtValue();
1177             int Idx2 = Ex2Idx->getZExtValue();
1178             int Dist = Idx2 - Idx1;
1179             // The distance is too large - still may be profitable to use
1180             // shuffles.
1181             if (std::abs(Dist) == 0)
1182               return LookAheadHeuristics::ScoreSplat;
1183             if (std::abs(Dist) > NumLanes / 2)
1184               return LookAheadHeuristics::ScoreSameOpcode;
1185             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1186                               : LookAheadHeuristics::ScoreReversedExtracts;
1187           }
1188           return LookAheadHeuristics::ScoreAltOpcodes;
1189         }
1190         return LookAheadHeuristics::ScoreFail;
1191       }
1192 
1193       auto *I1 = dyn_cast<Instruction>(V1);
1194       auto *I2 = dyn_cast<Instruction>(V2);
1195       if (I1 && I2) {
1196         if (I1->getParent() != I2->getParent())
1197           return LookAheadHeuristics::ScoreFail;
1198         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1199         Ops.push_back(I1);
1200         Ops.push_back(I2);
1201         InstructionsState S = getSameOpcode(Ops);
1202         // Note: Only consider instructions with <= 2 operands to avoid
1203         // complexity explosion.
1204         if (S.getOpcode() &&
1205             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1206              !S.isAltShuffle()) &&
1207             all_of(Ops, [&S](Value *V) {
1208               return cast<Instruction>(V)->getNumOperands() ==
1209                      S.MainOp->getNumOperands();
1210             }))
1211           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1212                                   : LookAheadHeuristics::ScoreSameOpcode;
1213       }
1214 
1215       if (isa<UndefValue>(V2))
1216         return LookAheadHeuristics::ScoreUndef;
1217 
1218       return LookAheadHeuristics::ScoreFail;
1219     }
1220 
1221     /// Go through the operands of \p LHS and \p RHS recursively until
1222     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1223     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1224     /// of \p U1 and \p U2), except at the beginning of the recursion where
1225     /// these are set to nullptr.
1226     ///
1227     /// For example:
1228     /// \verbatim
1229     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1230     ///     \ /         \ /         \ /        \ /
1231     ///      +           +           +          +
1232     ///     G1          G2          G3         G4
1233     /// \endverbatim
1234     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1235     /// each level recursively, accumulating the score. It starts from matching
1236     /// the additions at level 0, then moves on to the loads (level 1). The
1237     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1238     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1239     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1240     /// Please note that the order of the operands does not matter, as we
1241     /// evaluate the score of all profitable combinations of operands. In
1242     /// other words the score of G1 and G4 is the same as G1 and G2. This
1243     /// heuristic is based on ideas described in:
1244     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1245     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1246     ///   Luís F. W. Góes
1247     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1248                            Instruction *U2, int CurrLevel,
1249                            ArrayRef<Value *> MainAltOps) const {
1250 
1251       // Get the shallow score of V1 and V2.
1252       int ShallowScoreAtThisLevel =
1253           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1254 
1255       // If reached MaxLevel,
1256       //  or if V1 and V2 are not instructions,
1257       //  or if they are SPLAT,
1258       //  or if they are not consecutive,
1259       //  or if profitable to vectorize loads or extractelements, early return
1260       //  the current cost.
1261       auto *I1 = dyn_cast<Instruction>(LHS);
1262       auto *I2 = dyn_cast<Instruction>(RHS);
1263       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1264           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1265           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1266             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1267             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1268            ShallowScoreAtThisLevel))
1269         return ShallowScoreAtThisLevel;
1270       assert(I1 && I2 && "Should have early exited.");
1271 
1272       // Contains the I2 operand indexes that got matched with I1 operands.
1273       SmallSet<unsigned, 4> Op2Used;
1274 
1275       // Recursion towards the operands of I1 and I2. We are trying all possible
1276       // operand pairs, and keeping track of the best score.
1277       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1278            OpIdx1 != NumOperands1; ++OpIdx1) {
1279         // Try to pair op1I with the best operand of I2.
1280         int MaxTmpScore = 0;
1281         unsigned MaxOpIdx2 = 0;
1282         bool FoundBest = false;
1283         // If I2 is commutative try all combinations.
1284         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1285         unsigned ToIdx = isCommutative(I2)
1286                              ? I2->getNumOperands()
1287                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1288         assert(FromIdx <= ToIdx && "Bad index");
1289         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1290           // Skip operands already paired with OpIdx1.
1291           if (Op2Used.count(OpIdx2))
1292             continue;
1293           // Recursively calculate the cost at each level
1294           int TmpScore =
1295               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1296                                  I1, I2, CurrLevel + 1, None);
1297           // Look for the best score.
1298           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1299               TmpScore > MaxTmpScore) {
1300             MaxTmpScore = TmpScore;
1301             MaxOpIdx2 = OpIdx2;
1302             FoundBest = true;
1303           }
1304         }
1305         if (FoundBest) {
1306           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1307           Op2Used.insert(MaxOpIdx2);
1308           ShallowScoreAtThisLevel += MaxTmpScore;
1309         }
1310       }
1311       return ShallowScoreAtThisLevel;
1312     }
1313   };
1314   /// A helper data structure to hold the operands of a vector of instructions.
1315   /// This supports a fixed vector length for all operand vectors.
1316   class VLOperands {
1317     /// For each operand we need (i) the value, and (ii) the opcode that it
1318     /// would be attached to if the expression was in a left-linearized form.
1319     /// This is required to avoid illegal operand reordering.
1320     /// For example:
1321     /// \verbatim
1322     ///                         0 Op1
1323     ///                         |/
1324     /// Op1 Op2   Linearized    + Op2
1325     ///   \ /     ---------->   |/
1326     ///    -                    -
1327     ///
1328     /// Op1 - Op2            (0 + Op1) - Op2
1329     /// \endverbatim
1330     ///
1331     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1332     ///
1333     /// Another way to think of this is to track all the operations across the
1334     /// path from the operand all the way to the root of the tree and to
1335     /// calculate the operation that corresponds to this path. For example, the
1336     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1337     /// corresponding operation is a '-' (which matches the one in the
1338     /// linearized tree, as shown above).
1339     ///
1340     /// For lack of a better term, we refer to this operation as Accumulated
1341     /// Path Operation (APO).
1342     struct OperandData {
1343       OperandData() = default;
1344       OperandData(Value *V, bool APO, bool IsUsed)
1345           : V(V), APO(APO), IsUsed(IsUsed) {}
1346       /// The operand value.
1347       Value *V = nullptr;
1348       /// TreeEntries only allow a single opcode, or an alternate sequence of
1349       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1350       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1351       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1352       /// (e.g., Add/Mul)
1353       bool APO = false;
1354       /// Helper data for the reordering function.
1355       bool IsUsed = false;
1356     };
1357 
1358     /// During operand reordering, we are trying to select the operand at lane
1359     /// that matches best with the operand at the neighboring lane. Our
1360     /// selection is based on the type of value we are looking for. For example,
1361     /// if the neighboring lane has a load, we need to look for a load that is
1362     /// accessing a consecutive address. These strategies are summarized in the
1363     /// 'ReorderingMode' enumerator.
1364     enum class ReorderingMode {
1365       Load,     ///< Matching loads to consecutive memory addresses
1366       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1367       Constant, ///< Matching constants
1368       Splat,    ///< Matching the same instruction multiple times (broadcast)
1369       Failed,   ///< We failed to create a vectorizable group
1370     };
1371 
1372     using OperandDataVec = SmallVector<OperandData, 2>;
1373 
1374     /// A vector of operand vectors.
1375     SmallVector<OperandDataVec, 4> OpsVec;
1376 
1377     const DataLayout &DL;
1378     ScalarEvolution &SE;
1379     const BoUpSLP &R;
1380 
1381     /// \returns the operand data at \p OpIdx and \p Lane.
1382     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1383       return OpsVec[OpIdx][Lane];
1384     }
1385 
1386     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1387     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1388       return OpsVec[OpIdx][Lane];
1389     }
1390 
1391     /// Clears the used flag for all entries.
1392     void clearUsed() {
1393       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1394            OpIdx != NumOperands; ++OpIdx)
1395         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1396              ++Lane)
1397           OpsVec[OpIdx][Lane].IsUsed = false;
1398     }
1399 
1400     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1401     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1402       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1403     }
1404 
1405     /// \param Lane lane of the operands under analysis.
1406     /// \param OpIdx operand index in \p Lane lane we're looking the best
1407     /// candidate for.
1408     /// \param Idx operand index of the current candidate value.
1409     /// \returns The additional score due to possible broadcasting of the
1410     /// elements in the lane. It is more profitable to have power-of-2 unique
1411     /// elements in the lane, it will be vectorized with higher probability
1412     /// after removing duplicates. Currently the SLP vectorizer supports only
1413     /// vectorization of the power-of-2 number of unique scalars.
1414     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1415       Value *IdxLaneV = getData(Idx, Lane).V;
1416       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1417         return 0;
1418       SmallPtrSet<Value *, 4> Uniques;
1419       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1420         if (Ln == Lane)
1421           continue;
1422         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1423         if (!isa<Instruction>(OpIdxLnV))
1424           return 0;
1425         Uniques.insert(OpIdxLnV);
1426       }
1427       int UniquesCount = Uniques.size();
1428       int UniquesCntWithIdxLaneV =
1429           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1430       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1431       int UniquesCntWithOpIdxLaneV =
1432           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1434         return 0;
1435       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1436               UniquesCntWithOpIdxLaneV) -
1437              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1438     }
1439 
1440     /// \param Lane lane of the operands under analysis.
1441     /// \param OpIdx operand index in \p Lane lane we're looking the best
1442     /// candidate for.
1443     /// \param Idx operand index of the current candidate value.
1444     /// \returns The additional score for the scalar which users are all
1445     /// vectorized.
1446     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1447       Value *IdxLaneV = getData(Idx, Lane).V;
1448       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1449       // Do not care about number of uses for vector-like instructions
1450       // (extractelement/extractvalue with constant indices), they are extracts
1451       // themselves and already externally used. Vectorization of such
1452       // instructions does not add extra extractelement instruction, just may
1453       // remove it.
1454       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1455           isVectorLikeInstWithConstOps(OpIdxLaneV))
1456         return LookAheadHeuristics::ScoreAllUserVectorized;
1457       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1458       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1459         return 0;
1460       return R.areAllUsersVectorized(IdxLaneI, None)
1461                  ? LookAheadHeuristics::ScoreAllUserVectorized
1462                  : 0;
1463     }
1464 
1465     /// Score scaling factor for fully compatible instructions but with
1466     /// different number of external uses. Allows better selection of the
1467     /// instructions with less external uses.
1468     static const int ScoreScaleFactor = 10;
1469 
1470     /// \Returns the look-ahead score, which tells us how much the sub-trees
1471     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1472     /// score. This helps break ties in an informed way when we cannot decide on
1473     /// the order of the operands by just considering the immediate
1474     /// predecessors.
1475     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1476                           int Lane, unsigned OpIdx, unsigned Idx,
1477                           bool &IsUsed) {
1478       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1479                                     LookAheadMaxDepth);
1480       // Keep track of the instruction stack as we recurse into the operands
1481       // during the look-ahead score exploration.
1482       int Score =
1483           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1484                                        /*CurrLevel=*/1, MainAltOps);
1485       if (Score) {
1486         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1487         if (Score <= -SplatScore) {
1488           // Set the minimum score for splat-like sequence to avoid setting
1489           // failed state.
1490           Score = 1;
1491         } else {
1492           Score += SplatScore;
1493           // Scale score to see the difference between different operands
1494           // and similar operands but all vectorized/not all vectorized
1495           // uses. It does not affect actual selection of the best
1496           // compatible operand in general, just allows to select the
1497           // operand with all vectorized uses.
1498           Score *= ScoreScaleFactor;
1499           Score += getExternalUseScore(Lane, OpIdx, Idx);
1500           IsUsed = true;
1501         }
1502       }
1503       return Score;
1504     }
1505 
1506     /// Best defined scores per lanes between the passes. Used to choose the
1507     /// best operand (with the highest score) between the passes.
1508     /// The key - {Operand Index, Lane}.
1509     /// The value - the best score between the passes for the lane and the
1510     /// operand.
1511     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1512         BestScoresPerLanes;
1513 
1514     // Search all operands in Ops[*][Lane] for the one that matches best
1515     // Ops[OpIdx][LastLane] and return its opreand index.
1516     // If no good match can be found, return None.
1517     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1518                                       ArrayRef<ReorderingMode> ReorderingModes,
1519                                       ArrayRef<Value *> MainAltOps) {
1520       unsigned NumOperands = getNumOperands();
1521 
1522       // The operand of the previous lane at OpIdx.
1523       Value *OpLastLane = getData(OpIdx, LastLane).V;
1524 
1525       // Our strategy mode for OpIdx.
1526       ReorderingMode RMode = ReorderingModes[OpIdx];
1527       if (RMode == ReorderingMode::Failed)
1528         return None;
1529 
1530       // The linearized opcode of the operand at OpIdx, Lane.
1531       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1532 
1533       // The best operand index and its score.
1534       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1535       // are using the score to differentiate between the two.
1536       struct BestOpData {
1537         Optional<unsigned> Idx = None;
1538         unsigned Score = 0;
1539       } BestOp;
1540       BestOp.Score =
1541           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1542               .first->second;
1543 
1544       // Track if the operand must be marked as used. If the operand is set to
1545       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1546       // want to reestimate the operands again on the following iterations).
1547       bool IsUsed =
1548           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1549       // Iterate through all unused operands and look for the best.
1550       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1551         // Get the operand at Idx and Lane.
1552         OperandData &OpData = getData(Idx, Lane);
1553         Value *Op = OpData.V;
1554         bool OpAPO = OpData.APO;
1555 
1556         // Skip already selected operands.
1557         if (OpData.IsUsed)
1558           continue;
1559 
1560         // Skip if we are trying to move the operand to a position with a
1561         // different opcode in the linearized tree form. This would break the
1562         // semantics.
1563         if (OpAPO != OpIdxAPO)
1564           continue;
1565 
1566         // Look for an operand that matches the current mode.
1567         switch (RMode) {
1568         case ReorderingMode::Load:
1569         case ReorderingMode::Constant:
1570         case ReorderingMode::Opcode: {
1571           bool LeftToRight = Lane > LastLane;
1572           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1573           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1574           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1575                                         OpIdx, Idx, IsUsed);
1576           if (Score > static_cast<int>(BestOp.Score)) {
1577             BestOp.Idx = Idx;
1578             BestOp.Score = Score;
1579             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1580           }
1581           break;
1582         }
1583         case ReorderingMode::Splat:
1584           if (Op == OpLastLane)
1585             BestOp.Idx = Idx;
1586           break;
1587         case ReorderingMode::Failed:
1588           llvm_unreachable("Not expected Failed reordering mode.");
1589         }
1590       }
1591 
1592       if (BestOp.Idx) {
1593         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1594         return BestOp.Idx;
1595       }
1596       // If we could not find a good match return None.
1597       return None;
1598     }
1599 
1600     /// Helper for reorderOperandVecs.
1601     /// \returns the lane that we should start reordering from. This is the one
1602     /// which has the least number of operands that can freely move about or
1603     /// less profitable because it already has the most optimal set of operands.
1604     unsigned getBestLaneToStartReordering() const {
1605       unsigned Min = UINT_MAX;
1606       unsigned SameOpNumber = 0;
1607       // std::pair<unsigned, unsigned> is used to implement a simple voting
1608       // algorithm and choose the lane with the least number of operands that
1609       // can freely move about or less profitable because it already has the
1610       // most optimal set of operands. The first unsigned is a counter for
1611       // voting, the second unsigned is the counter of lanes with instructions
1612       // with same/alternate opcodes and same parent basic block.
1613       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1614       // Try to be closer to the original results, if we have multiple lanes
1615       // with same cost. If 2 lanes have the same cost, use the one with the
1616       // lowest index.
1617       for (int I = getNumLanes(); I > 0; --I) {
1618         unsigned Lane = I - 1;
1619         OperandsOrderData NumFreeOpsHash =
1620             getMaxNumOperandsThatCanBeReordered(Lane);
1621         // Compare the number of operands that can move and choose the one with
1622         // the least number.
1623         if (NumFreeOpsHash.NumOfAPOs < Min) {
1624           Min = NumFreeOpsHash.NumOfAPOs;
1625           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1626           HashMap.clear();
1627           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1628         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1629                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1630           // Select the most optimal lane in terms of number of operands that
1631           // should be moved around.
1632           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1633           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1634         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1635                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1636           auto It = HashMap.find(NumFreeOpsHash.Hash);
1637           if (It == HashMap.end())
1638             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1639           else
1640             ++It->second.first;
1641         }
1642       }
1643       // Select the lane with the minimum counter.
1644       unsigned BestLane = 0;
1645       unsigned CntMin = UINT_MAX;
1646       for (const auto &Data : reverse(HashMap)) {
1647         if (Data.second.first < CntMin) {
1648           CntMin = Data.second.first;
1649           BestLane = Data.second.second;
1650         }
1651       }
1652       return BestLane;
1653     }
1654 
1655     /// Data structure that helps to reorder operands.
1656     struct OperandsOrderData {
1657       /// The best number of operands with the same APOs, which can be
1658       /// reordered.
1659       unsigned NumOfAPOs = UINT_MAX;
1660       /// Number of operands with the same/alternate instruction opcode and
1661       /// parent.
1662       unsigned NumOpsWithSameOpcodeParent = 0;
1663       /// Hash for the actual operands ordering.
1664       /// Used to count operands, actually their position id and opcode
1665       /// value. It is used in the voting mechanism to find the lane with the
1666       /// least number of operands that can freely move about or less profitable
1667       /// because it already has the most optimal set of operands. Can be
1668       /// replaced with SmallVector<unsigned> instead but hash code is faster
1669       /// and requires less memory.
1670       unsigned Hash = 0;
1671     };
1672     /// \returns the maximum number of operands that are allowed to be reordered
1673     /// for \p Lane and the number of compatible instructions(with the same
1674     /// parent/opcode). This is used as a heuristic for selecting the first lane
1675     /// to start operand reordering.
1676     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1677       unsigned CntTrue = 0;
1678       unsigned NumOperands = getNumOperands();
1679       // Operands with the same APO can be reordered. We therefore need to count
1680       // how many of them we have for each APO, like this: Cnt[APO] = x.
1681       // Since we only have two APOs, namely true and false, we can avoid using
1682       // a map. Instead we can simply count the number of operands that
1683       // correspond to one of them (in this case the 'true' APO), and calculate
1684       // the other by subtracting it from the total number of operands.
1685       // Operands with the same instruction opcode and parent are more
1686       // profitable since we don't need to move them in many cases, with a high
1687       // probability such lane already can be vectorized effectively.
1688       bool AllUndefs = true;
1689       unsigned NumOpsWithSameOpcodeParent = 0;
1690       Instruction *OpcodeI = nullptr;
1691       BasicBlock *Parent = nullptr;
1692       unsigned Hash = 0;
1693       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1694         const OperandData &OpData = getData(OpIdx, Lane);
1695         if (OpData.APO)
1696           ++CntTrue;
1697         // Use Boyer-Moore majority voting for finding the majority opcode and
1698         // the number of times it occurs.
1699         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1700           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1701               I->getParent() != Parent) {
1702             if (NumOpsWithSameOpcodeParent == 0) {
1703               NumOpsWithSameOpcodeParent = 1;
1704               OpcodeI = I;
1705               Parent = I->getParent();
1706             } else {
1707               --NumOpsWithSameOpcodeParent;
1708             }
1709           } else {
1710             ++NumOpsWithSameOpcodeParent;
1711           }
1712         }
1713         Hash = hash_combine(
1714             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1715         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1716       }
1717       if (AllUndefs)
1718         return {};
1719       OperandsOrderData Data;
1720       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1721       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1722       Data.Hash = Hash;
1723       return Data;
1724     }
1725 
1726     /// Go through the instructions in VL and append their operands.
1727     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1728       assert(!VL.empty() && "Bad VL");
1729       assert((empty() || VL.size() == getNumLanes()) &&
1730              "Expected same number of lanes");
1731       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1732       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1733       OpsVec.resize(NumOperands);
1734       unsigned NumLanes = VL.size();
1735       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1736         OpsVec[OpIdx].resize(NumLanes);
1737         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1738           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1739           // Our tree has just 3 nodes: the root and two operands.
1740           // It is therefore trivial to get the APO. We only need to check the
1741           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1742           // RHS operand. The LHS operand of both add and sub is never attached
1743           // to an inversese operation in the linearized form, therefore its APO
1744           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1745 
1746           // Since operand reordering is performed on groups of commutative
1747           // operations or alternating sequences (e.g., +, -), we can safely
1748           // tell the inverse operations by checking commutativity.
1749           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1750           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1751           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1752                                  APO, false};
1753         }
1754       }
1755     }
1756 
1757     /// \returns the number of operands.
1758     unsigned getNumOperands() const { return OpsVec.size(); }
1759 
1760     /// \returns the number of lanes.
1761     unsigned getNumLanes() const { return OpsVec[0].size(); }
1762 
1763     /// \returns the operand value at \p OpIdx and \p Lane.
1764     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1765       return getData(OpIdx, Lane).V;
1766     }
1767 
1768     /// \returns true if the data structure is empty.
1769     bool empty() const { return OpsVec.empty(); }
1770 
1771     /// Clears the data.
1772     void clear() { OpsVec.clear(); }
1773 
1774     /// \Returns true if there are enough operands identical to \p Op to fill
1775     /// the whole vector.
1776     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1777     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1778       bool OpAPO = getData(OpIdx, Lane).APO;
1779       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1780         if (Ln == Lane)
1781           continue;
1782         // This is set to true if we found a candidate for broadcast at Lane.
1783         bool FoundCandidate = false;
1784         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1785           OperandData &Data = getData(OpI, Ln);
1786           if (Data.APO != OpAPO || Data.IsUsed)
1787             continue;
1788           if (Data.V == Op) {
1789             FoundCandidate = true;
1790             Data.IsUsed = true;
1791             break;
1792           }
1793         }
1794         if (!FoundCandidate)
1795           return false;
1796       }
1797       return true;
1798     }
1799 
1800   public:
1801     /// Initialize with all the operands of the instruction vector \p RootVL.
1802     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1803                ScalarEvolution &SE, const BoUpSLP &R)
1804         : DL(DL), SE(SE), R(R) {
1805       // Append all the operands of RootVL.
1806       appendOperandsOfVL(RootVL);
1807     }
1808 
1809     /// \Returns a value vector with the operands across all lanes for the
1810     /// opearnd at \p OpIdx.
1811     ValueList getVL(unsigned OpIdx) const {
1812       ValueList OpVL(OpsVec[OpIdx].size());
1813       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1814              "Expected same num of lanes across all operands");
1815       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1816         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1817       return OpVL;
1818     }
1819 
1820     // Performs operand reordering for 2 or more operands.
1821     // The original operands are in OrigOps[OpIdx][Lane].
1822     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1823     void reorder() {
1824       unsigned NumOperands = getNumOperands();
1825       unsigned NumLanes = getNumLanes();
1826       // Each operand has its own mode. We are using this mode to help us select
1827       // the instructions for each lane, so that they match best with the ones
1828       // we have selected so far.
1829       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1830 
1831       // This is a greedy single-pass algorithm. We are going over each lane
1832       // once and deciding on the best order right away with no back-tracking.
1833       // However, in order to increase its effectiveness, we start with the lane
1834       // that has operands that can move the least. For example, given the
1835       // following lanes:
1836       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1837       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1838       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1839       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1840       // we will start at Lane 1, since the operands of the subtraction cannot
1841       // be reordered. Then we will visit the rest of the lanes in a circular
1842       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1843 
1844       // Find the first lane that we will start our search from.
1845       unsigned FirstLane = getBestLaneToStartReordering();
1846 
1847       // Initialize the modes.
1848       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1849         Value *OpLane0 = getValue(OpIdx, FirstLane);
1850         // Keep track if we have instructions with all the same opcode on one
1851         // side.
1852         if (isa<LoadInst>(OpLane0))
1853           ReorderingModes[OpIdx] = ReorderingMode::Load;
1854         else if (isa<Instruction>(OpLane0)) {
1855           // Check if OpLane0 should be broadcast.
1856           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1857             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1858           else
1859             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1860         }
1861         else if (isa<Constant>(OpLane0))
1862           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1863         else if (isa<Argument>(OpLane0))
1864           // Our best hope is a Splat. It may save some cost in some cases.
1865           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1866         else
1867           // NOTE: This should be unreachable.
1868           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1869       }
1870 
1871       // Check that we don't have same operands. No need to reorder if operands
1872       // are just perfect diamond or shuffled diamond match. Do not do it only
1873       // for possible broadcasts or non-power of 2 number of scalars (just for
1874       // now).
1875       auto &&SkipReordering = [this]() {
1876         SmallPtrSet<Value *, 4> UniqueValues;
1877         ArrayRef<OperandData> Op0 = OpsVec.front();
1878         for (const OperandData &Data : Op0)
1879           UniqueValues.insert(Data.V);
1880         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1881           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1882                 return !UniqueValues.contains(Data.V);
1883               }))
1884             return false;
1885         }
1886         // TODO: Check if we can remove a check for non-power-2 number of
1887         // scalars after full support of non-power-2 vectorization.
1888         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1889       };
1890 
1891       // If the initial strategy fails for any of the operand indexes, then we
1892       // perform reordering again in a second pass. This helps avoid assigning
1893       // high priority to the failed strategy, and should improve reordering for
1894       // the non-failed operand indexes.
1895       for (int Pass = 0; Pass != 2; ++Pass) {
1896         // Check if no need to reorder operands since they're are perfect or
1897         // shuffled diamond match.
1898         // Need to to do it to avoid extra external use cost counting for
1899         // shuffled matches, which may cause regressions.
1900         if (SkipReordering())
1901           break;
1902         // Skip the second pass if the first pass did not fail.
1903         bool StrategyFailed = false;
1904         // Mark all operand data as free to use.
1905         clearUsed();
1906         // We keep the original operand order for the FirstLane, so reorder the
1907         // rest of the lanes. We are visiting the nodes in a circular fashion,
1908         // using FirstLane as the center point and increasing the radius
1909         // distance.
1910         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1911         for (unsigned I = 0; I < NumOperands; ++I)
1912           MainAltOps[I].push_back(getData(I, FirstLane).V);
1913 
1914         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1915           // Visit the lane on the right and then the lane on the left.
1916           for (int Direction : {+1, -1}) {
1917             int Lane = FirstLane + Direction * Distance;
1918             if (Lane < 0 || Lane >= (int)NumLanes)
1919               continue;
1920             int LastLane = Lane - Direction;
1921             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1922                    "Out of bounds");
1923             // Look for a good match for each operand.
1924             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1925               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1926               Optional<unsigned> BestIdx = getBestOperand(
1927                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1928               // By not selecting a value, we allow the operands that follow to
1929               // select a better matching value. We will get a non-null value in
1930               // the next run of getBestOperand().
1931               if (BestIdx) {
1932                 // Swap the current operand with the one returned by
1933                 // getBestOperand().
1934                 swap(OpIdx, BestIdx.getValue(), Lane);
1935               } else {
1936                 // We failed to find a best operand, set mode to 'Failed'.
1937                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1938                 // Enable the second pass.
1939                 StrategyFailed = true;
1940               }
1941               // Try to get the alternate opcode and follow it during analysis.
1942               if (MainAltOps[OpIdx].size() != 2) {
1943                 OperandData &AltOp = getData(OpIdx, Lane);
1944                 InstructionsState OpS =
1945                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1946                 if (OpS.getOpcode() && OpS.isAltShuffle())
1947                   MainAltOps[OpIdx].push_back(AltOp.V);
1948               }
1949             }
1950           }
1951         }
1952         // Skip second pass if the strategy did not fail.
1953         if (!StrategyFailed)
1954           break;
1955       }
1956     }
1957 
1958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1959     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1960       switch (RMode) {
1961       case ReorderingMode::Load:
1962         return "Load";
1963       case ReorderingMode::Opcode:
1964         return "Opcode";
1965       case ReorderingMode::Constant:
1966         return "Constant";
1967       case ReorderingMode::Splat:
1968         return "Splat";
1969       case ReorderingMode::Failed:
1970         return "Failed";
1971       }
1972       llvm_unreachable("Unimplemented Reordering Type");
1973     }
1974 
1975     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1976                                                    raw_ostream &OS) {
1977       return OS << getModeStr(RMode);
1978     }
1979 
1980     /// Debug print.
1981     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1982       printMode(RMode, dbgs());
1983     }
1984 
1985     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1986       return printMode(RMode, OS);
1987     }
1988 
1989     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1990       const unsigned Indent = 2;
1991       unsigned Cnt = 0;
1992       for (const OperandDataVec &OpDataVec : OpsVec) {
1993         OS << "Operand " << Cnt++ << "\n";
1994         for (const OperandData &OpData : OpDataVec) {
1995           OS.indent(Indent) << "{";
1996           if (Value *V = OpData.V)
1997             OS << *V;
1998           else
1999             OS << "null";
2000           OS << ", APO:" << OpData.APO << "}\n";
2001         }
2002         OS << "\n";
2003       }
2004       return OS;
2005     }
2006 
2007     /// Debug print.
2008     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2009 #endif
2010   };
2011 
2012   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2013   /// for a pair which have highest score deemed to have best chance to form
2014   /// root of profitable tree to vectorize. Return None if no candidate scored
2015   /// above the LookAheadHeuristics::ScoreFail.
2016   Optional<int>
2017   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2018     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2019                                   RootLookAheadMaxDepth);
2020     int BestScore = LookAheadHeuristics::ScoreFail;
2021     Optional<int> Index = None;
2022     for (int I : seq<int>(0, Candidates.size())) {
2023       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2024                                                Candidates[I].second,
2025                                                /*U1=*/nullptr, /*U2=*/nullptr,
2026                                                /*Level=*/1, None);
2027       if (Score > BestScore) {
2028         BestScore = Score;
2029         Index = I;
2030       }
2031     }
2032     return Index;
2033   }
2034 
2035   /// Checks if the instruction is marked for deletion.
2036   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2037 
2038   /// Removes an instruction from its block and eventually deletes it.
2039   /// It's like Instruction::eraseFromParent() except that the actual deletion
2040   /// is delayed until BoUpSLP is destructed.
2041   void eraseInstruction(Instruction *I) {
2042     DeletedInstructions.insert(I);
2043   }
2044 
2045   ~BoUpSLP();
2046 
2047 private:
2048   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2049   /// reordering (i.e. the operands can be reordered because they have only one
2050   /// user and reordarable).
2051   /// \param ReorderableGathers List of all gather nodes that require reordering
2052   /// (e.g., gather of extractlements or partially vectorizable loads).
2053   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2054   /// reordering, subset of \p NonVectorized.
2055   bool
2056   canReorderOperands(TreeEntry *UserTE,
2057                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2058                      ArrayRef<TreeEntry *> ReorderableGathers,
2059                      SmallVectorImpl<TreeEntry *> &GatherOps);
2060 
2061   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2062   /// if any. If it is not vectorized (gather node), returns nullptr.
2063   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2064     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2065     TreeEntry *TE = nullptr;
2066     const auto *It = find_if(VL, [this, &TE](Value *V) {
2067       TE = getTreeEntry(V);
2068       return TE;
2069     });
2070     if (It != VL.end() && TE->isSame(VL))
2071       return TE;
2072     return nullptr;
2073   }
2074 
2075   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2076   /// if any. If it is not vectorized (gather node), returns nullptr.
2077   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2078                                         unsigned OpIdx) const {
2079     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2080         const_cast<TreeEntry *>(UserTE), OpIdx);
2081   }
2082 
2083   /// Checks if all users of \p I are the part of the vectorization tree.
2084   bool areAllUsersVectorized(Instruction *I,
2085                              ArrayRef<Value *> VectorizedVals) const;
2086 
2087   /// \returns the cost of the vectorizable entry.
2088   InstructionCost getEntryCost(const TreeEntry *E,
2089                                ArrayRef<Value *> VectorizedVals);
2090 
2091   /// This is the recursive part of buildTree.
2092   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2093                      const EdgeInfo &EI);
2094 
2095   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2096   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2097   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2098   /// returns false, setting \p CurrentOrder to either an empty vector or a
2099   /// non-identity permutation that allows to reuse extract instructions.
2100   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2101                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2102 
2103   /// Vectorize a single entry in the tree.
2104   Value *vectorizeTree(TreeEntry *E);
2105 
2106   /// Vectorize a single entry in the tree, starting in \p VL.
2107   Value *vectorizeTree(ArrayRef<Value *> VL);
2108 
2109   /// Create a new vector from a list of scalar values.  Produces a sequence
2110   /// which exploits values reused across lanes, and arranges the inserts
2111   /// for ease of later optimization.
2112   Value *createBuildVector(ArrayRef<Value *> VL);
2113 
2114   /// \returns the scalarization cost for this type. Scalarization in this
2115   /// context means the creation of vectors from a group of scalars. If \p
2116   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2117   /// vector elements.
2118   InstructionCost getGatherCost(FixedVectorType *Ty,
2119                                 const APInt &ShuffledIndices,
2120                                 bool NeedToShuffle) const;
2121 
2122   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2123   /// tree entries.
2124   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2125   /// previous tree entries. \p Mask is filled with the shuffle mask.
2126   Optional<TargetTransformInfo::ShuffleKind>
2127   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2128                         SmallVectorImpl<const TreeEntry *> &Entries);
2129 
2130   /// \returns the scalarization cost for this list of values. Assuming that
2131   /// this subtree gets vectorized, we may need to extract the values from the
2132   /// roots. This method calculates the cost of extracting the values.
2133   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2134 
2135   /// Set the Builder insert point to one after the last instruction in
2136   /// the bundle
2137   void setInsertPointAfterBundle(const TreeEntry *E);
2138 
2139   /// \returns a vector from a collection of scalars in \p VL.
2140   Value *gather(ArrayRef<Value *> VL);
2141 
2142   /// \returns whether the VectorizableTree is fully vectorizable and will
2143   /// be beneficial even the tree height is tiny.
2144   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2145 
2146   /// Reorder commutative or alt operands to get better probability of
2147   /// generating vectorized code.
2148   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2149                                              SmallVectorImpl<Value *> &Left,
2150                                              SmallVectorImpl<Value *> &Right,
2151                                              const DataLayout &DL,
2152                                              ScalarEvolution &SE,
2153                                              const BoUpSLP &R);
2154   struct TreeEntry {
2155     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2156     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2157 
2158     /// \returns true if the scalars in VL are equal to this entry.
2159     bool isSame(ArrayRef<Value *> VL) const {
2160       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2161         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2162           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2163         return VL.size() == Mask.size() &&
2164                std::equal(VL.begin(), VL.end(), Mask.begin(),
2165                           [Scalars](Value *V, int Idx) {
2166                             return (isa<UndefValue>(V) &&
2167                                     Idx == UndefMaskElem) ||
2168                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2169                           });
2170       };
2171       if (!ReorderIndices.empty()) {
2172         // TODO: implement matching if the nodes are just reordered, still can
2173         // treat the vector as the same if the list of scalars matches VL
2174         // directly, without reordering.
2175         SmallVector<int> Mask;
2176         inversePermutation(ReorderIndices, Mask);
2177         if (VL.size() == Scalars.size())
2178           return IsSame(Scalars, Mask);
2179         if (VL.size() == ReuseShuffleIndices.size()) {
2180           ::addMask(Mask, ReuseShuffleIndices);
2181           return IsSame(Scalars, Mask);
2182         }
2183         return false;
2184       }
2185       return IsSame(Scalars, ReuseShuffleIndices);
2186     }
2187 
2188     /// \returns true if current entry has same operands as \p TE.
2189     bool hasEqualOperands(const TreeEntry &TE) const {
2190       if (TE.getNumOperands() != getNumOperands())
2191         return false;
2192       SmallBitVector Used(getNumOperands());
2193       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2194         unsigned PrevCount = Used.count();
2195         for (unsigned K = 0; K < E; ++K) {
2196           if (Used.test(K))
2197             continue;
2198           if (getOperand(K) == TE.getOperand(I)) {
2199             Used.set(K);
2200             break;
2201           }
2202         }
2203         // Check if we actually found the matching operand.
2204         if (PrevCount == Used.count())
2205           return false;
2206       }
2207       return true;
2208     }
2209 
2210     /// \return Final vectorization factor for the node. Defined by the total
2211     /// number of vectorized scalars, including those, used several times in the
2212     /// entry and counted in the \a ReuseShuffleIndices, if any.
2213     unsigned getVectorFactor() const {
2214       if (!ReuseShuffleIndices.empty())
2215         return ReuseShuffleIndices.size();
2216       return Scalars.size();
2217     };
2218 
2219     /// A vector of scalars.
2220     ValueList Scalars;
2221 
2222     /// The Scalars are vectorized into this value. It is initialized to Null.
2223     Value *VectorizedValue = nullptr;
2224 
2225     /// Do we need to gather this sequence or vectorize it
2226     /// (either with vector instruction or with scatter/gather
2227     /// intrinsics for store/load)?
2228     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2229     EntryState State;
2230 
2231     /// Does this sequence require some shuffling?
2232     SmallVector<int, 4> ReuseShuffleIndices;
2233 
2234     /// Does this entry require reordering?
2235     SmallVector<unsigned, 4> ReorderIndices;
2236 
2237     /// Points back to the VectorizableTree.
2238     ///
2239     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2240     /// to be a pointer and needs to be able to initialize the child iterator.
2241     /// Thus we need a reference back to the container to translate the indices
2242     /// to entries.
2243     VecTreeTy &Container;
2244 
2245     /// The TreeEntry index containing the user of this entry.  We can actually
2246     /// have multiple users so the data structure is not truly a tree.
2247     SmallVector<EdgeInfo, 1> UserTreeIndices;
2248 
2249     /// The index of this treeEntry in VectorizableTree.
2250     int Idx = -1;
2251 
2252   private:
2253     /// The operands of each instruction in each lane Operands[op_index][lane].
2254     /// Note: This helps avoid the replication of the code that performs the
2255     /// reordering of operands during buildTree_rec() and vectorizeTree().
2256     SmallVector<ValueList, 2> Operands;
2257 
2258     /// The main/alternate instruction.
2259     Instruction *MainOp = nullptr;
2260     Instruction *AltOp = nullptr;
2261 
2262   public:
2263     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2264     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2265       if (Operands.size() < OpIdx + 1)
2266         Operands.resize(OpIdx + 1);
2267       assert(Operands[OpIdx].empty() && "Already resized?");
2268       assert(OpVL.size() <= Scalars.size() &&
2269              "Number of operands is greater than the number of scalars.");
2270       Operands[OpIdx].resize(OpVL.size());
2271       copy(OpVL, Operands[OpIdx].begin());
2272     }
2273 
2274     /// Set the operands of this bundle in their original order.
2275     void setOperandsInOrder() {
2276       assert(Operands.empty() && "Already initialized?");
2277       auto *I0 = cast<Instruction>(Scalars[0]);
2278       Operands.resize(I0->getNumOperands());
2279       unsigned NumLanes = Scalars.size();
2280       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2281            OpIdx != NumOperands; ++OpIdx) {
2282         Operands[OpIdx].resize(NumLanes);
2283         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2284           auto *I = cast<Instruction>(Scalars[Lane]);
2285           assert(I->getNumOperands() == NumOperands &&
2286                  "Expected same number of operands");
2287           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2288         }
2289       }
2290     }
2291 
2292     /// Reorders operands of the node to the given mask \p Mask.
2293     void reorderOperands(ArrayRef<int> Mask) {
2294       for (ValueList &Operand : Operands)
2295         reorderScalars(Operand, Mask);
2296     }
2297 
2298     /// \returns the \p OpIdx operand of this TreeEntry.
2299     ValueList &getOperand(unsigned OpIdx) {
2300       assert(OpIdx < Operands.size() && "Off bounds");
2301       return Operands[OpIdx];
2302     }
2303 
2304     /// \returns the \p OpIdx operand of this TreeEntry.
2305     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2306       assert(OpIdx < Operands.size() && "Off bounds");
2307       return Operands[OpIdx];
2308     }
2309 
2310     /// \returns the number of operands.
2311     unsigned getNumOperands() const { return Operands.size(); }
2312 
2313     /// \return the single \p OpIdx operand.
2314     Value *getSingleOperand(unsigned OpIdx) const {
2315       assert(OpIdx < Operands.size() && "Off bounds");
2316       assert(!Operands[OpIdx].empty() && "No operand available");
2317       return Operands[OpIdx][0];
2318     }
2319 
2320     /// Some of the instructions in the list have alternate opcodes.
2321     bool isAltShuffle() const { return MainOp != AltOp; }
2322 
2323     bool isOpcodeOrAlt(Instruction *I) const {
2324       unsigned CheckedOpcode = I->getOpcode();
2325       return (getOpcode() == CheckedOpcode ||
2326               getAltOpcode() == CheckedOpcode);
2327     }
2328 
2329     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2330     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2331     /// \p OpValue.
2332     Value *isOneOf(Value *Op) const {
2333       auto *I = dyn_cast<Instruction>(Op);
2334       if (I && isOpcodeOrAlt(I))
2335         return Op;
2336       return MainOp;
2337     }
2338 
2339     void setOperations(const InstructionsState &S) {
2340       MainOp = S.MainOp;
2341       AltOp = S.AltOp;
2342     }
2343 
2344     Instruction *getMainOp() const {
2345       return MainOp;
2346     }
2347 
2348     Instruction *getAltOp() const {
2349       return AltOp;
2350     }
2351 
2352     /// The main/alternate opcodes for the list of instructions.
2353     unsigned getOpcode() const {
2354       return MainOp ? MainOp->getOpcode() : 0;
2355     }
2356 
2357     unsigned getAltOpcode() const {
2358       return AltOp ? AltOp->getOpcode() : 0;
2359     }
2360 
2361     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2362     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2363     int findLaneForValue(Value *V) const {
2364       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2365       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2366       if (!ReorderIndices.empty())
2367         FoundLane = ReorderIndices[FoundLane];
2368       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2369       if (!ReuseShuffleIndices.empty()) {
2370         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2371                                   find(ReuseShuffleIndices, FoundLane));
2372       }
2373       return FoundLane;
2374     }
2375 
2376 #ifndef NDEBUG
2377     /// Debug printer.
2378     LLVM_DUMP_METHOD void dump() const {
2379       dbgs() << Idx << ".\n";
2380       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2381         dbgs() << "Operand " << OpI << ":\n";
2382         for (const Value *V : Operands[OpI])
2383           dbgs().indent(2) << *V << "\n";
2384       }
2385       dbgs() << "Scalars: \n";
2386       for (Value *V : Scalars)
2387         dbgs().indent(2) << *V << "\n";
2388       dbgs() << "State: ";
2389       switch (State) {
2390       case Vectorize:
2391         dbgs() << "Vectorize\n";
2392         break;
2393       case ScatterVectorize:
2394         dbgs() << "ScatterVectorize\n";
2395         break;
2396       case NeedToGather:
2397         dbgs() << "NeedToGather\n";
2398         break;
2399       }
2400       dbgs() << "MainOp: ";
2401       if (MainOp)
2402         dbgs() << *MainOp << "\n";
2403       else
2404         dbgs() << "NULL\n";
2405       dbgs() << "AltOp: ";
2406       if (AltOp)
2407         dbgs() << *AltOp << "\n";
2408       else
2409         dbgs() << "NULL\n";
2410       dbgs() << "VectorizedValue: ";
2411       if (VectorizedValue)
2412         dbgs() << *VectorizedValue << "\n";
2413       else
2414         dbgs() << "NULL\n";
2415       dbgs() << "ReuseShuffleIndices: ";
2416       if (ReuseShuffleIndices.empty())
2417         dbgs() << "Empty";
2418       else
2419         for (int ReuseIdx : ReuseShuffleIndices)
2420           dbgs() << ReuseIdx << ", ";
2421       dbgs() << "\n";
2422       dbgs() << "ReorderIndices: ";
2423       for (unsigned ReorderIdx : ReorderIndices)
2424         dbgs() << ReorderIdx << ", ";
2425       dbgs() << "\n";
2426       dbgs() << "UserTreeIndices: ";
2427       for (const auto &EInfo : UserTreeIndices)
2428         dbgs() << EInfo << ", ";
2429       dbgs() << "\n";
2430     }
2431 #endif
2432   };
2433 
2434 #ifndef NDEBUG
2435   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2436                      InstructionCost VecCost,
2437                      InstructionCost ScalarCost) const {
2438     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2439     dbgs() << "SLP: Costs:\n";
2440     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2441     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2442     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2443     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2444                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2445   }
2446 #endif
2447 
2448   /// Create a new VectorizableTree entry.
2449   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2450                           const InstructionsState &S,
2451                           const EdgeInfo &UserTreeIdx,
2452                           ArrayRef<int> ReuseShuffleIndices = None,
2453                           ArrayRef<unsigned> ReorderIndices = None) {
2454     TreeEntry::EntryState EntryState =
2455         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2456     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2457                         ReuseShuffleIndices, ReorderIndices);
2458   }
2459 
2460   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2461                           TreeEntry::EntryState EntryState,
2462                           Optional<ScheduleData *> Bundle,
2463                           const InstructionsState &S,
2464                           const EdgeInfo &UserTreeIdx,
2465                           ArrayRef<int> ReuseShuffleIndices = None,
2466                           ArrayRef<unsigned> ReorderIndices = None) {
2467     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2468             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2469            "Need to vectorize gather entry?");
2470     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2471     TreeEntry *Last = VectorizableTree.back().get();
2472     Last->Idx = VectorizableTree.size() - 1;
2473     Last->State = EntryState;
2474     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2475                                      ReuseShuffleIndices.end());
2476     if (ReorderIndices.empty()) {
2477       Last->Scalars.assign(VL.begin(), VL.end());
2478       Last->setOperations(S);
2479     } else {
2480       // Reorder scalars and build final mask.
2481       Last->Scalars.assign(VL.size(), nullptr);
2482       transform(ReorderIndices, Last->Scalars.begin(),
2483                 [VL](unsigned Idx) -> Value * {
2484                   if (Idx >= VL.size())
2485                     return UndefValue::get(VL.front()->getType());
2486                   return VL[Idx];
2487                 });
2488       InstructionsState S = getSameOpcode(Last->Scalars);
2489       Last->setOperations(S);
2490       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2491     }
2492     if (Last->State != TreeEntry::NeedToGather) {
2493       for (Value *V : VL) {
2494         assert(!getTreeEntry(V) && "Scalar already in tree!");
2495         ScalarToTreeEntry[V] = Last;
2496       }
2497       // Update the scheduler bundle to point to this TreeEntry.
2498       ScheduleData *BundleMember = Bundle.getValue();
2499       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2500               isVectorLikeInstWithConstOps(S.MainOp) ||
2501               doesNotNeedToSchedule(VL)) &&
2502              "Bundle and VL out of sync");
2503       if (BundleMember) {
2504         for (Value *V : VL) {
2505           if (doesNotNeedToBeScheduled(V))
2506             continue;
2507           assert(BundleMember && "Unexpected end of bundle.");
2508           BundleMember->TE = Last;
2509           BundleMember = BundleMember->NextInBundle;
2510         }
2511       }
2512       assert(!BundleMember && "Bundle and VL out of sync");
2513     } else {
2514       MustGather.insert(VL.begin(), VL.end());
2515     }
2516 
2517     if (UserTreeIdx.UserTE)
2518       Last->UserTreeIndices.push_back(UserTreeIdx);
2519 
2520     return Last;
2521   }
2522 
2523   /// -- Vectorization State --
2524   /// Holds all of the tree entries.
2525   TreeEntry::VecTreeTy VectorizableTree;
2526 
2527 #ifndef NDEBUG
2528   /// Debug printer.
2529   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2530     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2531       VectorizableTree[Id]->dump();
2532       dbgs() << "\n";
2533     }
2534   }
2535 #endif
2536 
2537   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2538 
2539   const TreeEntry *getTreeEntry(Value *V) const {
2540     return ScalarToTreeEntry.lookup(V);
2541   }
2542 
2543   /// Maps a specific scalar to its tree entry.
2544   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2545 
2546   /// Maps a value to the proposed vectorizable size.
2547   SmallDenseMap<Value *, unsigned> InstrElementSize;
2548 
2549   /// A list of scalars that we found that we need to keep as scalars.
2550   ValueSet MustGather;
2551 
2552   /// This POD struct describes one external user in the vectorized tree.
2553   struct ExternalUser {
2554     ExternalUser(Value *S, llvm::User *U, int L)
2555         : Scalar(S), User(U), Lane(L) {}
2556 
2557     // Which scalar in our function.
2558     Value *Scalar;
2559 
2560     // Which user that uses the scalar.
2561     llvm::User *User;
2562 
2563     // Which lane does the scalar belong to.
2564     int Lane;
2565   };
2566   using UserList = SmallVector<ExternalUser, 16>;
2567 
2568   /// Checks if two instructions may access the same memory.
2569   ///
2570   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2571   /// is invariant in the calling loop.
2572   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2573                  Instruction *Inst2) {
2574     // First check if the result is already in the cache.
2575     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2576     Optional<bool> &result = AliasCache[key];
2577     if (result.hasValue()) {
2578       return result.getValue();
2579     }
2580     bool aliased = true;
2581     if (Loc1.Ptr && isSimple(Inst1))
2582       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2583     // Store the result in the cache.
2584     result = aliased;
2585     return aliased;
2586   }
2587 
2588   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2589 
2590   /// Cache for alias results.
2591   /// TODO: consider moving this to the AliasAnalysis itself.
2592   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2593 
2594   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2595   // globally through SLP because we don't perform any action which
2596   // invalidates capture results.
2597   BatchAAResults BatchAA;
2598 
2599   /// Temporary store for deleted instructions. Instructions will be deleted
2600   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2601   /// ensure that there are no incorrect collisions in the AliasCache, which
2602   /// can happen if a new instruction is allocated at the same address as a
2603   /// previously deleted instruction.
2604   DenseSet<Instruction *> DeletedInstructions;
2605 
2606   /// A list of values that need to extracted out of the tree.
2607   /// This list holds pairs of (Internal Scalar : External User). External User
2608   /// can be nullptr, it means that this Internal Scalar will be used later,
2609   /// after vectorization.
2610   UserList ExternalUses;
2611 
2612   /// Values used only by @llvm.assume calls.
2613   SmallPtrSet<const Value *, 32> EphValues;
2614 
2615   /// Holds all of the instructions that we gathered.
2616   SetVector<Instruction *> GatherShuffleSeq;
2617 
2618   /// A list of blocks that we are going to CSE.
2619   SetVector<BasicBlock *> CSEBlocks;
2620 
2621   /// Contains all scheduling relevant data for an instruction.
2622   /// A ScheduleData either represents a single instruction or a member of an
2623   /// instruction bundle (= a group of instructions which is combined into a
2624   /// vector instruction).
2625   struct ScheduleData {
2626     // The initial value for the dependency counters. It means that the
2627     // dependencies are not calculated yet.
2628     enum { InvalidDeps = -1 };
2629 
2630     ScheduleData() = default;
2631 
2632     void init(int BlockSchedulingRegionID, Value *OpVal) {
2633       FirstInBundle = this;
2634       NextInBundle = nullptr;
2635       NextLoadStore = nullptr;
2636       IsScheduled = false;
2637       SchedulingRegionID = BlockSchedulingRegionID;
2638       clearDependencies();
2639       OpValue = OpVal;
2640       TE = nullptr;
2641     }
2642 
2643     /// Verify basic self consistency properties
2644     void verify() {
2645       if (hasValidDependencies()) {
2646         assert(UnscheduledDeps <= Dependencies && "invariant");
2647       } else {
2648         assert(UnscheduledDeps == Dependencies && "invariant");
2649       }
2650 
2651       if (IsScheduled) {
2652         assert(isSchedulingEntity() &&
2653                 "unexpected scheduled state");
2654         for (const ScheduleData *BundleMember = this; BundleMember;
2655              BundleMember = BundleMember->NextInBundle) {
2656           assert(BundleMember->hasValidDependencies() &&
2657                  BundleMember->UnscheduledDeps == 0 &&
2658                  "unexpected scheduled state");
2659           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2660                  "only bundle is marked scheduled");
2661         }
2662       }
2663 
2664       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2665              "all bundle members must be in same basic block");
2666     }
2667 
2668     /// Returns true if the dependency information has been calculated.
2669     /// Note that depenendency validity can vary between instructions within
2670     /// a single bundle.
2671     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2672 
2673     /// Returns true for single instructions and for bundle representatives
2674     /// (= the head of a bundle).
2675     bool isSchedulingEntity() const { return FirstInBundle == this; }
2676 
2677     /// Returns true if it represents an instruction bundle and not only a
2678     /// single instruction.
2679     bool isPartOfBundle() const {
2680       return NextInBundle != nullptr || FirstInBundle != this || TE;
2681     }
2682 
2683     /// Returns true if it is ready for scheduling, i.e. it has no more
2684     /// unscheduled depending instructions/bundles.
2685     bool isReady() const {
2686       assert(isSchedulingEntity() &&
2687              "can't consider non-scheduling entity for ready list");
2688       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2689     }
2690 
2691     /// Modifies the number of unscheduled dependencies for this instruction,
2692     /// and returns the number of remaining dependencies for the containing
2693     /// bundle.
2694     int incrementUnscheduledDeps(int Incr) {
2695       assert(hasValidDependencies() &&
2696              "increment of unscheduled deps would be meaningless");
2697       UnscheduledDeps += Incr;
2698       return FirstInBundle->unscheduledDepsInBundle();
2699     }
2700 
2701     /// Sets the number of unscheduled dependencies to the number of
2702     /// dependencies.
2703     void resetUnscheduledDeps() {
2704       UnscheduledDeps = Dependencies;
2705     }
2706 
2707     /// Clears all dependency information.
2708     void clearDependencies() {
2709       Dependencies = InvalidDeps;
2710       resetUnscheduledDeps();
2711       MemoryDependencies.clear();
2712       ControlDependencies.clear();
2713     }
2714 
2715     int unscheduledDepsInBundle() const {
2716       assert(isSchedulingEntity() && "only meaningful on the bundle");
2717       int Sum = 0;
2718       for (const ScheduleData *BundleMember = this; BundleMember;
2719            BundleMember = BundleMember->NextInBundle) {
2720         if (BundleMember->UnscheduledDeps == InvalidDeps)
2721           return InvalidDeps;
2722         Sum += BundleMember->UnscheduledDeps;
2723       }
2724       return Sum;
2725     }
2726 
2727     void dump(raw_ostream &os) const {
2728       if (!isSchedulingEntity()) {
2729         os << "/ " << *Inst;
2730       } else if (NextInBundle) {
2731         os << '[' << *Inst;
2732         ScheduleData *SD = NextInBundle;
2733         while (SD) {
2734           os << ';' << *SD->Inst;
2735           SD = SD->NextInBundle;
2736         }
2737         os << ']';
2738       } else {
2739         os << *Inst;
2740       }
2741     }
2742 
2743     Instruction *Inst = nullptr;
2744 
2745     /// Opcode of the current instruction in the schedule data.
2746     Value *OpValue = nullptr;
2747 
2748     /// The TreeEntry that this instruction corresponds to.
2749     TreeEntry *TE = nullptr;
2750 
2751     /// Points to the head in an instruction bundle (and always to this for
2752     /// single instructions).
2753     ScheduleData *FirstInBundle = nullptr;
2754 
2755     /// Single linked list of all instructions in a bundle. Null if it is a
2756     /// single instruction.
2757     ScheduleData *NextInBundle = nullptr;
2758 
2759     /// Single linked list of all memory instructions (e.g. load, store, call)
2760     /// in the block - until the end of the scheduling region.
2761     ScheduleData *NextLoadStore = nullptr;
2762 
2763     /// The dependent memory instructions.
2764     /// This list is derived on demand in calculateDependencies().
2765     SmallVector<ScheduleData *, 4> MemoryDependencies;
2766 
2767     /// List of instructions which this instruction could be control dependent
2768     /// on.  Allowing such nodes to be scheduled below this one could introduce
2769     /// a runtime fault which didn't exist in the original program.
2770     /// ex: this is a load or udiv following a readonly call which inf loops
2771     SmallVector<ScheduleData *, 4> ControlDependencies;
2772 
2773     /// This ScheduleData is in the current scheduling region if this matches
2774     /// the current SchedulingRegionID of BlockScheduling.
2775     int SchedulingRegionID = 0;
2776 
2777     /// Used for getting a "good" final ordering of instructions.
2778     int SchedulingPriority = 0;
2779 
2780     /// The number of dependencies. Constitutes of the number of users of the
2781     /// instruction plus the number of dependent memory instructions (if any).
2782     /// This value is calculated on demand.
2783     /// If InvalidDeps, the number of dependencies is not calculated yet.
2784     int Dependencies = InvalidDeps;
2785 
2786     /// The number of dependencies minus the number of dependencies of scheduled
2787     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2788     /// for scheduling.
2789     /// Note that this is negative as long as Dependencies is not calculated.
2790     int UnscheduledDeps = InvalidDeps;
2791 
2792     /// True if this instruction is scheduled (or considered as scheduled in the
2793     /// dry-run).
2794     bool IsScheduled = false;
2795   };
2796 
2797 #ifndef NDEBUG
2798   friend inline raw_ostream &operator<<(raw_ostream &os,
2799                                         const BoUpSLP::ScheduleData &SD) {
2800     SD.dump(os);
2801     return os;
2802   }
2803 #endif
2804 
2805   friend struct GraphTraits<BoUpSLP *>;
2806   friend struct DOTGraphTraits<BoUpSLP *>;
2807 
2808   /// Contains all scheduling data for a basic block.
2809   /// It does not schedules instructions, which are not memory read/write
2810   /// instructions and their operands are either constants, or arguments, or
2811   /// phis, or instructions from others blocks, or their users are phis or from
2812   /// the other blocks. The resulting vector instructions can be placed at the
2813   /// beginning of the basic block without scheduling (if operands does not need
2814   /// to be scheduled) or at the end of the block (if users are outside of the
2815   /// block). It allows to save some compile time and memory used by the
2816   /// compiler.
2817   /// ScheduleData is assigned for each instruction in between the boundaries of
2818   /// the tree entry, even for those, which are not part of the graph. It is
2819   /// required to correctly follow the dependencies between the instructions and
2820   /// their correct scheduling. The ScheduleData is not allocated for the
2821   /// instructions, which do not require scheduling, like phis, nodes with
2822   /// extractelements/insertelements only or nodes with instructions, with
2823   /// uses/operands outside of the block.
2824   struct BlockScheduling {
2825     BlockScheduling(BasicBlock *BB)
2826         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2827 
2828     void clear() {
2829       ReadyInsts.clear();
2830       ScheduleStart = nullptr;
2831       ScheduleEnd = nullptr;
2832       FirstLoadStoreInRegion = nullptr;
2833       LastLoadStoreInRegion = nullptr;
2834       RegionHasStackSave = false;
2835 
2836       // Reduce the maximum schedule region size by the size of the
2837       // previous scheduling run.
2838       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2839       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2840         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2841       ScheduleRegionSize = 0;
2842 
2843       // Make a new scheduling region, i.e. all existing ScheduleData is not
2844       // in the new region yet.
2845       ++SchedulingRegionID;
2846     }
2847 
2848     ScheduleData *getScheduleData(Instruction *I) {
2849       if (BB != I->getParent())
2850         // Avoid lookup if can't possibly be in map.
2851         return nullptr;
2852       ScheduleData *SD = ScheduleDataMap.lookup(I);
2853       if (SD && isInSchedulingRegion(SD))
2854         return SD;
2855       return nullptr;
2856     }
2857 
2858     ScheduleData *getScheduleData(Value *V) {
2859       if (auto *I = dyn_cast<Instruction>(V))
2860         return getScheduleData(I);
2861       return nullptr;
2862     }
2863 
2864     ScheduleData *getScheduleData(Value *V, Value *Key) {
2865       if (V == Key)
2866         return getScheduleData(V);
2867       auto I = ExtraScheduleDataMap.find(V);
2868       if (I != ExtraScheduleDataMap.end()) {
2869         ScheduleData *SD = I->second.lookup(Key);
2870         if (SD && isInSchedulingRegion(SD))
2871           return SD;
2872       }
2873       return nullptr;
2874     }
2875 
2876     bool isInSchedulingRegion(ScheduleData *SD) const {
2877       return SD->SchedulingRegionID == SchedulingRegionID;
2878     }
2879 
2880     /// Marks an instruction as scheduled and puts all dependent ready
2881     /// instructions into the ready-list.
2882     template <typename ReadyListType>
2883     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2884       SD->IsScheduled = true;
2885       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2886 
2887       for (ScheduleData *BundleMember = SD; BundleMember;
2888            BundleMember = BundleMember->NextInBundle) {
2889         if (BundleMember->Inst != BundleMember->OpValue)
2890           continue;
2891 
2892         // Handle the def-use chain dependencies.
2893 
2894         // Decrement the unscheduled counter and insert to ready list if ready.
2895         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2896           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2897             if (OpDef && OpDef->hasValidDependencies() &&
2898                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2899               // There are no more unscheduled dependencies after
2900               // decrementing, so we can put the dependent instruction
2901               // into the ready list.
2902               ScheduleData *DepBundle = OpDef->FirstInBundle;
2903               assert(!DepBundle->IsScheduled &&
2904                      "already scheduled bundle gets ready");
2905               ReadyList.insert(DepBundle);
2906               LLVM_DEBUG(dbgs()
2907                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2908             }
2909           });
2910         };
2911 
2912         // If BundleMember is a vector bundle, its operands may have been
2913         // reordered during buildTree(). We therefore need to get its operands
2914         // through the TreeEntry.
2915         if (TreeEntry *TE = BundleMember->TE) {
2916           // Need to search for the lane since the tree entry can be reordered.
2917           int Lane = std::distance(TE->Scalars.begin(),
2918                                    find(TE->Scalars, BundleMember->Inst));
2919           assert(Lane >= 0 && "Lane not set");
2920 
2921           // Since vectorization tree is being built recursively this assertion
2922           // ensures that the tree entry has all operands set before reaching
2923           // this code. Couple of exceptions known at the moment are extracts
2924           // where their second (immediate) operand is not added. Since
2925           // immediates do not affect scheduler behavior this is considered
2926           // okay.
2927           auto *In = BundleMember->Inst;
2928           assert(In &&
2929                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2930                   In->getNumOperands() == TE->getNumOperands()) &&
2931                  "Missed TreeEntry operands?");
2932           (void)In; // fake use to avoid build failure when assertions disabled
2933 
2934           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2935                OpIdx != NumOperands; ++OpIdx)
2936             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2937               DecrUnsched(I);
2938         } else {
2939           // If BundleMember is a stand-alone instruction, no operand reordering
2940           // has taken place, so we directly access its operands.
2941           for (Use &U : BundleMember->Inst->operands())
2942             if (auto *I = dyn_cast<Instruction>(U.get()))
2943               DecrUnsched(I);
2944         }
2945         // Handle the memory dependencies.
2946         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2947           if (MemoryDepSD->hasValidDependencies() &&
2948               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2949             // There are no more unscheduled dependencies after decrementing,
2950             // so we can put the dependent instruction into the ready list.
2951             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2952             assert(!DepBundle->IsScheduled &&
2953                    "already scheduled bundle gets ready");
2954             ReadyList.insert(DepBundle);
2955             LLVM_DEBUG(dbgs()
2956                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2957           }
2958         }
2959         // Handle the control dependencies.
2960         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2961           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2962             // There are no more unscheduled dependencies after decrementing,
2963             // so we can put the dependent instruction into the ready list.
2964             ScheduleData *DepBundle = DepSD->FirstInBundle;
2965             assert(!DepBundle->IsScheduled &&
2966                    "already scheduled bundle gets ready");
2967             ReadyList.insert(DepBundle);
2968             LLVM_DEBUG(dbgs()
2969                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2970           }
2971         }
2972 
2973       }
2974     }
2975 
2976     /// Verify basic self consistency properties of the data structure.
2977     void verify() {
2978       if (!ScheduleStart)
2979         return;
2980 
2981       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2982              ScheduleStart->comesBefore(ScheduleEnd) &&
2983              "Not a valid scheduling region?");
2984 
2985       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2986         auto *SD = getScheduleData(I);
2987         if (!SD)
2988           continue;
2989         assert(isInSchedulingRegion(SD) &&
2990                "primary schedule data not in window?");
2991         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2992                "entire bundle in window!");
2993         (void)SD;
2994         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2995       }
2996 
2997       for (auto *SD : ReadyInsts) {
2998         assert(SD->isSchedulingEntity() && SD->isReady() &&
2999                "item in ready list not ready?");
3000         (void)SD;
3001       }
3002     }
3003 
3004     void doForAllOpcodes(Value *V,
3005                          function_ref<void(ScheduleData *SD)> Action) {
3006       if (ScheduleData *SD = getScheduleData(V))
3007         Action(SD);
3008       auto I = ExtraScheduleDataMap.find(V);
3009       if (I != ExtraScheduleDataMap.end())
3010         for (auto &P : I->second)
3011           if (isInSchedulingRegion(P.second))
3012             Action(P.second);
3013     }
3014 
3015     /// Put all instructions into the ReadyList which are ready for scheduling.
3016     template <typename ReadyListType>
3017     void initialFillReadyList(ReadyListType &ReadyList) {
3018       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3019         doForAllOpcodes(I, [&](ScheduleData *SD) {
3020           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3021               SD->isReady()) {
3022             ReadyList.insert(SD);
3023             LLVM_DEBUG(dbgs()
3024                        << "SLP:    initially in ready list: " << *SD << "\n");
3025           }
3026         });
3027       }
3028     }
3029 
3030     /// Build a bundle from the ScheduleData nodes corresponding to the
3031     /// scalar instruction for each lane.
3032     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3033 
3034     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3035     /// cyclic dependencies. This is only a dry-run, no instructions are
3036     /// actually moved at this stage.
3037     /// \returns the scheduling bundle. The returned Optional value is non-None
3038     /// if \p VL is allowed to be scheduled.
3039     Optional<ScheduleData *>
3040     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3041                       const InstructionsState &S);
3042 
3043     /// Un-bundles a group of instructions.
3044     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3045 
3046     /// Allocates schedule data chunk.
3047     ScheduleData *allocateScheduleDataChunks();
3048 
3049     /// Extends the scheduling region so that V is inside the region.
3050     /// \returns true if the region size is within the limit.
3051     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3052 
3053     /// Initialize the ScheduleData structures for new instructions in the
3054     /// scheduling region.
3055     void initScheduleData(Instruction *FromI, Instruction *ToI,
3056                           ScheduleData *PrevLoadStore,
3057                           ScheduleData *NextLoadStore);
3058 
3059     /// Updates the dependency information of a bundle and of all instructions/
3060     /// bundles which depend on the original bundle.
3061     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3062                                BoUpSLP *SLP);
3063 
3064     /// Sets all instruction in the scheduling region to un-scheduled.
3065     void resetSchedule();
3066 
3067     BasicBlock *BB;
3068 
3069     /// Simple memory allocation for ScheduleData.
3070     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3071 
3072     /// The size of a ScheduleData array in ScheduleDataChunks.
3073     int ChunkSize;
3074 
3075     /// The allocator position in the current chunk, which is the last entry
3076     /// of ScheduleDataChunks.
3077     int ChunkPos;
3078 
3079     /// Attaches ScheduleData to Instruction.
3080     /// Note that the mapping survives during all vectorization iterations, i.e.
3081     /// ScheduleData structures are recycled.
3082     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3083 
3084     /// Attaches ScheduleData to Instruction with the leading key.
3085     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3086         ExtraScheduleDataMap;
3087 
3088     /// The ready-list for scheduling (only used for the dry-run).
3089     SetVector<ScheduleData *> ReadyInsts;
3090 
3091     /// The first instruction of the scheduling region.
3092     Instruction *ScheduleStart = nullptr;
3093 
3094     /// The first instruction _after_ the scheduling region.
3095     Instruction *ScheduleEnd = nullptr;
3096 
3097     /// The first memory accessing instruction in the scheduling region
3098     /// (can be null).
3099     ScheduleData *FirstLoadStoreInRegion = nullptr;
3100 
3101     /// The last memory accessing instruction in the scheduling region
3102     /// (can be null).
3103     ScheduleData *LastLoadStoreInRegion = nullptr;
3104 
3105     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3106     /// region?  Used to optimize the dependence calculation for the
3107     /// common case where there isn't.
3108     bool RegionHasStackSave = false;
3109 
3110     /// The current size of the scheduling region.
3111     int ScheduleRegionSize = 0;
3112 
3113     /// The maximum size allowed for the scheduling region.
3114     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3115 
3116     /// The ID of the scheduling region. For a new vectorization iteration this
3117     /// is incremented which "removes" all ScheduleData from the region.
3118     /// Make sure that the initial SchedulingRegionID is greater than the
3119     /// initial SchedulingRegionID in ScheduleData (which is 0).
3120     int SchedulingRegionID = 1;
3121   };
3122 
3123   /// Attaches the BlockScheduling structures to basic blocks.
3124   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3125 
3126   /// Performs the "real" scheduling. Done before vectorization is actually
3127   /// performed in a basic block.
3128   void scheduleBlock(BlockScheduling *BS);
3129 
3130   /// List of users to ignore during scheduling and that don't need extracting.
3131   ArrayRef<Value *> UserIgnoreList;
3132 
3133   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3134   /// sorted SmallVectors of unsigned.
3135   struct OrdersTypeDenseMapInfo {
3136     static OrdersType getEmptyKey() {
3137       OrdersType V;
3138       V.push_back(~1U);
3139       return V;
3140     }
3141 
3142     static OrdersType getTombstoneKey() {
3143       OrdersType V;
3144       V.push_back(~2U);
3145       return V;
3146     }
3147 
3148     static unsigned getHashValue(const OrdersType &V) {
3149       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3150     }
3151 
3152     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3153       return LHS == RHS;
3154     }
3155   };
3156 
3157   // Analysis and block reference.
3158   Function *F;
3159   ScalarEvolution *SE;
3160   TargetTransformInfo *TTI;
3161   TargetLibraryInfo *TLI;
3162   LoopInfo *LI;
3163   DominatorTree *DT;
3164   AssumptionCache *AC;
3165   DemandedBits *DB;
3166   const DataLayout *DL;
3167   OptimizationRemarkEmitter *ORE;
3168 
3169   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3170   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3171 
3172   /// Instruction builder to construct the vectorized tree.
3173   IRBuilder<> Builder;
3174 
3175   /// A map of scalar integer values to the smallest bit width with which they
3176   /// can legally be represented. The values map to (width, signed) pairs,
3177   /// where "width" indicates the minimum bit width and "signed" is True if the
3178   /// value must be signed-extended, rather than zero-extended, back to its
3179   /// original width.
3180   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3181 };
3182 
3183 } // end namespace slpvectorizer
3184 
3185 template <> struct GraphTraits<BoUpSLP *> {
3186   using TreeEntry = BoUpSLP::TreeEntry;
3187 
3188   /// NodeRef has to be a pointer per the GraphWriter.
3189   using NodeRef = TreeEntry *;
3190 
3191   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3192 
3193   /// Add the VectorizableTree to the index iterator to be able to return
3194   /// TreeEntry pointers.
3195   struct ChildIteratorType
3196       : public iterator_adaptor_base<
3197             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3198     ContainerTy &VectorizableTree;
3199 
3200     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3201                       ContainerTy &VT)
3202         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3203 
3204     NodeRef operator*() { return I->UserTE; }
3205   };
3206 
3207   static NodeRef getEntryNode(BoUpSLP &R) {
3208     return R.VectorizableTree[0].get();
3209   }
3210 
3211   static ChildIteratorType child_begin(NodeRef N) {
3212     return {N->UserTreeIndices.begin(), N->Container};
3213   }
3214 
3215   static ChildIteratorType child_end(NodeRef N) {
3216     return {N->UserTreeIndices.end(), N->Container};
3217   }
3218 
3219   /// For the node iterator we just need to turn the TreeEntry iterator into a
3220   /// TreeEntry* iterator so that it dereferences to NodeRef.
3221   class nodes_iterator {
3222     using ItTy = ContainerTy::iterator;
3223     ItTy It;
3224 
3225   public:
3226     nodes_iterator(const ItTy &It2) : It(It2) {}
3227     NodeRef operator*() { return It->get(); }
3228     nodes_iterator operator++() {
3229       ++It;
3230       return *this;
3231     }
3232     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3233   };
3234 
3235   static nodes_iterator nodes_begin(BoUpSLP *R) {
3236     return nodes_iterator(R->VectorizableTree.begin());
3237   }
3238 
3239   static nodes_iterator nodes_end(BoUpSLP *R) {
3240     return nodes_iterator(R->VectorizableTree.end());
3241   }
3242 
3243   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3244 };
3245 
3246 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3247   using TreeEntry = BoUpSLP::TreeEntry;
3248 
3249   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3250 
3251   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3252     std::string Str;
3253     raw_string_ostream OS(Str);
3254     if (isSplat(Entry->Scalars))
3255       OS << "<splat> ";
3256     for (auto V : Entry->Scalars) {
3257       OS << *V;
3258       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3259             return EU.Scalar == V;
3260           }))
3261         OS << " <extract>";
3262       OS << "\n";
3263     }
3264     return Str;
3265   }
3266 
3267   static std::string getNodeAttributes(const TreeEntry *Entry,
3268                                        const BoUpSLP *) {
3269     if (Entry->State == TreeEntry::NeedToGather)
3270       return "color=red";
3271     return "";
3272   }
3273 };
3274 
3275 } // end namespace llvm
3276 
3277 BoUpSLP::~BoUpSLP() {
3278   SmallVector<WeakTrackingVH> DeadInsts;
3279   for (auto *I : DeletedInstructions) {
3280     for (Use &U : I->operands()) {
3281       auto *Op = dyn_cast<Instruction>(U.get());
3282       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3283           wouldInstructionBeTriviallyDead(Op, TLI))
3284         DeadInsts.emplace_back(Op);
3285     }
3286     I->dropAllReferences();
3287   }
3288   for (auto *I : DeletedInstructions) {
3289     assert(I->use_empty() &&
3290            "trying to erase instruction with users.");
3291     I->eraseFromParent();
3292   }
3293 
3294   // Cleanup any dead scalar code feeding the vectorized instructions
3295   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3296 
3297 #ifdef EXPENSIVE_CHECKS
3298   // If we could guarantee that this call is not extremely slow, we could
3299   // remove the ifdef limitation (see PR47712).
3300   assert(!verifyFunction(*F, &dbgs()));
3301 #endif
3302 }
3303 
3304 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3305 /// contains original mask for the scalars reused in the node. Procedure
3306 /// transform this mask in accordance with the given \p Mask.
3307 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3308   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3309          "Expected non-empty mask.");
3310   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3311   Prev.swap(Reuses);
3312   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3313     if (Mask[I] != UndefMaskElem)
3314       Reuses[Mask[I]] = Prev[I];
3315 }
3316 
3317 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3318 /// the original order of the scalars. Procedure transforms the provided order
3319 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3320 /// identity order, \p Order is cleared.
3321 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3322   assert(!Mask.empty() && "Expected non-empty mask.");
3323   SmallVector<int> MaskOrder;
3324   if (Order.empty()) {
3325     MaskOrder.resize(Mask.size());
3326     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3327   } else {
3328     inversePermutation(Order, MaskOrder);
3329   }
3330   reorderReuses(MaskOrder, Mask);
3331   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3332     Order.clear();
3333     return;
3334   }
3335   Order.assign(Mask.size(), Mask.size());
3336   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3337     if (MaskOrder[I] != UndefMaskElem)
3338       Order[MaskOrder[I]] = I;
3339   fixupOrderingIndices(Order);
3340 }
3341 
3342 Optional<BoUpSLP::OrdersType>
3343 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3344   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3345   unsigned NumScalars = TE.Scalars.size();
3346   OrdersType CurrentOrder(NumScalars, NumScalars);
3347   SmallVector<int> Positions;
3348   SmallBitVector UsedPositions(NumScalars);
3349   const TreeEntry *STE = nullptr;
3350   // Try to find all gathered scalars that are gets vectorized in other
3351   // vectorize node. Here we can have only one single tree vector node to
3352   // correctly identify order of the gathered scalars.
3353   for (unsigned I = 0; I < NumScalars; ++I) {
3354     Value *V = TE.Scalars[I];
3355     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3356       continue;
3357     if (const auto *LocalSTE = getTreeEntry(V)) {
3358       if (!STE)
3359         STE = LocalSTE;
3360       else if (STE != LocalSTE)
3361         // Take the order only from the single vector node.
3362         return None;
3363       unsigned Lane =
3364           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3365       if (Lane >= NumScalars)
3366         return None;
3367       if (CurrentOrder[Lane] != NumScalars) {
3368         if (Lane != I)
3369           continue;
3370         UsedPositions.reset(CurrentOrder[Lane]);
3371       }
3372       // The partial identity (where only some elements of the gather node are
3373       // in the identity order) is good.
3374       CurrentOrder[Lane] = I;
3375       UsedPositions.set(I);
3376     }
3377   }
3378   // Need to keep the order if we have a vector entry and at least 2 scalars or
3379   // the vectorized entry has just 2 scalars.
3380   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3381     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3382       for (unsigned I = 0; I < NumScalars; ++I)
3383         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3384           return false;
3385       return true;
3386     };
3387     if (IsIdentityOrder(CurrentOrder)) {
3388       CurrentOrder.clear();
3389       return CurrentOrder;
3390     }
3391     auto *It = CurrentOrder.begin();
3392     for (unsigned I = 0; I < NumScalars;) {
3393       if (UsedPositions.test(I)) {
3394         ++I;
3395         continue;
3396       }
3397       if (*It == NumScalars) {
3398         *It = I;
3399         ++I;
3400       }
3401       ++It;
3402     }
3403     return CurrentOrder;
3404   }
3405   return None;
3406 }
3407 
3408 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3409                                                          bool TopToBottom) {
3410   // No need to reorder if need to shuffle reuses, still need to shuffle the
3411   // node.
3412   if (!TE.ReuseShuffleIndices.empty())
3413     return None;
3414   if (TE.State == TreeEntry::Vectorize &&
3415       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3416        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3417       !TE.isAltShuffle())
3418     return TE.ReorderIndices;
3419   if (TE.State == TreeEntry::NeedToGather) {
3420     // TODO: add analysis of other gather nodes with extractelement
3421     // instructions and other values/instructions, not only undefs.
3422     if (((TE.getOpcode() == Instruction::ExtractElement &&
3423           !TE.isAltShuffle()) ||
3424          (all_of(TE.Scalars,
3425                  [](Value *V) {
3426                    return isa<UndefValue, ExtractElementInst>(V);
3427                  }) &&
3428           any_of(TE.Scalars,
3429                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3430         all_of(TE.Scalars,
3431                [](Value *V) {
3432                  auto *EE = dyn_cast<ExtractElementInst>(V);
3433                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3434                }) &&
3435         allSameType(TE.Scalars)) {
3436       // Check that gather of extractelements can be represented as
3437       // just a shuffle of a single vector.
3438       OrdersType CurrentOrder;
3439       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3440       if (Reuse || !CurrentOrder.empty()) {
3441         if (!CurrentOrder.empty())
3442           fixupOrderingIndices(CurrentOrder);
3443         return CurrentOrder;
3444       }
3445     }
3446     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3447       return CurrentOrder;
3448   }
3449   return None;
3450 }
3451 
3452 void BoUpSLP::reorderTopToBottom() {
3453   // Maps VF to the graph nodes.
3454   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3455   // ExtractElement gather nodes which can be vectorized and need to handle
3456   // their ordering.
3457   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3458   // Find all reorderable nodes with the given VF.
3459   // Currently the are vectorized stores,loads,extracts + some gathering of
3460   // extracts.
3461   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3462                                  const std::unique_ptr<TreeEntry> &TE) {
3463     if (Optional<OrdersType> CurrentOrder =
3464             getReorderingData(*TE, /*TopToBottom=*/true)) {
3465       // Do not include ordering for nodes used in the alt opcode vectorization,
3466       // better to reorder them during bottom-to-top stage. If follow the order
3467       // here, it causes reordering of the whole graph though actually it is
3468       // profitable just to reorder the subgraph that starts from the alternate
3469       // opcode vectorization node. Such nodes already end-up with the shuffle
3470       // instruction and it is just enough to change this shuffle rather than
3471       // rotate the scalars for the whole graph.
3472       unsigned Cnt = 0;
3473       const TreeEntry *UserTE = TE.get();
3474       while (UserTE && Cnt < RecursionMaxDepth) {
3475         if (UserTE->UserTreeIndices.size() != 1)
3476           break;
3477         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3478               return EI.UserTE->State == TreeEntry::Vectorize &&
3479                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3480             }))
3481           return;
3482         if (UserTE->UserTreeIndices.empty())
3483           UserTE = nullptr;
3484         else
3485           UserTE = UserTE->UserTreeIndices.back().UserTE;
3486         ++Cnt;
3487       }
3488       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3489       if (TE->State != TreeEntry::Vectorize)
3490         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3491     }
3492   });
3493 
3494   // Reorder the graph nodes according to their vectorization factor.
3495   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3496        VF /= 2) {
3497     auto It = VFToOrderedEntries.find(VF);
3498     if (It == VFToOrderedEntries.end())
3499       continue;
3500     // Try to find the most profitable order. We just are looking for the most
3501     // used order and reorder scalar elements in the nodes according to this
3502     // mostly used order.
3503     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3504     // All operands are reordered and used only in this node - propagate the
3505     // most used order to the user node.
3506     MapVector<OrdersType, unsigned,
3507               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3508         OrdersUses;
3509     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3510     for (const TreeEntry *OpTE : OrderedEntries) {
3511       // No need to reorder this nodes, still need to extend and to use shuffle,
3512       // just need to merge reordering shuffle and the reuse shuffle.
3513       if (!OpTE->ReuseShuffleIndices.empty())
3514         continue;
3515       // Count number of orders uses.
3516       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3517         if (OpTE->State == TreeEntry::NeedToGather)
3518           return GathersToOrders.find(OpTE)->second;
3519         return OpTE->ReorderIndices;
3520       }();
3521       // Stores actually store the mask, not the order, need to invert.
3522       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3523           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3524         SmallVector<int> Mask;
3525         inversePermutation(Order, Mask);
3526         unsigned E = Order.size();
3527         OrdersType CurrentOrder(E, E);
3528         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3529           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3530         });
3531         fixupOrderingIndices(CurrentOrder);
3532         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3533       } else {
3534         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3535       }
3536     }
3537     // Set order of the user node.
3538     if (OrdersUses.empty())
3539       continue;
3540     // Choose the most used order.
3541     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3542     unsigned Cnt = OrdersUses.front().second;
3543     for (const auto &Pair : drop_begin(OrdersUses)) {
3544       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3545         BestOrder = Pair.first;
3546         Cnt = Pair.second;
3547       }
3548     }
3549     // Set order of the user node.
3550     if (BestOrder.empty())
3551       continue;
3552     SmallVector<int> Mask;
3553     inversePermutation(BestOrder, Mask);
3554     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3555     unsigned E = BestOrder.size();
3556     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3557       return I < E ? static_cast<int>(I) : UndefMaskElem;
3558     });
3559     // Do an actual reordering, if profitable.
3560     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3561       // Just do the reordering for the nodes with the given VF.
3562       if (TE->Scalars.size() != VF) {
3563         if (TE->ReuseShuffleIndices.size() == VF) {
3564           // Need to reorder the reuses masks of the operands with smaller VF to
3565           // be able to find the match between the graph nodes and scalar
3566           // operands of the given node during vectorization/cost estimation.
3567           assert(all_of(TE->UserTreeIndices,
3568                         [VF, &TE](const EdgeInfo &EI) {
3569                           return EI.UserTE->Scalars.size() == VF ||
3570                                  EI.UserTE->Scalars.size() ==
3571                                      TE->Scalars.size();
3572                         }) &&
3573                  "All users must be of VF size.");
3574           // Update ordering of the operands with the smaller VF than the given
3575           // one.
3576           reorderReuses(TE->ReuseShuffleIndices, Mask);
3577         }
3578         continue;
3579       }
3580       if (TE->State == TreeEntry::Vectorize &&
3581           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3582               InsertElementInst>(TE->getMainOp()) &&
3583           !TE->isAltShuffle()) {
3584         // Build correct orders for extract{element,value}, loads and
3585         // stores.
3586         reorderOrder(TE->ReorderIndices, Mask);
3587         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3588           TE->reorderOperands(Mask);
3589       } else {
3590         // Reorder the node and its operands.
3591         TE->reorderOperands(Mask);
3592         assert(TE->ReorderIndices.empty() &&
3593                "Expected empty reorder sequence.");
3594         reorderScalars(TE->Scalars, Mask);
3595       }
3596       if (!TE->ReuseShuffleIndices.empty()) {
3597         // Apply reversed order to keep the original ordering of the reused
3598         // elements to avoid extra reorder indices shuffling.
3599         OrdersType CurrentOrder;
3600         reorderOrder(CurrentOrder, MaskOrder);
3601         SmallVector<int> NewReuses;
3602         inversePermutation(CurrentOrder, NewReuses);
3603         addMask(NewReuses, TE->ReuseShuffleIndices);
3604         TE->ReuseShuffleIndices.swap(NewReuses);
3605       }
3606     }
3607   }
3608 }
3609 
3610 bool BoUpSLP::canReorderOperands(
3611     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3612     ArrayRef<TreeEntry *> ReorderableGathers,
3613     SmallVectorImpl<TreeEntry *> &GatherOps) {
3614   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3615     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3616           return OpData.first == I &&
3617                  OpData.second->State == TreeEntry::Vectorize;
3618         }))
3619       continue;
3620     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3621       // Do not reorder if operand node is used by many user nodes.
3622       if (any_of(TE->UserTreeIndices,
3623                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3624         return false;
3625       // Add the node to the list of the ordered nodes with the identity
3626       // order.
3627       Edges.emplace_back(I, TE);
3628       continue;
3629     }
3630     ArrayRef<Value *> VL = UserTE->getOperand(I);
3631     TreeEntry *Gather = nullptr;
3632     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3633           assert(TE->State != TreeEntry::Vectorize &&
3634                  "Only non-vectorized nodes are expected.");
3635           if (TE->isSame(VL)) {
3636             Gather = TE;
3637             return true;
3638           }
3639           return false;
3640         }) > 1)
3641       return false;
3642     if (Gather)
3643       GatherOps.push_back(Gather);
3644   }
3645   return true;
3646 }
3647 
3648 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3649   SetVector<TreeEntry *> OrderedEntries;
3650   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3651   // Find all reorderable leaf nodes with the given VF.
3652   // Currently the are vectorized loads,extracts without alternate operands +
3653   // some gathering of extracts.
3654   SmallVector<TreeEntry *> NonVectorized;
3655   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3656                               &NonVectorized](
3657                                  const std::unique_ptr<TreeEntry> &TE) {
3658     if (TE->State != TreeEntry::Vectorize)
3659       NonVectorized.push_back(TE.get());
3660     if (Optional<OrdersType> CurrentOrder =
3661             getReorderingData(*TE, /*TopToBottom=*/false)) {
3662       OrderedEntries.insert(TE.get());
3663       if (TE->State != TreeEntry::Vectorize)
3664         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3665     }
3666   });
3667 
3668   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3669   // I.e., if the node has operands, that are reordered, try to make at least
3670   // one operand order in the natural order and reorder others + reorder the
3671   // user node itself.
3672   SmallPtrSet<const TreeEntry *, 4> Visited;
3673   while (!OrderedEntries.empty()) {
3674     // 1. Filter out only reordered nodes.
3675     // 2. If the entry has multiple uses - skip it and jump to the next node.
3676     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3677     SmallVector<TreeEntry *> Filtered;
3678     for (TreeEntry *TE : OrderedEntries) {
3679       if (!(TE->State == TreeEntry::Vectorize ||
3680             (TE->State == TreeEntry::NeedToGather &&
3681              GathersToOrders.count(TE))) ||
3682           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3683           !all_of(drop_begin(TE->UserTreeIndices),
3684                   [TE](const EdgeInfo &EI) {
3685                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3686                   }) ||
3687           !Visited.insert(TE).second) {
3688         Filtered.push_back(TE);
3689         continue;
3690       }
3691       // Build a map between user nodes and their operands order to speedup
3692       // search. The graph currently does not provide this dependency directly.
3693       for (EdgeInfo &EI : TE->UserTreeIndices) {
3694         TreeEntry *UserTE = EI.UserTE;
3695         auto It = Users.find(UserTE);
3696         if (It == Users.end())
3697           It = Users.insert({UserTE, {}}).first;
3698         It->second.emplace_back(EI.EdgeIdx, TE);
3699       }
3700     }
3701     // Erase filtered entries.
3702     for_each(Filtered,
3703              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3704     for (auto &Data : Users) {
3705       // Check that operands are used only in the User node.
3706       SmallVector<TreeEntry *> GatherOps;
3707       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3708                               GatherOps)) {
3709         for_each(Data.second,
3710                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3711                    OrderedEntries.remove(Op.second);
3712                  });
3713         continue;
3714       }
3715       // All operands are reordered and used only in this node - propagate the
3716       // most used order to the user node.
3717       MapVector<OrdersType, unsigned,
3718                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3719           OrdersUses;
3720       // Do the analysis for each tree entry only once, otherwise the order of
3721       // the same node my be considered several times, though might be not
3722       // profitable.
3723       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3724       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3725       for (const auto &Op : Data.second) {
3726         TreeEntry *OpTE = Op.second;
3727         if (!VisitedOps.insert(OpTE).second)
3728           continue;
3729         if (!OpTE->ReuseShuffleIndices.empty() ||
3730             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3731           continue;
3732         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3733           if (OpTE->State == TreeEntry::NeedToGather)
3734             return GathersToOrders.find(OpTE)->second;
3735           return OpTE->ReorderIndices;
3736         }();
3737         unsigned NumOps = count_if(
3738             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3739               return P.second == OpTE;
3740             });
3741         // Stores actually store the mask, not the order, need to invert.
3742         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3743             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3744           SmallVector<int> Mask;
3745           inversePermutation(Order, Mask);
3746           unsigned E = Order.size();
3747           OrdersType CurrentOrder(E, E);
3748           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3749             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3750           });
3751           fixupOrderingIndices(CurrentOrder);
3752           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3753               NumOps;
3754         } else {
3755           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3756         }
3757         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3758         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3759                                             const TreeEntry *TE) {
3760           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3761               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3762               (IgnoreReorder && TE->Idx == 0))
3763             return true;
3764           if (TE->State == TreeEntry::NeedToGather) {
3765             auto It = GathersToOrders.find(TE);
3766             if (It != GathersToOrders.end())
3767               return !It->second.empty();
3768             return true;
3769           }
3770           return false;
3771         };
3772         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3773           TreeEntry *UserTE = EI.UserTE;
3774           if (!VisitedUsers.insert(UserTE).second)
3775             continue;
3776           // May reorder user node if it requires reordering, has reused
3777           // scalars, is an alternate op vectorize node or its op nodes require
3778           // reordering.
3779           if (AllowsReordering(UserTE))
3780             continue;
3781           // Check if users allow reordering.
3782           // Currently look up just 1 level of operands to avoid increase of
3783           // the compile time.
3784           // Profitable to reorder if definitely more operands allow
3785           // reordering rather than those with natural order.
3786           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3787           if (static_cast<unsigned>(count_if(
3788                   Ops, [UserTE, &AllowsReordering](
3789                            const std::pair<unsigned, TreeEntry *> &Op) {
3790                     return AllowsReordering(Op.second) &&
3791                            all_of(Op.second->UserTreeIndices,
3792                                   [UserTE](const EdgeInfo &EI) {
3793                                     return EI.UserTE == UserTE;
3794                                   });
3795                   })) <= Ops.size() / 2)
3796             ++Res.first->second;
3797         }
3798       }
3799       // If no orders - skip current nodes and jump to the next one, if any.
3800       if (OrdersUses.empty()) {
3801         for_each(Data.second,
3802                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3803                    OrderedEntries.remove(Op.second);
3804                  });
3805         continue;
3806       }
3807       // Choose the best order.
3808       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3809       unsigned Cnt = OrdersUses.front().second;
3810       for (const auto &Pair : drop_begin(OrdersUses)) {
3811         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3812           BestOrder = Pair.first;
3813           Cnt = Pair.second;
3814         }
3815       }
3816       // Set order of the user node (reordering of operands and user nodes).
3817       if (BestOrder.empty()) {
3818         for_each(Data.second,
3819                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3820                    OrderedEntries.remove(Op.second);
3821                  });
3822         continue;
3823       }
3824       // Erase operands from OrderedEntries list and adjust their orders.
3825       VisitedOps.clear();
3826       SmallVector<int> Mask;
3827       inversePermutation(BestOrder, Mask);
3828       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3829       unsigned E = BestOrder.size();
3830       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3831         return I < E ? static_cast<int>(I) : UndefMaskElem;
3832       });
3833       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3834         TreeEntry *TE = Op.second;
3835         OrderedEntries.remove(TE);
3836         if (!VisitedOps.insert(TE).second)
3837           continue;
3838         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3839           // Just reorder reuses indices.
3840           reorderReuses(TE->ReuseShuffleIndices, Mask);
3841           continue;
3842         }
3843         // Gathers are processed separately.
3844         if (TE->State != TreeEntry::Vectorize)
3845           continue;
3846         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3847                 TE->ReorderIndices.empty()) &&
3848                "Non-matching sizes of user/operand entries.");
3849         reorderOrder(TE->ReorderIndices, Mask);
3850       }
3851       // For gathers just need to reorder its scalars.
3852       for (TreeEntry *Gather : GatherOps) {
3853         assert(Gather->ReorderIndices.empty() &&
3854                "Unexpected reordering of gathers.");
3855         if (!Gather->ReuseShuffleIndices.empty()) {
3856           // Just reorder reuses indices.
3857           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3858           continue;
3859         }
3860         reorderScalars(Gather->Scalars, Mask);
3861         OrderedEntries.remove(Gather);
3862       }
3863       // Reorder operands of the user node and set the ordering for the user
3864       // node itself.
3865       if (Data.first->State != TreeEntry::Vectorize ||
3866           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3867               Data.first->getMainOp()) ||
3868           Data.first->isAltShuffle())
3869         Data.first->reorderOperands(Mask);
3870       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3871           Data.first->isAltShuffle()) {
3872         reorderScalars(Data.first->Scalars, Mask);
3873         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3874         if (Data.first->ReuseShuffleIndices.empty() &&
3875             !Data.first->ReorderIndices.empty() &&
3876             !Data.first->isAltShuffle()) {
3877           // Insert user node to the list to try to sink reordering deeper in
3878           // the graph.
3879           OrderedEntries.insert(Data.first);
3880         }
3881       } else {
3882         reorderOrder(Data.first->ReorderIndices, Mask);
3883       }
3884     }
3885   }
3886   // If the reordering is unnecessary, just remove the reorder.
3887   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3888       VectorizableTree.front()->ReuseShuffleIndices.empty())
3889     VectorizableTree.front()->ReorderIndices.clear();
3890 }
3891 
3892 void BoUpSLP::buildExternalUses(
3893     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3894   // Collect the values that we need to extract from the tree.
3895   for (auto &TEPtr : VectorizableTree) {
3896     TreeEntry *Entry = TEPtr.get();
3897 
3898     // No need to handle users of gathered values.
3899     if (Entry->State == TreeEntry::NeedToGather)
3900       continue;
3901 
3902     // For each lane:
3903     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3904       Value *Scalar = Entry->Scalars[Lane];
3905       int FoundLane = Entry->findLaneForValue(Scalar);
3906 
3907       // Check if the scalar is externally used as an extra arg.
3908       auto ExtI = ExternallyUsedValues.find(Scalar);
3909       if (ExtI != ExternallyUsedValues.end()) {
3910         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3911                           << Lane << " from " << *Scalar << ".\n");
3912         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3913       }
3914       for (User *U : Scalar->users()) {
3915         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3916 
3917         Instruction *UserInst = dyn_cast<Instruction>(U);
3918         if (!UserInst)
3919           continue;
3920 
3921         if (isDeleted(UserInst))
3922           continue;
3923 
3924         // Skip in-tree scalars that become vectors
3925         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3926           Value *UseScalar = UseEntry->Scalars[0];
3927           // Some in-tree scalars will remain as scalar in vectorized
3928           // instructions. If that is the case, the one in Lane 0 will
3929           // be used.
3930           if (UseScalar != U ||
3931               UseEntry->State == TreeEntry::ScatterVectorize ||
3932               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3933             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3934                               << ".\n");
3935             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3936             continue;
3937           }
3938         }
3939 
3940         // Ignore users in the user ignore list.
3941         if (is_contained(UserIgnoreList, UserInst))
3942           continue;
3943 
3944         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3945                           << Lane << " from " << *Scalar << ".\n");
3946         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3947       }
3948     }
3949   }
3950 }
3951 
3952 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3953                         ArrayRef<Value *> UserIgnoreLst) {
3954   deleteTree();
3955   UserIgnoreList = UserIgnoreLst;
3956   if (!allSameType(Roots))
3957     return;
3958   buildTree_rec(Roots, 0, EdgeInfo());
3959 }
3960 
3961 namespace {
3962 /// Tracks the state we can represent the loads in the given sequence.
3963 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3964 } // anonymous namespace
3965 
3966 /// Checks if the given array of loads can be represented as a vectorized,
3967 /// scatter or just simple gather.
3968 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3969                                     const TargetTransformInfo &TTI,
3970                                     const DataLayout &DL, ScalarEvolution &SE,
3971                                     SmallVectorImpl<unsigned> &Order,
3972                                     SmallVectorImpl<Value *> &PointerOps) {
3973   // Check that a vectorized load would load the same memory as a scalar
3974   // load. For example, we don't want to vectorize loads that are smaller
3975   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3976   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3977   // from such a struct, we read/write packed bits disagreeing with the
3978   // unvectorized version.
3979   Type *ScalarTy = VL0->getType();
3980 
3981   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3982     return LoadsState::Gather;
3983 
3984   // Make sure all loads in the bundle are simple - we can't vectorize
3985   // atomic or volatile loads.
3986   PointerOps.clear();
3987   PointerOps.resize(VL.size());
3988   auto *POIter = PointerOps.begin();
3989   for (Value *V : VL) {
3990     auto *L = cast<LoadInst>(V);
3991     if (!L->isSimple())
3992       return LoadsState::Gather;
3993     *POIter = L->getPointerOperand();
3994     ++POIter;
3995   }
3996 
3997   Order.clear();
3998   // Check the order of pointer operands.
3999   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4000     Value *Ptr0;
4001     Value *PtrN;
4002     if (Order.empty()) {
4003       Ptr0 = PointerOps.front();
4004       PtrN = PointerOps.back();
4005     } else {
4006       Ptr0 = PointerOps[Order.front()];
4007       PtrN = PointerOps[Order.back()];
4008     }
4009     Optional<int> Diff =
4010         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4011     // Check that the sorted loads are consecutive.
4012     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4013       return LoadsState::Vectorize;
4014     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4015     for (Value *V : VL)
4016       CommonAlignment =
4017           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4018     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4019                                 CommonAlignment))
4020       return LoadsState::ScatterVectorize;
4021   }
4022 
4023   return LoadsState::Gather;
4024 }
4025 
4026 /// \return true if the specified list of values has only one instruction that
4027 /// requires scheduling, false otherwise.
4028 #ifndef NDEBUG
4029 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4030   Value *NeedsScheduling = nullptr;
4031   for (Value *V : VL) {
4032     if (doesNotNeedToBeScheduled(V))
4033       continue;
4034     if (!NeedsScheduling) {
4035       NeedsScheduling = V;
4036       continue;
4037     }
4038     return false;
4039   }
4040   return NeedsScheduling;
4041 }
4042 #endif
4043 
4044 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4045                             const EdgeInfo &UserTreeIdx) {
4046   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4047 
4048   SmallVector<int> ReuseShuffleIndicies;
4049   SmallVector<Value *> UniqueValues;
4050   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4051                                 &UserTreeIdx,
4052                                 this](const InstructionsState &S) {
4053     // Check that every instruction appears once in this bundle.
4054     DenseMap<Value *, unsigned> UniquePositions;
4055     for (Value *V : VL) {
4056       if (isConstant(V)) {
4057         ReuseShuffleIndicies.emplace_back(
4058             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4059         UniqueValues.emplace_back(V);
4060         continue;
4061       }
4062       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4063       ReuseShuffleIndicies.emplace_back(Res.first->second);
4064       if (Res.second)
4065         UniqueValues.emplace_back(V);
4066     }
4067     size_t NumUniqueScalarValues = UniqueValues.size();
4068     if (NumUniqueScalarValues == VL.size()) {
4069       ReuseShuffleIndicies.clear();
4070     } else {
4071       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4072       if (NumUniqueScalarValues <= 1 ||
4073           (UniquePositions.size() == 1 && all_of(UniqueValues,
4074                                                  [](Value *V) {
4075                                                    return isa<UndefValue>(V) ||
4076                                                           !isConstant(V);
4077                                                  })) ||
4078           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4079         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4080         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4081         return false;
4082       }
4083       VL = UniqueValues;
4084     }
4085     return true;
4086   };
4087 
4088   InstructionsState S = getSameOpcode(VL);
4089   if (Depth == RecursionMaxDepth) {
4090     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4091     if (TryToFindDuplicates(S))
4092       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4093                    ReuseShuffleIndicies);
4094     return;
4095   }
4096 
4097   // Don't handle scalable vectors
4098   if (S.getOpcode() == Instruction::ExtractElement &&
4099       isa<ScalableVectorType>(
4100           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4101     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4102     if (TryToFindDuplicates(S))
4103       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4104                    ReuseShuffleIndicies);
4105     return;
4106   }
4107 
4108   // Don't handle vectors.
4109   if (S.OpValue->getType()->isVectorTy() &&
4110       !isa<InsertElementInst>(S.OpValue)) {
4111     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4112     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4113     return;
4114   }
4115 
4116   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4117     if (SI->getValueOperand()->getType()->isVectorTy()) {
4118       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4119       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4120       return;
4121     }
4122 
4123   // If all of the operands are identical or constant we have a simple solution.
4124   // If we deal with insert/extract instructions, they all must have constant
4125   // indices, otherwise we should gather them, not try to vectorize.
4126   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4127       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4128        !all_of(VL, isVectorLikeInstWithConstOps))) {
4129     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4130     if (TryToFindDuplicates(S))
4131       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4132                    ReuseShuffleIndicies);
4133     return;
4134   }
4135 
4136   // We now know that this is a vector of instructions of the same type from
4137   // the same block.
4138 
4139   // Don't vectorize ephemeral values.
4140   for (Value *V : VL) {
4141     if (EphValues.count(V)) {
4142       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4143                         << ") is ephemeral.\n");
4144       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4145       return;
4146     }
4147   }
4148 
4149   // Check if this is a duplicate of another entry.
4150   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4151     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4152     if (!E->isSame(VL)) {
4153       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4154       if (TryToFindDuplicates(S))
4155         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4156                      ReuseShuffleIndicies);
4157       return;
4158     }
4159     // Record the reuse of the tree node.  FIXME, currently this is only used to
4160     // properly draw the graph rather than for the actual vectorization.
4161     E->UserTreeIndices.push_back(UserTreeIdx);
4162     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4163                       << ".\n");
4164     return;
4165   }
4166 
4167   // Check that none of the instructions in the bundle are already in the tree.
4168   for (Value *V : VL) {
4169     auto *I = dyn_cast<Instruction>(V);
4170     if (!I)
4171       continue;
4172     if (getTreeEntry(I)) {
4173       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4174                         << ") is already in tree.\n");
4175       if (TryToFindDuplicates(S))
4176         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4177                      ReuseShuffleIndicies);
4178       return;
4179     }
4180   }
4181 
4182   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4183   for (Value *V : VL) {
4184     if (is_contained(UserIgnoreList, V)) {
4185       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4186       if (TryToFindDuplicates(S))
4187         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4188                      ReuseShuffleIndicies);
4189       return;
4190     }
4191   }
4192 
4193   // Check that all of the users of the scalars that we want to vectorize are
4194   // schedulable.
4195   auto *VL0 = cast<Instruction>(S.OpValue);
4196   BasicBlock *BB = VL0->getParent();
4197 
4198   if (!DT->isReachableFromEntry(BB)) {
4199     // Don't go into unreachable blocks. They may contain instructions with
4200     // dependency cycles which confuse the final scheduling.
4201     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4202     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4203     return;
4204   }
4205 
4206   // Check that every instruction appears once in this bundle.
4207   if (!TryToFindDuplicates(S))
4208     return;
4209 
4210   auto &BSRef = BlocksSchedules[BB];
4211   if (!BSRef)
4212     BSRef = std::make_unique<BlockScheduling>(BB);
4213 
4214   BlockScheduling &BS = *BSRef;
4215 
4216   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4217 #ifdef EXPENSIVE_CHECKS
4218   // Make sure we didn't break any internal invariants
4219   BS.verify();
4220 #endif
4221   if (!Bundle) {
4222     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4223     assert((!BS.getScheduleData(VL0) ||
4224             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4225            "tryScheduleBundle should cancelScheduling on failure");
4226     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4227                  ReuseShuffleIndicies);
4228     return;
4229   }
4230   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4231 
4232   unsigned ShuffleOrOp = S.isAltShuffle() ?
4233                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4234   switch (ShuffleOrOp) {
4235     case Instruction::PHI: {
4236       auto *PH = cast<PHINode>(VL0);
4237 
4238       // Check for terminator values (e.g. invoke).
4239       for (Value *V : VL)
4240         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4241           Instruction *Term = dyn_cast<Instruction>(Incoming);
4242           if (Term && Term->isTerminator()) {
4243             LLVM_DEBUG(dbgs()
4244                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4245             BS.cancelScheduling(VL, VL0);
4246             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4247                          ReuseShuffleIndicies);
4248             return;
4249           }
4250         }
4251 
4252       TreeEntry *TE =
4253           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4254       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4255 
4256       // Keeps the reordered operands to avoid code duplication.
4257       SmallVector<ValueList, 2> OperandsVec;
4258       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4259         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4260           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4261           TE->setOperand(I, Operands);
4262           OperandsVec.push_back(Operands);
4263           continue;
4264         }
4265         ValueList Operands;
4266         // Prepare the operand vector.
4267         for (Value *V : VL)
4268           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4269               PH->getIncomingBlock(I)));
4270         TE->setOperand(I, Operands);
4271         OperandsVec.push_back(Operands);
4272       }
4273       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4274         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4275       return;
4276     }
4277     case Instruction::ExtractValue:
4278     case Instruction::ExtractElement: {
4279       OrdersType CurrentOrder;
4280       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4281       if (Reuse) {
4282         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4283         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4284                      ReuseShuffleIndicies);
4285         // This is a special case, as it does not gather, but at the same time
4286         // we are not extending buildTree_rec() towards the operands.
4287         ValueList Op0;
4288         Op0.assign(VL.size(), VL0->getOperand(0));
4289         VectorizableTree.back()->setOperand(0, Op0);
4290         return;
4291       }
4292       if (!CurrentOrder.empty()) {
4293         LLVM_DEBUG({
4294           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4295                     "with order";
4296           for (unsigned Idx : CurrentOrder)
4297             dbgs() << " " << Idx;
4298           dbgs() << "\n";
4299         });
4300         fixupOrderingIndices(CurrentOrder);
4301         // Insert new order with initial value 0, if it does not exist,
4302         // otherwise return the iterator to the existing one.
4303         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4304                      ReuseShuffleIndicies, CurrentOrder);
4305         // This is a special case, as it does not gather, but at the same time
4306         // we are not extending buildTree_rec() towards the operands.
4307         ValueList Op0;
4308         Op0.assign(VL.size(), VL0->getOperand(0));
4309         VectorizableTree.back()->setOperand(0, Op0);
4310         return;
4311       }
4312       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4313       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4314                    ReuseShuffleIndicies);
4315       BS.cancelScheduling(VL, VL0);
4316       return;
4317     }
4318     case Instruction::InsertElement: {
4319       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4320 
4321       // Check that we have a buildvector and not a shuffle of 2 or more
4322       // different vectors.
4323       ValueSet SourceVectors;
4324       for (Value *V : VL) {
4325         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4326         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4327       }
4328 
4329       if (count_if(VL, [&SourceVectors](Value *V) {
4330             return !SourceVectors.contains(V);
4331           }) >= 2) {
4332         // Found 2nd source vector - cancel.
4333         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4334                              "different source vectors.\n");
4335         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4336         BS.cancelScheduling(VL, VL0);
4337         return;
4338       }
4339 
4340       auto OrdCompare = [](const std::pair<int, int> &P1,
4341                            const std::pair<int, int> &P2) {
4342         return P1.first > P2.first;
4343       };
4344       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4345                     decltype(OrdCompare)>
4346           Indices(OrdCompare);
4347       for (int I = 0, E = VL.size(); I < E; ++I) {
4348         unsigned Idx = *getInsertIndex(VL[I]);
4349         Indices.emplace(Idx, I);
4350       }
4351       OrdersType CurrentOrder(VL.size(), VL.size());
4352       bool IsIdentity = true;
4353       for (int I = 0, E = VL.size(); I < E; ++I) {
4354         CurrentOrder[Indices.top().second] = I;
4355         IsIdentity &= Indices.top().second == I;
4356         Indices.pop();
4357       }
4358       if (IsIdentity)
4359         CurrentOrder.clear();
4360       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4361                                    None, CurrentOrder);
4362       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4363 
4364       constexpr int NumOps = 2;
4365       ValueList VectorOperands[NumOps];
4366       for (int I = 0; I < NumOps; ++I) {
4367         for (Value *V : VL)
4368           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4369 
4370         TE->setOperand(I, VectorOperands[I]);
4371       }
4372       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4373       return;
4374     }
4375     case Instruction::Load: {
4376       // Check that a vectorized load would load the same memory as a scalar
4377       // load. For example, we don't want to vectorize loads that are smaller
4378       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4379       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4380       // from such a struct, we read/write packed bits disagreeing with the
4381       // unvectorized version.
4382       SmallVector<Value *> PointerOps;
4383       OrdersType CurrentOrder;
4384       TreeEntry *TE = nullptr;
4385       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4386                                 PointerOps)) {
4387       case LoadsState::Vectorize:
4388         if (CurrentOrder.empty()) {
4389           // Original loads are consecutive and does not require reordering.
4390           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4391                             ReuseShuffleIndicies);
4392           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4393         } else {
4394           fixupOrderingIndices(CurrentOrder);
4395           // Need to reorder.
4396           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4397                             ReuseShuffleIndicies, CurrentOrder);
4398           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4399         }
4400         TE->setOperandsInOrder();
4401         break;
4402       case LoadsState::ScatterVectorize:
4403         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4404         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4405                           UserTreeIdx, ReuseShuffleIndicies);
4406         TE->setOperandsInOrder();
4407         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4408         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4409         break;
4410       case LoadsState::Gather:
4411         BS.cancelScheduling(VL, VL0);
4412         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4413                      ReuseShuffleIndicies);
4414 #ifndef NDEBUG
4415         Type *ScalarTy = VL0->getType();
4416         if (DL->getTypeSizeInBits(ScalarTy) !=
4417             DL->getTypeAllocSizeInBits(ScalarTy))
4418           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4419         else if (any_of(VL, [](Value *V) {
4420                    return !cast<LoadInst>(V)->isSimple();
4421                  }))
4422           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4423         else
4424           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4425 #endif // NDEBUG
4426         break;
4427       }
4428       return;
4429     }
4430     case Instruction::ZExt:
4431     case Instruction::SExt:
4432     case Instruction::FPToUI:
4433     case Instruction::FPToSI:
4434     case Instruction::FPExt:
4435     case Instruction::PtrToInt:
4436     case Instruction::IntToPtr:
4437     case Instruction::SIToFP:
4438     case Instruction::UIToFP:
4439     case Instruction::Trunc:
4440     case Instruction::FPTrunc:
4441     case Instruction::BitCast: {
4442       Type *SrcTy = VL0->getOperand(0)->getType();
4443       for (Value *V : VL) {
4444         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4445         if (Ty != SrcTy || !isValidElementType(Ty)) {
4446           BS.cancelScheduling(VL, VL0);
4447           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4448                        ReuseShuffleIndicies);
4449           LLVM_DEBUG(dbgs()
4450                      << "SLP: Gathering casts with different src types.\n");
4451           return;
4452         }
4453       }
4454       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4455                                    ReuseShuffleIndicies);
4456       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4457 
4458       TE->setOperandsInOrder();
4459       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4460         ValueList Operands;
4461         // Prepare the operand vector.
4462         for (Value *V : VL)
4463           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4464 
4465         buildTree_rec(Operands, Depth + 1, {TE, i});
4466       }
4467       return;
4468     }
4469     case Instruction::ICmp:
4470     case Instruction::FCmp: {
4471       // Check that all of the compares have the same predicate.
4472       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4473       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4474       Type *ComparedTy = VL0->getOperand(0)->getType();
4475       for (Value *V : VL) {
4476         CmpInst *Cmp = cast<CmpInst>(V);
4477         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4478             Cmp->getOperand(0)->getType() != ComparedTy) {
4479           BS.cancelScheduling(VL, VL0);
4480           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4481                        ReuseShuffleIndicies);
4482           LLVM_DEBUG(dbgs()
4483                      << "SLP: Gathering cmp with different predicate.\n");
4484           return;
4485         }
4486       }
4487 
4488       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4489                                    ReuseShuffleIndicies);
4490       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4491 
4492       ValueList Left, Right;
4493       if (cast<CmpInst>(VL0)->isCommutative()) {
4494         // Commutative predicate - collect + sort operands of the instructions
4495         // so that each side is more likely to have the same opcode.
4496         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4497         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4498       } else {
4499         // Collect operands - commute if it uses the swapped predicate.
4500         for (Value *V : VL) {
4501           auto *Cmp = cast<CmpInst>(V);
4502           Value *LHS = Cmp->getOperand(0);
4503           Value *RHS = Cmp->getOperand(1);
4504           if (Cmp->getPredicate() != P0)
4505             std::swap(LHS, RHS);
4506           Left.push_back(LHS);
4507           Right.push_back(RHS);
4508         }
4509       }
4510       TE->setOperand(0, Left);
4511       TE->setOperand(1, Right);
4512       buildTree_rec(Left, Depth + 1, {TE, 0});
4513       buildTree_rec(Right, Depth + 1, {TE, 1});
4514       return;
4515     }
4516     case Instruction::Select:
4517     case Instruction::FNeg:
4518     case Instruction::Add:
4519     case Instruction::FAdd:
4520     case Instruction::Sub:
4521     case Instruction::FSub:
4522     case Instruction::Mul:
4523     case Instruction::FMul:
4524     case Instruction::UDiv:
4525     case Instruction::SDiv:
4526     case Instruction::FDiv:
4527     case Instruction::URem:
4528     case Instruction::SRem:
4529     case Instruction::FRem:
4530     case Instruction::Shl:
4531     case Instruction::LShr:
4532     case Instruction::AShr:
4533     case Instruction::And:
4534     case Instruction::Or:
4535     case Instruction::Xor: {
4536       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4537                                    ReuseShuffleIndicies);
4538       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4539 
4540       // Sort operands of the instructions so that each side is more likely to
4541       // have the same opcode.
4542       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4543         ValueList Left, Right;
4544         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4545         TE->setOperand(0, Left);
4546         TE->setOperand(1, Right);
4547         buildTree_rec(Left, Depth + 1, {TE, 0});
4548         buildTree_rec(Right, Depth + 1, {TE, 1});
4549         return;
4550       }
4551 
4552       TE->setOperandsInOrder();
4553       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4554         ValueList Operands;
4555         // Prepare the operand vector.
4556         for (Value *V : VL)
4557           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4558 
4559         buildTree_rec(Operands, Depth + 1, {TE, i});
4560       }
4561       return;
4562     }
4563     case Instruction::GetElementPtr: {
4564       // We don't combine GEPs with complicated (nested) indexing.
4565       for (Value *V : VL) {
4566         if (cast<Instruction>(V)->getNumOperands() != 2) {
4567           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4568           BS.cancelScheduling(VL, VL0);
4569           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4570                        ReuseShuffleIndicies);
4571           return;
4572         }
4573       }
4574 
4575       // We can't combine several GEPs into one vector if they operate on
4576       // different types.
4577       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4578       for (Value *V : VL) {
4579         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4580         if (Ty0 != CurTy) {
4581           LLVM_DEBUG(dbgs()
4582                      << "SLP: not-vectorizable GEP (different types).\n");
4583           BS.cancelScheduling(VL, VL0);
4584           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4585                        ReuseShuffleIndicies);
4586           return;
4587         }
4588       }
4589 
4590       // We don't combine GEPs with non-constant indexes.
4591       Type *Ty1 = VL0->getOperand(1)->getType();
4592       for (Value *V : VL) {
4593         auto Op = cast<Instruction>(V)->getOperand(1);
4594         if (!isa<ConstantInt>(Op) ||
4595             (Op->getType() != Ty1 &&
4596              Op->getType()->getScalarSizeInBits() >
4597                  DL->getIndexSizeInBits(
4598                      V->getType()->getPointerAddressSpace()))) {
4599           LLVM_DEBUG(dbgs()
4600                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4601           BS.cancelScheduling(VL, VL0);
4602           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4603                        ReuseShuffleIndicies);
4604           return;
4605         }
4606       }
4607 
4608       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4609                                    ReuseShuffleIndicies);
4610       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4611       SmallVector<ValueList, 2> Operands(2);
4612       // Prepare the operand vector for pointer operands.
4613       for (Value *V : VL)
4614         Operands.front().push_back(
4615             cast<GetElementPtrInst>(V)->getPointerOperand());
4616       TE->setOperand(0, Operands.front());
4617       // Need to cast all indices to the same type before vectorization to
4618       // avoid crash.
4619       // Required to be able to find correct matches between different gather
4620       // nodes and reuse the vectorized values rather than trying to gather them
4621       // again.
4622       int IndexIdx = 1;
4623       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4624       Type *Ty = all_of(VL,
4625                         [VL0Ty, IndexIdx](Value *V) {
4626                           return VL0Ty == cast<GetElementPtrInst>(V)
4627                                               ->getOperand(IndexIdx)
4628                                               ->getType();
4629                         })
4630                      ? VL0Ty
4631                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4632                                             ->getPointerOperandType()
4633                                             ->getScalarType());
4634       // Prepare the operand vector.
4635       for (Value *V : VL) {
4636         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4637         auto *CI = cast<ConstantInt>(Op);
4638         Operands.back().push_back(ConstantExpr::getIntegerCast(
4639             CI, Ty, CI->getValue().isSignBitSet()));
4640       }
4641       TE->setOperand(IndexIdx, Operands.back());
4642 
4643       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4644         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4645       return;
4646     }
4647     case Instruction::Store: {
4648       // Check if the stores are consecutive or if we need to swizzle them.
4649       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4650       // Avoid types that are padded when being allocated as scalars, while
4651       // being packed together in a vector (such as i1).
4652       if (DL->getTypeSizeInBits(ScalarTy) !=
4653           DL->getTypeAllocSizeInBits(ScalarTy)) {
4654         BS.cancelScheduling(VL, VL0);
4655         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4656                      ReuseShuffleIndicies);
4657         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4658         return;
4659       }
4660       // Make sure all stores in the bundle are simple - we can't vectorize
4661       // atomic or volatile stores.
4662       SmallVector<Value *, 4> PointerOps(VL.size());
4663       ValueList Operands(VL.size());
4664       auto POIter = PointerOps.begin();
4665       auto OIter = Operands.begin();
4666       for (Value *V : VL) {
4667         auto *SI = cast<StoreInst>(V);
4668         if (!SI->isSimple()) {
4669           BS.cancelScheduling(VL, VL0);
4670           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4671                        ReuseShuffleIndicies);
4672           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4673           return;
4674         }
4675         *POIter = SI->getPointerOperand();
4676         *OIter = SI->getValueOperand();
4677         ++POIter;
4678         ++OIter;
4679       }
4680 
4681       OrdersType CurrentOrder;
4682       // Check the order of pointer operands.
4683       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4684         Value *Ptr0;
4685         Value *PtrN;
4686         if (CurrentOrder.empty()) {
4687           Ptr0 = PointerOps.front();
4688           PtrN = PointerOps.back();
4689         } else {
4690           Ptr0 = PointerOps[CurrentOrder.front()];
4691           PtrN = PointerOps[CurrentOrder.back()];
4692         }
4693         Optional<int> Dist =
4694             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4695         // Check that the sorted pointer operands are consecutive.
4696         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4697           if (CurrentOrder.empty()) {
4698             // Original stores are consecutive and does not require reordering.
4699             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4700                                          UserTreeIdx, ReuseShuffleIndicies);
4701             TE->setOperandsInOrder();
4702             buildTree_rec(Operands, Depth + 1, {TE, 0});
4703             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4704           } else {
4705             fixupOrderingIndices(CurrentOrder);
4706             TreeEntry *TE =
4707                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4708                              ReuseShuffleIndicies, CurrentOrder);
4709             TE->setOperandsInOrder();
4710             buildTree_rec(Operands, Depth + 1, {TE, 0});
4711             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4712           }
4713           return;
4714         }
4715       }
4716 
4717       BS.cancelScheduling(VL, VL0);
4718       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4719                    ReuseShuffleIndicies);
4720       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4721       return;
4722     }
4723     case Instruction::Call: {
4724       // Check if the calls are all to the same vectorizable intrinsic or
4725       // library function.
4726       CallInst *CI = cast<CallInst>(VL0);
4727       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4728 
4729       VFShape Shape = VFShape::get(
4730           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4731           false /*HasGlobalPred*/);
4732       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4733 
4734       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4735         BS.cancelScheduling(VL, VL0);
4736         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4737                      ReuseShuffleIndicies);
4738         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4739         return;
4740       }
4741       Function *F = CI->getCalledFunction();
4742       unsigned NumArgs = CI->arg_size();
4743       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4744       for (unsigned j = 0; j != NumArgs; ++j)
4745         if (hasVectorIntrinsicScalarOpd(ID, j))
4746           ScalarArgs[j] = CI->getArgOperand(j);
4747       for (Value *V : VL) {
4748         CallInst *CI2 = dyn_cast<CallInst>(V);
4749         if (!CI2 || CI2->getCalledFunction() != F ||
4750             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4751             (VecFunc &&
4752              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4753             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4754           BS.cancelScheduling(VL, VL0);
4755           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4756                        ReuseShuffleIndicies);
4757           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4758                             << "\n");
4759           return;
4760         }
4761         // Some intrinsics have scalar arguments and should be same in order for
4762         // them to be vectorized.
4763         for (unsigned j = 0; j != NumArgs; ++j) {
4764           if (hasVectorIntrinsicScalarOpd(ID, j)) {
4765             Value *A1J = CI2->getArgOperand(j);
4766             if (ScalarArgs[j] != A1J) {
4767               BS.cancelScheduling(VL, VL0);
4768               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4769                            ReuseShuffleIndicies);
4770               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4771                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4772                                 << "\n");
4773               return;
4774             }
4775           }
4776         }
4777         // Verify that the bundle operands are identical between the two calls.
4778         if (CI->hasOperandBundles() &&
4779             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4780                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4781                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4782           BS.cancelScheduling(VL, VL0);
4783           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4784                        ReuseShuffleIndicies);
4785           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4786                             << *CI << "!=" << *V << '\n');
4787           return;
4788         }
4789       }
4790 
4791       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4792                                    ReuseShuffleIndicies);
4793       TE->setOperandsInOrder();
4794       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4795         // For scalar operands no need to to create an entry since no need to
4796         // vectorize it.
4797         if (hasVectorIntrinsicScalarOpd(ID, i))
4798           continue;
4799         ValueList Operands;
4800         // Prepare the operand vector.
4801         for (Value *V : VL) {
4802           auto *CI2 = cast<CallInst>(V);
4803           Operands.push_back(CI2->getArgOperand(i));
4804         }
4805         buildTree_rec(Operands, Depth + 1, {TE, i});
4806       }
4807       return;
4808     }
4809     case Instruction::ShuffleVector: {
4810       // If this is not an alternate sequence of opcode like add-sub
4811       // then do not vectorize this instruction.
4812       if (!S.isAltShuffle()) {
4813         BS.cancelScheduling(VL, VL0);
4814         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4815                      ReuseShuffleIndicies);
4816         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4817         return;
4818       }
4819       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4820                                    ReuseShuffleIndicies);
4821       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4822 
4823       // Reorder operands if reordering would enable vectorization.
4824       auto *CI = dyn_cast<CmpInst>(VL0);
4825       if (isa<BinaryOperator>(VL0) || CI) {
4826         ValueList Left, Right;
4827         if (!CI || all_of(VL, [](Value *V) {
4828               return cast<CmpInst>(V)->isCommutative();
4829             })) {
4830           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4831         } else {
4832           CmpInst::Predicate P0 = CI->getPredicate();
4833           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4834           assert(P0 != AltP0 &&
4835                  "Expected different main/alternate predicates.");
4836           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4837           Value *BaseOp0 = VL0->getOperand(0);
4838           Value *BaseOp1 = VL0->getOperand(1);
4839           // Collect operands - commute if it uses the swapped predicate or
4840           // alternate operation.
4841           for (Value *V : VL) {
4842             auto *Cmp = cast<CmpInst>(V);
4843             Value *LHS = Cmp->getOperand(0);
4844             Value *RHS = Cmp->getOperand(1);
4845             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4846             if (P0 == AltP0Swapped) {
4847               if (CI != Cmp && S.AltOp != Cmp &&
4848                   ((P0 == CurrentPred &&
4849                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4850                    (AltP0 == CurrentPred &&
4851                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4852                 std::swap(LHS, RHS);
4853             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4854               std::swap(LHS, RHS);
4855             }
4856             Left.push_back(LHS);
4857             Right.push_back(RHS);
4858           }
4859         }
4860         TE->setOperand(0, Left);
4861         TE->setOperand(1, Right);
4862         buildTree_rec(Left, Depth + 1, {TE, 0});
4863         buildTree_rec(Right, Depth + 1, {TE, 1});
4864         return;
4865       }
4866 
4867       TE->setOperandsInOrder();
4868       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4869         ValueList Operands;
4870         // Prepare the operand vector.
4871         for (Value *V : VL)
4872           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4873 
4874         buildTree_rec(Operands, Depth + 1, {TE, i});
4875       }
4876       return;
4877     }
4878     default:
4879       BS.cancelScheduling(VL, VL0);
4880       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4881                    ReuseShuffleIndicies);
4882       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4883       return;
4884   }
4885 }
4886 
4887 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4888   unsigned N = 1;
4889   Type *EltTy = T;
4890 
4891   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4892          isa<VectorType>(EltTy)) {
4893     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4894       // Check that struct is homogeneous.
4895       for (const auto *Ty : ST->elements())
4896         if (Ty != *ST->element_begin())
4897           return 0;
4898       N *= ST->getNumElements();
4899       EltTy = *ST->element_begin();
4900     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4901       N *= AT->getNumElements();
4902       EltTy = AT->getElementType();
4903     } else {
4904       auto *VT = cast<FixedVectorType>(EltTy);
4905       N *= VT->getNumElements();
4906       EltTy = VT->getElementType();
4907     }
4908   }
4909 
4910   if (!isValidElementType(EltTy))
4911     return 0;
4912   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4913   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4914     return 0;
4915   return N;
4916 }
4917 
4918 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4919                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4920   const auto *It = find_if(VL, [](Value *V) {
4921     return isa<ExtractElementInst, ExtractValueInst>(V);
4922   });
4923   assert(It != VL.end() && "Expected at least one extract instruction.");
4924   auto *E0 = cast<Instruction>(*It);
4925   assert(all_of(VL,
4926                 [](Value *V) {
4927                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4928                       V);
4929                 }) &&
4930          "Invalid opcode");
4931   // Check if all of the extracts come from the same vector and from the
4932   // correct offset.
4933   Value *Vec = E0->getOperand(0);
4934 
4935   CurrentOrder.clear();
4936 
4937   // We have to extract from a vector/aggregate with the same number of elements.
4938   unsigned NElts;
4939   if (E0->getOpcode() == Instruction::ExtractValue) {
4940     const DataLayout &DL = E0->getModule()->getDataLayout();
4941     NElts = canMapToVector(Vec->getType(), DL);
4942     if (!NElts)
4943       return false;
4944     // Check if load can be rewritten as load of vector.
4945     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4946     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4947       return false;
4948   } else {
4949     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4950   }
4951 
4952   if (NElts != VL.size())
4953     return false;
4954 
4955   // Check that all of the indices extract from the correct offset.
4956   bool ShouldKeepOrder = true;
4957   unsigned E = VL.size();
4958   // Assign to all items the initial value E + 1 so we can check if the extract
4959   // instruction index was used already.
4960   // Also, later we can check that all the indices are used and we have a
4961   // consecutive access in the extract instructions, by checking that no
4962   // element of CurrentOrder still has value E + 1.
4963   CurrentOrder.assign(E, E);
4964   unsigned I = 0;
4965   for (; I < E; ++I) {
4966     auto *Inst = dyn_cast<Instruction>(VL[I]);
4967     if (!Inst)
4968       continue;
4969     if (Inst->getOperand(0) != Vec)
4970       break;
4971     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4972       if (isa<UndefValue>(EE->getIndexOperand()))
4973         continue;
4974     Optional<unsigned> Idx = getExtractIndex(Inst);
4975     if (!Idx)
4976       break;
4977     const unsigned ExtIdx = *Idx;
4978     if (ExtIdx != I) {
4979       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4980         break;
4981       ShouldKeepOrder = false;
4982       CurrentOrder[ExtIdx] = I;
4983     } else {
4984       if (CurrentOrder[I] != E)
4985         break;
4986       CurrentOrder[I] = I;
4987     }
4988   }
4989   if (I < E) {
4990     CurrentOrder.clear();
4991     return false;
4992   }
4993   if (ShouldKeepOrder)
4994     CurrentOrder.clear();
4995 
4996   return ShouldKeepOrder;
4997 }
4998 
4999 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5000                                     ArrayRef<Value *> VectorizedVals) const {
5001   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5002          all_of(I->users(), [this](User *U) {
5003            return ScalarToTreeEntry.count(U) > 0 ||
5004                   isVectorLikeInstWithConstOps(U) ||
5005                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5006          });
5007 }
5008 
5009 static std::pair<InstructionCost, InstructionCost>
5010 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5011                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5012   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5013 
5014   // Calculate the cost of the scalar and vector calls.
5015   SmallVector<Type *, 4> VecTys;
5016   for (Use &Arg : CI->args())
5017     VecTys.push_back(
5018         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5019   FastMathFlags FMF;
5020   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5021     FMF = FPCI->getFastMathFlags();
5022   SmallVector<const Value *> Arguments(CI->args());
5023   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5024                                     dyn_cast<IntrinsicInst>(CI));
5025   auto IntrinsicCost =
5026     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5027 
5028   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5029                                      VecTy->getNumElements())),
5030                             false /*HasGlobalPred*/);
5031   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5032   auto LibCost = IntrinsicCost;
5033   if (!CI->isNoBuiltin() && VecFunc) {
5034     // Calculate the cost of the vector library call.
5035     // If the corresponding vector call is cheaper, return its cost.
5036     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5037                                     TTI::TCK_RecipThroughput);
5038   }
5039   return {IntrinsicCost, LibCost};
5040 }
5041 
5042 /// Compute the cost of creating a vector of type \p VecTy containing the
5043 /// extracted values from \p VL.
5044 static InstructionCost
5045 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5046                    TargetTransformInfo::ShuffleKind ShuffleKind,
5047                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5048   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5049 
5050   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5051       VecTy->getNumElements() < NumOfParts)
5052     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5053 
5054   bool AllConsecutive = true;
5055   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5056   unsigned Idx = -1;
5057   InstructionCost Cost = 0;
5058 
5059   // Process extracts in blocks of EltsPerVector to check if the source vector
5060   // operand can be re-used directly. If not, add the cost of creating a shuffle
5061   // to extract the values into a vector register.
5062   for (auto *V : VL) {
5063     ++Idx;
5064 
5065     // Need to exclude undefs from analysis.
5066     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5067       continue;
5068 
5069     // Reached the start of a new vector registers.
5070     if (Idx % EltsPerVector == 0) {
5071       AllConsecutive = true;
5072       continue;
5073     }
5074 
5075     // Check all extracts for a vector register on the target directly
5076     // extract values in order.
5077     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5078     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5079       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5080       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5081                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5082     }
5083 
5084     if (AllConsecutive)
5085       continue;
5086 
5087     // Skip all indices, except for the last index per vector block.
5088     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5089       continue;
5090 
5091     // If we have a series of extracts which are not consecutive and hence
5092     // cannot re-use the source vector register directly, compute the shuffle
5093     // cost to extract the a vector with EltsPerVector elements.
5094     Cost += TTI.getShuffleCost(
5095         TargetTransformInfo::SK_PermuteSingleSrc,
5096         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5097   }
5098   return Cost;
5099 }
5100 
5101 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5102 /// operations operands.
5103 static void
5104 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5105                       ArrayRef<int> ReusesIndices,
5106                       const function_ref<bool(Instruction *)> IsAltOp,
5107                       SmallVectorImpl<int> &Mask,
5108                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5109                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5110   unsigned Sz = VL.size();
5111   Mask.assign(Sz, UndefMaskElem);
5112   SmallVector<int> OrderMask;
5113   if (!ReorderIndices.empty())
5114     inversePermutation(ReorderIndices, OrderMask);
5115   for (unsigned I = 0; I < Sz; ++I) {
5116     unsigned Idx = I;
5117     if (!ReorderIndices.empty())
5118       Idx = OrderMask[I];
5119     auto *OpInst = cast<Instruction>(VL[Idx]);
5120     if (IsAltOp(OpInst)) {
5121       Mask[I] = Sz + Idx;
5122       if (AltScalars)
5123         AltScalars->push_back(OpInst);
5124     } else {
5125       Mask[I] = Idx;
5126       if (OpScalars)
5127         OpScalars->push_back(OpInst);
5128     }
5129   }
5130   if (!ReusesIndices.empty()) {
5131     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5132     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5133       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5134     });
5135     Mask.swap(NewMask);
5136   }
5137 }
5138 
5139 /// Checks if the specified instruction \p I is an alternate operation for the
5140 /// given \p MainOp and \p AltOp instructions.
5141 static bool isAlternateInstruction(const Instruction *I,
5142                                    const Instruction *MainOp,
5143                                    const Instruction *AltOp) {
5144   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5145     auto *AltCI0 = cast<CmpInst>(AltOp);
5146     auto *CI = cast<CmpInst>(I);
5147     CmpInst::Predicate P0 = CI0->getPredicate();
5148     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5149     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5150     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5151     CmpInst::Predicate CurrentPred = CI->getPredicate();
5152     if (P0 == AltP0Swapped)
5153       return I == AltCI0 ||
5154              (I != MainOp &&
5155               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5156                                    CI->getOperand(0), CI->getOperand(1)));
5157     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5158   }
5159   return I->getOpcode() == AltOp->getOpcode();
5160 }
5161 
5162 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5163                                       ArrayRef<Value *> VectorizedVals) {
5164   ArrayRef<Value*> VL = E->Scalars;
5165 
5166   Type *ScalarTy = VL[0]->getType();
5167   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5168     ScalarTy = SI->getValueOperand()->getType();
5169   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5170     ScalarTy = CI->getOperand(0)->getType();
5171   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5172     ScalarTy = IE->getOperand(1)->getType();
5173   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5174   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5175 
5176   // If we have computed a smaller type for the expression, update VecTy so
5177   // that the costs will be accurate.
5178   if (MinBWs.count(VL[0]))
5179     VecTy = FixedVectorType::get(
5180         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5181   unsigned EntryVF = E->getVectorFactor();
5182   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5183 
5184   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5185   // FIXME: it tries to fix a problem with MSVC buildbots.
5186   TargetTransformInfo &TTIRef = *TTI;
5187   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5188                                VectorizedVals, E](InstructionCost &Cost) {
5189     DenseMap<Value *, int> ExtractVectorsTys;
5190     SmallPtrSet<Value *, 4> CheckedExtracts;
5191     for (auto *V : VL) {
5192       if (isa<UndefValue>(V))
5193         continue;
5194       // If all users of instruction are going to be vectorized and this
5195       // instruction itself is not going to be vectorized, consider this
5196       // instruction as dead and remove its cost from the final cost of the
5197       // vectorized tree.
5198       // Also, avoid adjusting the cost for extractelements with multiple uses
5199       // in different graph entries.
5200       const TreeEntry *VE = getTreeEntry(V);
5201       if (!CheckedExtracts.insert(V).second ||
5202           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5203           (VE && VE != E))
5204         continue;
5205       auto *EE = cast<ExtractElementInst>(V);
5206       Optional<unsigned> EEIdx = getExtractIndex(EE);
5207       if (!EEIdx)
5208         continue;
5209       unsigned Idx = *EEIdx;
5210       if (TTIRef.getNumberOfParts(VecTy) !=
5211           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5212         auto It =
5213             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5214         It->getSecond() = std::min<int>(It->second, Idx);
5215       }
5216       // Take credit for instruction that will become dead.
5217       if (EE->hasOneUse()) {
5218         Instruction *Ext = EE->user_back();
5219         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5220             all_of(Ext->users(),
5221                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5222           // Use getExtractWithExtendCost() to calculate the cost of
5223           // extractelement/ext pair.
5224           Cost -=
5225               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5226                                               EE->getVectorOperandType(), Idx);
5227           // Add back the cost of s|zext which is subtracted separately.
5228           Cost += TTIRef.getCastInstrCost(
5229               Ext->getOpcode(), Ext->getType(), EE->getType(),
5230               TTI::getCastContextHint(Ext), CostKind, Ext);
5231           continue;
5232         }
5233       }
5234       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5235                                         EE->getVectorOperandType(), Idx);
5236     }
5237     // Add a cost for subvector extracts/inserts if required.
5238     for (const auto &Data : ExtractVectorsTys) {
5239       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5240       unsigned NumElts = VecTy->getNumElements();
5241       if (Data.second % NumElts == 0)
5242         continue;
5243       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5244         unsigned Idx = (Data.second / NumElts) * NumElts;
5245         unsigned EENumElts = EEVTy->getNumElements();
5246         if (Idx + NumElts <= EENumElts) {
5247           Cost +=
5248               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5249                                     EEVTy, None, Idx, VecTy);
5250         } else {
5251           // Need to round up the subvector type vectorization factor to avoid a
5252           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5253           // <= EENumElts.
5254           auto *SubVT =
5255               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5256           Cost +=
5257               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5258                                     EEVTy, None, Idx, SubVT);
5259         }
5260       } else {
5261         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5262                                       VecTy, None, 0, EEVTy);
5263       }
5264     }
5265   };
5266   if (E->State == TreeEntry::NeedToGather) {
5267     if (allConstant(VL))
5268       return 0;
5269     if (isa<InsertElementInst>(VL[0]))
5270       return InstructionCost::getInvalid();
5271     SmallVector<int> Mask;
5272     SmallVector<const TreeEntry *> Entries;
5273     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5274         isGatherShuffledEntry(E, Mask, Entries);
5275     if (Shuffle.hasValue()) {
5276       InstructionCost GatherCost = 0;
5277       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5278         // Perfect match in the graph, will reuse the previously vectorized
5279         // node. Cost is 0.
5280         LLVM_DEBUG(
5281             dbgs()
5282             << "SLP: perfect diamond match for gather bundle that starts with "
5283             << *VL.front() << ".\n");
5284         if (NeedToShuffleReuses)
5285           GatherCost =
5286               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5287                                   FinalVecTy, E->ReuseShuffleIndices);
5288       } else {
5289         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5290                           << " entries for bundle that starts with "
5291                           << *VL.front() << ".\n");
5292         // Detected that instead of gather we can emit a shuffle of single/two
5293         // previously vectorized nodes. Add the cost of the permutation rather
5294         // than gather.
5295         ::addMask(Mask, E->ReuseShuffleIndices);
5296         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5297       }
5298       return GatherCost;
5299     }
5300     if ((E->getOpcode() == Instruction::ExtractElement ||
5301          all_of(E->Scalars,
5302                 [](Value *V) {
5303                   return isa<ExtractElementInst, UndefValue>(V);
5304                 })) &&
5305         allSameType(VL)) {
5306       // Check that gather of extractelements can be represented as just a
5307       // shuffle of a single/two vectors the scalars are extracted from.
5308       SmallVector<int> Mask;
5309       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5310           isFixedVectorShuffle(VL, Mask);
5311       if (ShuffleKind.hasValue()) {
5312         // Found the bunch of extractelement instructions that must be gathered
5313         // into a vector and can be represented as a permutation elements in a
5314         // single input vector or of 2 input vectors.
5315         InstructionCost Cost =
5316             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5317         AdjustExtractsCost(Cost);
5318         if (NeedToShuffleReuses)
5319           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5320                                       FinalVecTy, E->ReuseShuffleIndices);
5321         return Cost;
5322       }
5323     }
5324     if (isSplat(VL)) {
5325       // Found the broadcasting of the single scalar, calculate the cost as the
5326       // broadcast.
5327       assert(VecTy == FinalVecTy &&
5328              "No reused scalars expected for broadcast.");
5329       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5330                                  /*Mask=*/None, /*Index=*/0,
5331                                  /*SubTp=*/nullptr, /*Args=*/VL);
5332     }
5333     InstructionCost ReuseShuffleCost = 0;
5334     if (NeedToShuffleReuses)
5335       ReuseShuffleCost = TTI->getShuffleCost(
5336           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5337     // Improve gather cost for gather of loads, if we can group some of the
5338     // loads into vector loads.
5339     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5340         !E->isAltShuffle()) {
5341       BoUpSLP::ValueSet VectorizedLoads;
5342       unsigned StartIdx = 0;
5343       unsigned VF = VL.size() / 2;
5344       unsigned VectorizedCnt = 0;
5345       unsigned ScatterVectorizeCnt = 0;
5346       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5347       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5348         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5349              Cnt += VF) {
5350           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5351           if (!VectorizedLoads.count(Slice.front()) &&
5352               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5353             SmallVector<Value *> PointerOps;
5354             OrdersType CurrentOrder;
5355             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5356                                               *SE, CurrentOrder, PointerOps);
5357             switch (LS) {
5358             case LoadsState::Vectorize:
5359             case LoadsState::ScatterVectorize:
5360               // Mark the vectorized loads so that we don't vectorize them
5361               // again.
5362               if (LS == LoadsState::Vectorize)
5363                 ++VectorizedCnt;
5364               else
5365                 ++ScatterVectorizeCnt;
5366               VectorizedLoads.insert(Slice.begin(), Slice.end());
5367               // If we vectorized initial block, no need to try to vectorize it
5368               // again.
5369               if (Cnt == StartIdx)
5370                 StartIdx += VF;
5371               break;
5372             case LoadsState::Gather:
5373               break;
5374             }
5375           }
5376         }
5377         // Check if the whole array was vectorized already - exit.
5378         if (StartIdx >= VL.size())
5379           break;
5380         // Found vectorizable parts - exit.
5381         if (!VectorizedLoads.empty())
5382           break;
5383       }
5384       if (!VectorizedLoads.empty()) {
5385         InstructionCost GatherCost = 0;
5386         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5387         bool NeedInsertSubvectorAnalysis =
5388             !NumParts || (VL.size() / VF) > NumParts;
5389         // Get the cost for gathered loads.
5390         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5391           if (VectorizedLoads.contains(VL[I]))
5392             continue;
5393           GatherCost += getGatherCost(VL.slice(I, VF));
5394         }
5395         // The cost for vectorized loads.
5396         InstructionCost ScalarsCost = 0;
5397         for (Value *V : VectorizedLoads) {
5398           auto *LI = cast<LoadInst>(V);
5399           ScalarsCost += TTI->getMemoryOpCost(
5400               Instruction::Load, LI->getType(), LI->getAlign(),
5401               LI->getPointerAddressSpace(), CostKind, LI);
5402         }
5403         auto *LI = cast<LoadInst>(E->getMainOp());
5404         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5405         Align Alignment = LI->getAlign();
5406         GatherCost +=
5407             VectorizedCnt *
5408             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5409                                  LI->getPointerAddressSpace(), CostKind, LI);
5410         GatherCost += ScatterVectorizeCnt *
5411                       TTI->getGatherScatterOpCost(
5412                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5413                           /*VariableMask=*/false, Alignment, CostKind, LI);
5414         if (NeedInsertSubvectorAnalysis) {
5415           // Add the cost for the subvectors insert.
5416           for (int I = VF, E = VL.size(); I < E; I += VF)
5417             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5418                                               None, I, LoadTy);
5419         }
5420         return ReuseShuffleCost + GatherCost - ScalarsCost;
5421       }
5422     }
5423     return ReuseShuffleCost + getGatherCost(VL);
5424   }
5425   InstructionCost CommonCost = 0;
5426   SmallVector<int> Mask;
5427   if (!E->ReorderIndices.empty()) {
5428     SmallVector<int> NewMask;
5429     if (E->getOpcode() == Instruction::Store) {
5430       // For stores the order is actually a mask.
5431       NewMask.resize(E->ReorderIndices.size());
5432       copy(E->ReorderIndices, NewMask.begin());
5433     } else {
5434       inversePermutation(E->ReorderIndices, NewMask);
5435     }
5436     ::addMask(Mask, NewMask);
5437   }
5438   if (NeedToShuffleReuses)
5439     ::addMask(Mask, E->ReuseShuffleIndices);
5440   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5441     CommonCost =
5442         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5443   assert((E->State == TreeEntry::Vectorize ||
5444           E->State == TreeEntry::ScatterVectorize) &&
5445          "Unhandled state");
5446   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5447   Instruction *VL0 = E->getMainOp();
5448   unsigned ShuffleOrOp =
5449       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5450   switch (ShuffleOrOp) {
5451     case Instruction::PHI:
5452       return 0;
5453 
5454     case Instruction::ExtractValue:
5455     case Instruction::ExtractElement: {
5456       // The common cost of removal ExtractElement/ExtractValue instructions +
5457       // the cost of shuffles, if required to resuffle the original vector.
5458       if (NeedToShuffleReuses) {
5459         unsigned Idx = 0;
5460         for (unsigned I : E->ReuseShuffleIndices) {
5461           if (ShuffleOrOp == Instruction::ExtractElement) {
5462             auto *EE = cast<ExtractElementInst>(VL[I]);
5463             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5464                                                   EE->getVectorOperandType(),
5465                                                   *getExtractIndex(EE));
5466           } else {
5467             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5468                                                   VecTy, Idx);
5469             ++Idx;
5470           }
5471         }
5472         Idx = EntryVF;
5473         for (Value *V : VL) {
5474           if (ShuffleOrOp == Instruction::ExtractElement) {
5475             auto *EE = cast<ExtractElementInst>(V);
5476             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5477                                                   EE->getVectorOperandType(),
5478                                                   *getExtractIndex(EE));
5479           } else {
5480             --Idx;
5481             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5482                                                   VecTy, Idx);
5483           }
5484         }
5485       }
5486       if (ShuffleOrOp == Instruction::ExtractValue) {
5487         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5488           auto *EI = cast<Instruction>(VL[I]);
5489           // Take credit for instruction that will become dead.
5490           if (EI->hasOneUse()) {
5491             Instruction *Ext = EI->user_back();
5492             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5493                 all_of(Ext->users(),
5494                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5495               // Use getExtractWithExtendCost() to calculate the cost of
5496               // extractelement/ext pair.
5497               CommonCost -= TTI->getExtractWithExtendCost(
5498                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5499               // Add back the cost of s|zext which is subtracted separately.
5500               CommonCost += TTI->getCastInstrCost(
5501                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5502                   TTI::getCastContextHint(Ext), CostKind, Ext);
5503               continue;
5504             }
5505           }
5506           CommonCost -=
5507               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5508         }
5509       } else {
5510         AdjustExtractsCost(CommonCost);
5511       }
5512       return CommonCost;
5513     }
5514     case Instruction::InsertElement: {
5515       assert(E->ReuseShuffleIndices.empty() &&
5516              "Unique insertelements only are expected.");
5517       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5518 
5519       unsigned const NumElts = SrcVecTy->getNumElements();
5520       unsigned const NumScalars = VL.size();
5521       APInt DemandedElts = APInt::getZero(NumElts);
5522       // TODO: Add support for Instruction::InsertValue.
5523       SmallVector<int> Mask;
5524       if (!E->ReorderIndices.empty()) {
5525         inversePermutation(E->ReorderIndices, Mask);
5526         Mask.append(NumElts - NumScalars, UndefMaskElem);
5527       } else {
5528         Mask.assign(NumElts, UndefMaskElem);
5529         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5530       }
5531       unsigned Offset = *getInsertIndex(VL0);
5532       bool IsIdentity = true;
5533       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5534       Mask.swap(PrevMask);
5535       for (unsigned I = 0; I < NumScalars; ++I) {
5536         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5537         DemandedElts.setBit(InsertIdx);
5538         IsIdentity &= InsertIdx - Offset == I;
5539         Mask[InsertIdx - Offset] = I;
5540       }
5541       assert(Offset < NumElts && "Failed to find vector index offset");
5542 
5543       InstructionCost Cost = 0;
5544       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5545                                             /*Insert*/ true, /*Extract*/ false);
5546 
5547       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5548         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5549         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5550         Cost += TTI->getShuffleCost(
5551             TargetTransformInfo::SK_PermuteSingleSrc,
5552             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5553       } else if (!IsIdentity) {
5554         auto *FirstInsert =
5555             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5556               return !is_contained(E->Scalars,
5557                                    cast<Instruction>(V)->getOperand(0));
5558             }));
5559         if (isUndefVector(FirstInsert->getOperand(0))) {
5560           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5561         } else {
5562           SmallVector<int> InsertMask(NumElts);
5563           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5564           for (unsigned I = 0; I < NumElts; I++) {
5565             if (Mask[I] != UndefMaskElem)
5566               InsertMask[Offset + I] = NumElts + I;
5567           }
5568           Cost +=
5569               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5570         }
5571       }
5572 
5573       return Cost;
5574     }
5575     case Instruction::ZExt:
5576     case Instruction::SExt:
5577     case Instruction::FPToUI:
5578     case Instruction::FPToSI:
5579     case Instruction::FPExt:
5580     case Instruction::PtrToInt:
5581     case Instruction::IntToPtr:
5582     case Instruction::SIToFP:
5583     case Instruction::UIToFP:
5584     case Instruction::Trunc:
5585     case Instruction::FPTrunc:
5586     case Instruction::BitCast: {
5587       Type *SrcTy = VL0->getOperand(0)->getType();
5588       InstructionCost ScalarEltCost =
5589           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5590                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5591       if (NeedToShuffleReuses) {
5592         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5593       }
5594 
5595       // Calculate the cost of this instruction.
5596       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5597 
5598       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5599       InstructionCost VecCost = 0;
5600       // Check if the values are candidates to demote.
5601       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5602         VecCost = CommonCost + TTI->getCastInstrCost(
5603                                    E->getOpcode(), VecTy, SrcVecTy,
5604                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5605       }
5606       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5607       return VecCost - ScalarCost;
5608     }
5609     case Instruction::FCmp:
5610     case Instruction::ICmp:
5611     case Instruction::Select: {
5612       // Calculate the cost of this instruction.
5613       InstructionCost ScalarEltCost =
5614           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5615                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5616       if (NeedToShuffleReuses) {
5617         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5618       }
5619       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5620       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5621 
5622       // Check if all entries in VL are either compares or selects with compares
5623       // as condition that have the same predicates.
5624       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5625       bool First = true;
5626       for (auto *V : VL) {
5627         CmpInst::Predicate CurrentPred;
5628         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5629         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5630              !match(V, MatchCmp)) ||
5631             (!First && VecPred != CurrentPred)) {
5632           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5633           break;
5634         }
5635         First = false;
5636         VecPred = CurrentPred;
5637       }
5638 
5639       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5640           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5641       // Check if it is possible and profitable to use min/max for selects in
5642       // VL.
5643       //
5644       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5645       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5646         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5647                                           {VecTy, VecTy});
5648         InstructionCost IntrinsicCost =
5649             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5650         // If the selects are the only uses of the compares, they will be dead
5651         // and we can adjust the cost by removing their cost.
5652         if (IntrinsicAndUse.second)
5653           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5654                                                    MaskTy, VecPred, CostKind);
5655         VecCost = std::min(VecCost, IntrinsicCost);
5656       }
5657       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5658       return CommonCost + VecCost - ScalarCost;
5659     }
5660     case Instruction::FNeg:
5661     case Instruction::Add:
5662     case Instruction::FAdd:
5663     case Instruction::Sub:
5664     case Instruction::FSub:
5665     case Instruction::Mul:
5666     case Instruction::FMul:
5667     case Instruction::UDiv:
5668     case Instruction::SDiv:
5669     case Instruction::FDiv:
5670     case Instruction::URem:
5671     case Instruction::SRem:
5672     case Instruction::FRem:
5673     case Instruction::Shl:
5674     case Instruction::LShr:
5675     case Instruction::AShr:
5676     case Instruction::And:
5677     case Instruction::Or:
5678     case Instruction::Xor: {
5679       // Certain instructions can be cheaper to vectorize if they have a
5680       // constant second vector operand.
5681       TargetTransformInfo::OperandValueKind Op1VK =
5682           TargetTransformInfo::OK_AnyValue;
5683       TargetTransformInfo::OperandValueKind Op2VK =
5684           TargetTransformInfo::OK_UniformConstantValue;
5685       TargetTransformInfo::OperandValueProperties Op1VP =
5686           TargetTransformInfo::OP_None;
5687       TargetTransformInfo::OperandValueProperties Op2VP =
5688           TargetTransformInfo::OP_PowerOf2;
5689 
5690       // If all operands are exactly the same ConstantInt then set the
5691       // operand kind to OK_UniformConstantValue.
5692       // If instead not all operands are constants, then set the operand kind
5693       // to OK_AnyValue. If all operands are constants but not the same,
5694       // then set the operand kind to OK_NonUniformConstantValue.
5695       ConstantInt *CInt0 = nullptr;
5696       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5697         const Instruction *I = cast<Instruction>(VL[i]);
5698         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5699         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5700         if (!CInt) {
5701           Op2VK = TargetTransformInfo::OK_AnyValue;
5702           Op2VP = TargetTransformInfo::OP_None;
5703           break;
5704         }
5705         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5706             !CInt->getValue().isPowerOf2())
5707           Op2VP = TargetTransformInfo::OP_None;
5708         if (i == 0) {
5709           CInt0 = CInt;
5710           continue;
5711         }
5712         if (CInt0 != CInt)
5713           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5714       }
5715 
5716       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5717       InstructionCost ScalarEltCost =
5718           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5719                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5720       if (NeedToShuffleReuses) {
5721         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5722       }
5723       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5724       InstructionCost VecCost =
5725           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5726                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5727       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5728       return CommonCost + VecCost - ScalarCost;
5729     }
5730     case Instruction::GetElementPtr: {
5731       TargetTransformInfo::OperandValueKind Op1VK =
5732           TargetTransformInfo::OK_AnyValue;
5733       TargetTransformInfo::OperandValueKind Op2VK =
5734           TargetTransformInfo::OK_UniformConstantValue;
5735 
5736       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5737           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5738       if (NeedToShuffleReuses) {
5739         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5740       }
5741       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5742       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5743           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5744       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5745       return CommonCost + VecCost - ScalarCost;
5746     }
5747     case Instruction::Load: {
5748       // Cost of wide load - cost of scalar loads.
5749       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5750       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5751           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5752       if (NeedToShuffleReuses) {
5753         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5754       }
5755       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5756       InstructionCost VecLdCost;
5757       if (E->State == TreeEntry::Vectorize) {
5758         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5759                                          CostKind, VL0);
5760       } else {
5761         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5762         Align CommonAlignment = Alignment;
5763         for (Value *V : VL)
5764           CommonAlignment =
5765               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5766         VecLdCost = TTI->getGatherScatterOpCost(
5767             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5768             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5769       }
5770       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5771       return CommonCost + VecLdCost - ScalarLdCost;
5772     }
5773     case Instruction::Store: {
5774       // We know that we can merge the stores. Calculate the cost.
5775       bool IsReorder = !E->ReorderIndices.empty();
5776       auto *SI =
5777           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5778       Align Alignment = SI->getAlign();
5779       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5780           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5781       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5782       InstructionCost VecStCost = TTI->getMemoryOpCost(
5783           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5784       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5785       return CommonCost + VecStCost - ScalarStCost;
5786     }
5787     case Instruction::Call: {
5788       CallInst *CI = cast<CallInst>(VL0);
5789       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5790 
5791       // Calculate the cost of the scalar and vector calls.
5792       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5793       InstructionCost ScalarEltCost =
5794           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5795       if (NeedToShuffleReuses) {
5796         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5797       }
5798       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5799 
5800       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5801       InstructionCost VecCallCost =
5802           std::min(VecCallCosts.first, VecCallCosts.second);
5803 
5804       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5805                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5806                         << " for " << *CI << "\n");
5807 
5808       return CommonCost + VecCallCost - ScalarCallCost;
5809     }
5810     case Instruction::ShuffleVector: {
5811       assert(E->isAltShuffle() &&
5812              ((Instruction::isBinaryOp(E->getOpcode()) &&
5813                Instruction::isBinaryOp(E->getAltOpcode())) ||
5814               (Instruction::isCast(E->getOpcode()) &&
5815                Instruction::isCast(E->getAltOpcode())) ||
5816               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5817              "Invalid Shuffle Vector Operand");
5818       InstructionCost ScalarCost = 0;
5819       if (NeedToShuffleReuses) {
5820         for (unsigned Idx : E->ReuseShuffleIndices) {
5821           Instruction *I = cast<Instruction>(VL[Idx]);
5822           CommonCost -= TTI->getInstructionCost(I, CostKind);
5823         }
5824         for (Value *V : VL) {
5825           Instruction *I = cast<Instruction>(V);
5826           CommonCost += TTI->getInstructionCost(I, CostKind);
5827         }
5828       }
5829       for (Value *V : VL) {
5830         Instruction *I = cast<Instruction>(V);
5831         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5832         ScalarCost += TTI->getInstructionCost(I, CostKind);
5833       }
5834       // VecCost is equal to sum of the cost of creating 2 vectors
5835       // and the cost of creating shuffle.
5836       InstructionCost VecCost = 0;
5837       // Try to find the previous shuffle node with the same operands and same
5838       // main/alternate ops.
5839       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5840         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5841           if (TE.get() == E)
5842             break;
5843           if (TE->isAltShuffle() &&
5844               ((TE->getOpcode() == E->getOpcode() &&
5845                 TE->getAltOpcode() == E->getAltOpcode()) ||
5846                (TE->getOpcode() == E->getAltOpcode() &&
5847                 TE->getAltOpcode() == E->getOpcode())) &&
5848               TE->hasEqualOperands(*E))
5849             return true;
5850         }
5851         return false;
5852       };
5853       if (TryFindNodeWithEqualOperands()) {
5854         LLVM_DEBUG({
5855           dbgs() << "SLP: diamond match for alternate node found.\n";
5856           E->dump();
5857         });
5858         // No need to add new vector costs here since we're going to reuse
5859         // same main/alternate vector ops, just do different shuffling.
5860       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5861         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5862         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5863                                                CostKind);
5864       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5865         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5866                                           Builder.getInt1Ty(),
5867                                           CI0->getPredicate(), CostKind, VL0);
5868         VecCost += TTI->getCmpSelInstrCost(
5869             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5870             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5871             E->getAltOp());
5872       } else {
5873         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5874         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5875         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5876         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5877         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5878                                         TTI::CastContextHint::None, CostKind);
5879         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5880                                          TTI::CastContextHint::None, CostKind);
5881       }
5882 
5883       SmallVector<int> Mask;
5884       buildShuffleEntryMask(
5885           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5886           [E](Instruction *I) {
5887             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5888             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5889           },
5890           Mask);
5891       CommonCost =
5892           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5893       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5894       return CommonCost + VecCost - ScalarCost;
5895     }
5896     default:
5897       llvm_unreachable("Unknown instruction");
5898   }
5899 }
5900 
5901 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5902   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5903                     << VectorizableTree.size() << " is fully vectorizable .\n");
5904 
5905   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5906     SmallVector<int> Mask;
5907     return TE->State == TreeEntry::NeedToGather &&
5908            !any_of(TE->Scalars,
5909                    [this](Value *V) { return EphValues.contains(V); }) &&
5910            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5911             TE->Scalars.size() < Limit ||
5912             ((TE->getOpcode() == Instruction::ExtractElement ||
5913               all_of(TE->Scalars,
5914                      [](Value *V) {
5915                        return isa<ExtractElementInst, UndefValue>(V);
5916                      })) &&
5917              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5918             (TE->State == TreeEntry::NeedToGather &&
5919              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5920   };
5921 
5922   // We only handle trees of heights 1 and 2.
5923   if (VectorizableTree.size() == 1 &&
5924       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5925        (ForReduction &&
5926         AreVectorizableGathers(VectorizableTree[0].get(),
5927                                VectorizableTree[0]->Scalars.size()) &&
5928         VectorizableTree[0]->getVectorFactor() > 2)))
5929     return true;
5930 
5931   if (VectorizableTree.size() != 2)
5932     return false;
5933 
5934   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5935   // with the second gather nodes if they have less scalar operands rather than
5936   // the initial tree element (may be profitable to shuffle the second gather)
5937   // or they are extractelements, which form shuffle.
5938   SmallVector<int> Mask;
5939   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5940       AreVectorizableGathers(VectorizableTree[1].get(),
5941                              VectorizableTree[0]->Scalars.size()))
5942     return true;
5943 
5944   // Gathering cost would be too much for tiny trees.
5945   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5946       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5947        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5948     return false;
5949 
5950   return true;
5951 }
5952 
5953 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5954                                        TargetTransformInfo *TTI,
5955                                        bool MustMatchOrInst) {
5956   // Look past the root to find a source value. Arbitrarily follow the
5957   // path through operand 0 of any 'or'. Also, peek through optional
5958   // shift-left-by-multiple-of-8-bits.
5959   Value *ZextLoad = Root;
5960   const APInt *ShAmtC;
5961   bool FoundOr = false;
5962   while (!isa<ConstantExpr>(ZextLoad) &&
5963          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5964           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5965            ShAmtC->urem(8) == 0))) {
5966     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5967     ZextLoad = BinOp->getOperand(0);
5968     if (BinOp->getOpcode() == Instruction::Or)
5969       FoundOr = true;
5970   }
5971   // Check if the input is an extended load of the required or/shift expression.
5972   Value *Load;
5973   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5974       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5975     return false;
5976 
5977   // Require that the total load bit width is a legal integer type.
5978   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5979   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5980   Type *SrcTy = Load->getType();
5981   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5982   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5983     return false;
5984 
5985   // Everything matched - assume that we can fold the whole sequence using
5986   // load combining.
5987   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5988              << *(cast<Instruction>(Root)) << "\n");
5989 
5990   return true;
5991 }
5992 
5993 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5994   if (RdxKind != RecurKind::Or)
5995     return false;
5996 
5997   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5998   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5999   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6000                                     /* MatchOr */ false);
6001 }
6002 
6003 bool BoUpSLP::isLoadCombineCandidate() const {
6004   // Peek through a final sequence of stores and check if all operations are
6005   // likely to be load-combined.
6006   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6007   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6008     Value *X;
6009     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6010         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6011       return false;
6012   }
6013   return true;
6014 }
6015 
6016 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6017   // No need to vectorize inserts of gathered values.
6018   if (VectorizableTree.size() == 2 &&
6019       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6020       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6021     return true;
6022 
6023   // We can vectorize the tree if its size is greater than or equal to the
6024   // minimum size specified by the MinTreeSize command line option.
6025   if (VectorizableTree.size() >= MinTreeSize)
6026     return false;
6027 
6028   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6029   // can vectorize it if we can prove it fully vectorizable.
6030   if (isFullyVectorizableTinyTree(ForReduction))
6031     return false;
6032 
6033   assert(VectorizableTree.empty()
6034              ? ExternalUses.empty()
6035              : true && "We shouldn't have any external users");
6036 
6037   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6038   // vectorizable.
6039   return true;
6040 }
6041 
6042 InstructionCost BoUpSLP::getSpillCost() const {
6043   // Walk from the bottom of the tree to the top, tracking which values are
6044   // live. When we see a call instruction that is not part of our tree,
6045   // query TTI to see if there is a cost to keeping values live over it
6046   // (for example, if spills and fills are required).
6047   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6048   InstructionCost Cost = 0;
6049 
6050   SmallPtrSet<Instruction*, 4> LiveValues;
6051   Instruction *PrevInst = nullptr;
6052 
6053   // The entries in VectorizableTree are not necessarily ordered by their
6054   // position in basic blocks. Collect them and order them by dominance so later
6055   // instructions are guaranteed to be visited first. For instructions in
6056   // different basic blocks, we only scan to the beginning of the block, so
6057   // their order does not matter, as long as all instructions in a basic block
6058   // are grouped together. Using dominance ensures a deterministic order.
6059   SmallVector<Instruction *, 16> OrderedScalars;
6060   for (const auto &TEPtr : VectorizableTree) {
6061     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6062     if (!Inst)
6063       continue;
6064     OrderedScalars.push_back(Inst);
6065   }
6066   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6067     auto *NodeA = DT->getNode(A->getParent());
6068     auto *NodeB = DT->getNode(B->getParent());
6069     assert(NodeA && "Should only process reachable instructions");
6070     assert(NodeB && "Should only process reachable instructions");
6071     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6072            "Different nodes should have different DFS numbers");
6073     if (NodeA != NodeB)
6074       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6075     return B->comesBefore(A);
6076   });
6077 
6078   for (Instruction *Inst : OrderedScalars) {
6079     if (!PrevInst) {
6080       PrevInst = Inst;
6081       continue;
6082     }
6083 
6084     // Update LiveValues.
6085     LiveValues.erase(PrevInst);
6086     for (auto &J : PrevInst->operands()) {
6087       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6088         LiveValues.insert(cast<Instruction>(&*J));
6089     }
6090 
6091     LLVM_DEBUG({
6092       dbgs() << "SLP: #LV: " << LiveValues.size();
6093       for (auto *X : LiveValues)
6094         dbgs() << " " << X->getName();
6095       dbgs() << ", Looking at ";
6096       Inst->dump();
6097     });
6098 
6099     // Now find the sequence of instructions between PrevInst and Inst.
6100     unsigned NumCalls = 0;
6101     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6102                                  PrevInstIt =
6103                                      PrevInst->getIterator().getReverse();
6104     while (InstIt != PrevInstIt) {
6105       if (PrevInstIt == PrevInst->getParent()->rend()) {
6106         PrevInstIt = Inst->getParent()->rbegin();
6107         continue;
6108       }
6109 
6110       // Debug information does not impact spill cost.
6111       if ((isa<CallInst>(&*PrevInstIt) &&
6112            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6113           &*PrevInstIt != PrevInst)
6114         NumCalls++;
6115 
6116       ++PrevInstIt;
6117     }
6118 
6119     if (NumCalls) {
6120       SmallVector<Type*, 4> V;
6121       for (auto *II : LiveValues) {
6122         auto *ScalarTy = II->getType();
6123         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6124           ScalarTy = VectorTy->getElementType();
6125         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6126       }
6127       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6128     }
6129 
6130     PrevInst = Inst;
6131   }
6132 
6133   return Cost;
6134 }
6135 
6136 /// Check if two insertelement instructions are from the same buildvector.
6137 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6138                                             InsertElementInst *V) {
6139   // Instructions must be from the same basic blocks.
6140   if (VU->getParent() != V->getParent())
6141     return false;
6142   // Checks if 2 insertelements are from the same buildvector.
6143   if (VU->getType() != V->getType())
6144     return false;
6145   // Multiple used inserts are separate nodes.
6146   if (!VU->hasOneUse() && !V->hasOneUse())
6147     return false;
6148   auto *IE1 = VU;
6149   auto *IE2 = V;
6150   // Go through the vector operand of insertelement instructions trying to find
6151   // either VU as the original vector for IE2 or V as the original vector for
6152   // IE1.
6153   do {
6154     if (IE2 == VU || IE1 == V)
6155       return true;
6156     if (IE1) {
6157       if (IE1 != VU && !IE1->hasOneUse())
6158         IE1 = nullptr;
6159       else
6160         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6161     }
6162     if (IE2) {
6163       if (IE2 != V && !IE2->hasOneUse())
6164         IE2 = nullptr;
6165       else
6166         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6167     }
6168   } while (IE1 || IE2);
6169   return false;
6170 }
6171 
6172 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6173   InstructionCost Cost = 0;
6174   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6175                     << VectorizableTree.size() << ".\n");
6176 
6177   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6178 
6179   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6180     TreeEntry &TE = *VectorizableTree[I];
6181 
6182     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6183     Cost += C;
6184     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6185                       << " for bundle that starts with " << *TE.Scalars[0]
6186                       << ".\n"
6187                       << "SLP: Current total cost = " << Cost << "\n");
6188   }
6189 
6190   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6191   InstructionCost ExtractCost = 0;
6192   SmallVector<unsigned> VF;
6193   SmallVector<SmallVector<int>> ShuffleMask;
6194   SmallVector<Value *> FirstUsers;
6195   SmallVector<APInt> DemandedElts;
6196   for (ExternalUser &EU : ExternalUses) {
6197     // We only add extract cost once for the same scalar.
6198     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6199         !ExtractCostCalculated.insert(EU.Scalar).second)
6200       continue;
6201 
6202     // Uses by ephemeral values are free (because the ephemeral value will be
6203     // removed prior to code generation, and so the extraction will be
6204     // removed as well).
6205     if (EphValues.count(EU.User))
6206       continue;
6207 
6208     // No extract cost for vector "scalar"
6209     if (isa<FixedVectorType>(EU.Scalar->getType()))
6210       continue;
6211 
6212     // Already counted the cost for external uses when tried to adjust the cost
6213     // for extractelements, no need to add it again.
6214     if (isa<ExtractElementInst>(EU.Scalar))
6215       continue;
6216 
6217     // If found user is an insertelement, do not calculate extract cost but try
6218     // to detect it as a final shuffled/identity match.
6219     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6220       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6221         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6222         if (InsertIdx) {
6223           auto *It = find_if(FirstUsers, [VU](Value *V) {
6224             return areTwoInsertFromSameBuildVector(VU,
6225                                                    cast<InsertElementInst>(V));
6226           });
6227           int VecId = -1;
6228           if (It == FirstUsers.end()) {
6229             VF.push_back(FTy->getNumElements());
6230             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6231             // Find the insertvector, vectorized in tree, if any.
6232             Value *Base = VU;
6233             while (isa<InsertElementInst>(Base)) {
6234               // Build the mask for the vectorized insertelement instructions.
6235               if (const TreeEntry *E = getTreeEntry(Base)) {
6236                 VU = cast<InsertElementInst>(Base);
6237                 do {
6238                   int Idx = E->findLaneForValue(Base);
6239                   ShuffleMask.back()[Idx] = Idx;
6240                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6241                 } while (E == getTreeEntry(Base));
6242                 break;
6243               }
6244               Base = cast<InsertElementInst>(Base)->getOperand(0);
6245             }
6246             FirstUsers.push_back(VU);
6247             DemandedElts.push_back(APInt::getZero(VF.back()));
6248             VecId = FirstUsers.size() - 1;
6249           } else {
6250             VecId = std::distance(FirstUsers.begin(), It);
6251           }
6252           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6253           DemandedElts[VecId].setBit(*InsertIdx);
6254           continue;
6255         }
6256       }
6257     }
6258 
6259     // If we plan to rewrite the tree in a smaller type, we will need to sign
6260     // extend the extracted value back to the original type. Here, we account
6261     // for the extract and the added cost of the sign extend if needed.
6262     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6263     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6264     if (MinBWs.count(ScalarRoot)) {
6265       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6266       auto Extend =
6267           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6268       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6269       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6270                                                    VecTy, EU.Lane);
6271     } else {
6272       ExtractCost +=
6273           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6274     }
6275   }
6276 
6277   InstructionCost SpillCost = getSpillCost();
6278   Cost += SpillCost + ExtractCost;
6279   if (FirstUsers.size() == 1) {
6280     int Limit = ShuffleMask.front().size() * 2;
6281     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6282         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6283       InstructionCost C = TTI->getShuffleCost(
6284           TTI::SK_PermuteSingleSrc,
6285           cast<FixedVectorType>(FirstUsers.front()->getType()),
6286           ShuffleMask.front());
6287       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6288                         << " for final shuffle of insertelement external users "
6289                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6290                         << "SLP: Current total cost = " << Cost << "\n");
6291       Cost += C;
6292     }
6293     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6294         cast<FixedVectorType>(FirstUsers.front()->getType()),
6295         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6296     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6297                       << " for insertelements gather.\n"
6298                       << "SLP: Current total cost = " << Cost << "\n");
6299     Cost -= InsertCost;
6300   } else if (FirstUsers.size() >= 2) {
6301     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6302     // Combined masks of the first 2 vectors.
6303     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6304     copy(ShuffleMask.front(), CombinedMask.begin());
6305     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6306     auto *VecTy = FixedVectorType::get(
6307         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6308         MaxVF);
6309     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6310       if (ShuffleMask[1][I] != UndefMaskElem) {
6311         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6312         CombinedDemandedElts.setBit(I);
6313       }
6314     }
6315     InstructionCost C =
6316         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6317     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6318                       << " for final shuffle of vector node and external "
6319                          "insertelement users "
6320                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6321                       << "SLP: Current total cost = " << Cost << "\n");
6322     Cost += C;
6323     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6324         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6325     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6326                       << " for insertelements gather.\n"
6327                       << "SLP: Current total cost = " << Cost << "\n");
6328     Cost -= InsertCost;
6329     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6330       // Other elements - permutation of 2 vectors (the initial one and the
6331       // next Ith incoming vector).
6332       unsigned VF = ShuffleMask[I].size();
6333       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6334         int Mask = ShuffleMask[I][Idx];
6335         if (Mask != UndefMaskElem)
6336           CombinedMask[Idx] = MaxVF + Mask;
6337         else if (CombinedMask[Idx] != UndefMaskElem)
6338           CombinedMask[Idx] = Idx;
6339       }
6340       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6341         if (CombinedMask[Idx] != UndefMaskElem)
6342           CombinedMask[Idx] = Idx;
6343       InstructionCost C =
6344           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6345       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6346                         << " for final shuffle of vector node and external "
6347                            "insertelement users "
6348                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6349                         << "SLP: Current total cost = " << Cost << "\n");
6350       Cost += C;
6351       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6352           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6353           /*Insert*/ true, /*Extract*/ false);
6354       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6355                         << " for insertelements gather.\n"
6356                         << "SLP: Current total cost = " << Cost << "\n");
6357       Cost -= InsertCost;
6358     }
6359   }
6360 
6361 #ifndef NDEBUG
6362   SmallString<256> Str;
6363   {
6364     raw_svector_ostream OS(Str);
6365     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6366        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6367        << "SLP: Total Cost = " << Cost << ".\n";
6368   }
6369   LLVM_DEBUG(dbgs() << Str);
6370   if (ViewSLPTree)
6371     ViewGraph(this, "SLP" + F->getName(), false, Str);
6372 #endif
6373 
6374   return Cost;
6375 }
6376 
6377 Optional<TargetTransformInfo::ShuffleKind>
6378 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6379                                SmallVectorImpl<const TreeEntry *> &Entries) {
6380   // TODO: currently checking only for Scalars in the tree entry, need to count
6381   // reused elements too for better cost estimation.
6382   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6383   Entries.clear();
6384   // Build a lists of values to tree entries.
6385   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6386   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6387     if (EntryPtr.get() == TE)
6388       break;
6389     if (EntryPtr->State != TreeEntry::NeedToGather)
6390       continue;
6391     for (Value *V : EntryPtr->Scalars)
6392       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6393   }
6394   // Find all tree entries used by the gathered values. If no common entries
6395   // found - not a shuffle.
6396   // Here we build a set of tree nodes for each gathered value and trying to
6397   // find the intersection between these sets. If we have at least one common
6398   // tree node for each gathered value - we have just a permutation of the
6399   // single vector. If we have 2 different sets, we're in situation where we
6400   // have a permutation of 2 input vectors.
6401   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6402   DenseMap<Value *, int> UsedValuesEntry;
6403   for (Value *V : TE->Scalars) {
6404     if (isa<UndefValue>(V))
6405       continue;
6406     // Build a list of tree entries where V is used.
6407     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6408     auto It = ValueToTEs.find(V);
6409     if (It != ValueToTEs.end())
6410       VToTEs = It->second;
6411     if (const TreeEntry *VTE = getTreeEntry(V))
6412       VToTEs.insert(VTE);
6413     if (VToTEs.empty())
6414       return None;
6415     if (UsedTEs.empty()) {
6416       // The first iteration, just insert the list of nodes to vector.
6417       UsedTEs.push_back(VToTEs);
6418     } else {
6419       // Need to check if there are any previously used tree nodes which use V.
6420       // If there are no such nodes, consider that we have another one input
6421       // vector.
6422       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6423       unsigned Idx = 0;
6424       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6425         // Do we have a non-empty intersection of previously listed tree entries
6426         // and tree entries using current V?
6427         set_intersect(VToTEs, Set);
6428         if (!VToTEs.empty()) {
6429           // Yes, write the new subset and continue analysis for the next
6430           // scalar.
6431           Set.swap(VToTEs);
6432           break;
6433         }
6434         VToTEs = SavedVToTEs;
6435         ++Idx;
6436       }
6437       // No non-empty intersection found - need to add a second set of possible
6438       // source vectors.
6439       if (Idx == UsedTEs.size()) {
6440         // If the number of input vectors is greater than 2 - not a permutation,
6441         // fallback to the regular gather.
6442         if (UsedTEs.size() == 2)
6443           return None;
6444         UsedTEs.push_back(SavedVToTEs);
6445         Idx = UsedTEs.size() - 1;
6446       }
6447       UsedValuesEntry.try_emplace(V, Idx);
6448     }
6449   }
6450 
6451   unsigned VF = 0;
6452   if (UsedTEs.size() == 1) {
6453     // Try to find the perfect match in another gather node at first.
6454     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6455       return EntryPtr->isSame(TE->Scalars);
6456     });
6457     if (It != UsedTEs.front().end()) {
6458       Entries.push_back(*It);
6459       std::iota(Mask.begin(), Mask.end(), 0);
6460       return TargetTransformInfo::SK_PermuteSingleSrc;
6461     }
6462     // No perfect match, just shuffle, so choose the first tree node.
6463     Entries.push_back(*UsedTEs.front().begin());
6464   } else {
6465     // Try to find nodes with the same vector factor.
6466     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6467     DenseMap<int, const TreeEntry *> VFToTE;
6468     for (const TreeEntry *TE : UsedTEs.front())
6469       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6470     for (const TreeEntry *TE : UsedTEs.back()) {
6471       auto It = VFToTE.find(TE->getVectorFactor());
6472       if (It != VFToTE.end()) {
6473         VF = It->first;
6474         Entries.push_back(It->second);
6475         Entries.push_back(TE);
6476         break;
6477       }
6478     }
6479     // No 2 source vectors with the same vector factor - give up and do regular
6480     // gather.
6481     if (Entries.empty())
6482       return None;
6483   }
6484 
6485   // Build a shuffle mask for better cost estimation and vector emission.
6486   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6487     Value *V = TE->Scalars[I];
6488     if (isa<UndefValue>(V))
6489       continue;
6490     unsigned Idx = UsedValuesEntry.lookup(V);
6491     const TreeEntry *VTE = Entries[Idx];
6492     int FoundLane = VTE->findLaneForValue(V);
6493     Mask[I] = Idx * VF + FoundLane;
6494     // Extra check required by isSingleSourceMaskImpl function (called by
6495     // ShuffleVectorInst::isSingleSourceMask).
6496     if (Mask[I] >= 2 * E)
6497       return None;
6498   }
6499   switch (Entries.size()) {
6500   case 1:
6501     return TargetTransformInfo::SK_PermuteSingleSrc;
6502   case 2:
6503     return TargetTransformInfo::SK_PermuteTwoSrc;
6504   default:
6505     break;
6506   }
6507   return None;
6508 }
6509 
6510 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6511                                        const APInt &ShuffledIndices,
6512                                        bool NeedToShuffle) const {
6513   InstructionCost Cost =
6514       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6515                                     /*Extract*/ false);
6516   if (NeedToShuffle)
6517     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6518   return Cost;
6519 }
6520 
6521 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6522   // Find the type of the operands in VL.
6523   Type *ScalarTy = VL[0]->getType();
6524   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6525     ScalarTy = SI->getValueOperand()->getType();
6526   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6527   bool DuplicateNonConst = false;
6528   // Find the cost of inserting/extracting values from the vector.
6529   // Check if the same elements are inserted several times and count them as
6530   // shuffle candidates.
6531   APInt ShuffledElements = APInt::getZero(VL.size());
6532   DenseSet<Value *> UniqueElements;
6533   // Iterate in reverse order to consider insert elements with the high cost.
6534   for (unsigned I = VL.size(); I > 0; --I) {
6535     unsigned Idx = I - 1;
6536     // No need to shuffle duplicates for constants.
6537     if (isConstant(VL[Idx])) {
6538       ShuffledElements.setBit(Idx);
6539       continue;
6540     }
6541     if (!UniqueElements.insert(VL[Idx]).second) {
6542       DuplicateNonConst = true;
6543       ShuffledElements.setBit(Idx);
6544     }
6545   }
6546   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6547 }
6548 
6549 // Perform operand reordering on the instructions in VL and return the reordered
6550 // operands in Left and Right.
6551 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6552                                              SmallVectorImpl<Value *> &Left,
6553                                              SmallVectorImpl<Value *> &Right,
6554                                              const DataLayout &DL,
6555                                              ScalarEvolution &SE,
6556                                              const BoUpSLP &R) {
6557   if (VL.empty())
6558     return;
6559   VLOperands Ops(VL, DL, SE, R);
6560   // Reorder the operands in place.
6561   Ops.reorder();
6562   Left = Ops.getVL(0);
6563   Right = Ops.getVL(1);
6564 }
6565 
6566 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6567   // Get the basic block this bundle is in. All instructions in the bundle
6568   // should be in this block.
6569   auto *Front = E->getMainOp();
6570   auto *BB = Front->getParent();
6571   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6572     auto *I = cast<Instruction>(V);
6573     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6574   }));
6575 
6576   auto &&FindLastInst = [E, Front]() {
6577     Instruction *LastInst = Front;
6578     for (Value *V : E->Scalars) {
6579       auto *I = dyn_cast<Instruction>(V);
6580       if (!I)
6581         continue;
6582       if (LastInst->comesBefore(I))
6583         LastInst = I;
6584     }
6585     return LastInst;
6586   };
6587 
6588   auto &&FindFirstInst = [E, Front]() {
6589     Instruction *FirstInst = Front;
6590     for (Value *V : E->Scalars) {
6591       auto *I = dyn_cast<Instruction>(V);
6592       if (!I)
6593         continue;
6594       if (I->comesBefore(FirstInst))
6595         FirstInst = I;
6596     }
6597     return FirstInst;
6598   };
6599 
6600   // Set the insert point to the beginning of the basic block if the entry
6601   // should not be scheduled.
6602   if (E->State != TreeEntry::NeedToGather &&
6603       doesNotNeedToSchedule(E->Scalars)) {
6604     BasicBlock::iterator InsertPt;
6605     if (all_of(E->Scalars, isUsedOutsideBlock))
6606       InsertPt = FindLastInst()->getIterator();
6607     else
6608       InsertPt = FindFirstInst()->getIterator();
6609     Builder.SetInsertPoint(BB, InsertPt);
6610     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6611     return;
6612   }
6613 
6614   // The last instruction in the bundle in program order.
6615   Instruction *LastInst = nullptr;
6616 
6617   // Find the last instruction. The common case should be that BB has been
6618   // scheduled, and the last instruction is VL.back(). So we start with
6619   // VL.back() and iterate over schedule data until we reach the end of the
6620   // bundle. The end of the bundle is marked by null ScheduleData.
6621   if (BlocksSchedules.count(BB)) {
6622     Value *V = E->isOneOf(E->Scalars.back());
6623     if (doesNotNeedToBeScheduled(V))
6624       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6625     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6626     if (Bundle && Bundle->isPartOfBundle())
6627       for (; Bundle; Bundle = Bundle->NextInBundle)
6628         if (Bundle->OpValue == Bundle->Inst)
6629           LastInst = Bundle->Inst;
6630   }
6631 
6632   // LastInst can still be null at this point if there's either not an entry
6633   // for BB in BlocksSchedules or there's no ScheduleData available for
6634   // VL.back(). This can be the case if buildTree_rec aborts for various
6635   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6636   // size is reached, etc.). ScheduleData is initialized in the scheduling
6637   // "dry-run".
6638   //
6639   // If this happens, we can still find the last instruction by brute force. We
6640   // iterate forwards from Front (inclusive) until we either see all
6641   // instructions in the bundle or reach the end of the block. If Front is the
6642   // last instruction in program order, LastInst will be set to Front, and we
6643   // will visit all the remaining instructions in the block.
6644   //
6645   // One of the reasons we exit early from buildTree_rec is to place an upper
6646   // bound on compile-time. Thus, taking an additional compile-time hit here is
6647   // not ideal. However, this should be exceedingly rare since it requires that
6648   // we both exit early from buildTree_rec and that the bundle be out-of-order
6649   // (causing us to iterate all the way to the end of the block).
6650   if (!LastInst)
6651     LastInst = FindLastInst();
6652   assert(LastInst && "Failed to find last instruction in bundle");
6653 
6654   // Set the insertion point after the last instruction in the bundle. Set the
6655   // debug location to Front.
6656   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6657   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6658 }
6659 
6660 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6661   // List of instructions/lanes from current block and/or the blocks which are
6662   // part of the current loop. These instructions will be inserted at the end to
6663   // make it possible to optimize loops and hoist invariant instructions out of
6664   // the loops body with better chances for success.
6665   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6666   SmallSet<int, 4> PostponedIndices;
6667   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6668   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6669     SmallPtrSet<BasicBlock *, 4> Visited;
6670     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6671       InsertBB = InsertBB->getSinglePredecessor();
6672     return InsertBB && InsertBB == InstBB;
6673   };
6674   for (int I = 0, E = VL.size(); I < E; ++I) {
6675     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6676       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6677            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6678           PostponedIndices.insert(I).second)
6679         PostponedInsts.emplace_back(Inst, I);
6680   }
6681 
6682   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6683     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6684     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6685     if (!InsElt)
6686       return Vec;
6687     GatherShuffleSeq.insert(InsElt);
6688     CSEBlocks.insert(InsElt->getParent());
6689     // Add to our 'need-to-extract' list.
6690     if (TreeEntry *Entry = getTreeEntry(V)) {
6691       // Find which lane we need to extract.
6692       unsigned FoundLane = Entry->findLaneForValue(V);
6693       ExternalUses.emplace_back(V, InsElt, FoundLane);
6694     }
6695     return Vec;
6696   };
6697   Value *Val0 =
6698       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6699   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6700   Value *Vec = PoisonValue::get(VecTy);
6701   SmallVector<int> NonConsts;
6702   // Insert constant values at first.
6703   for (int I = 0, E = VL.size(); I < E; ++I) {
6704     if (PostponedIndices.contains(I))
6705       continue;
6706     if (!isConstant(VL[I])) {
6707       NonConsts.push_back(I);
6708       continue;
6709     }
6710     Vec = CreateInsertElement(Vec, VL[I], I);
6711   }
6712   // Insert non-constant values.
6713   for (int I : NonConsts)
6714     Vec = CreateInsertElement(Vec, VL[I], I);
6715   // Append instructions, which are/may be part of the loop, in the end to make
6716   // it possible to hoist non-loop-based instructions.
6717   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6718     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6719 
6720   return Vec;
6721 }
6722 
6723 namespace {
6724 /// Merges shuffle masks and emits final shuffle instruction, if required.
6725 class ShuffleInstructionBuilder {
6726   IRBuilderBase &Builder;
6727   const unsigned VF = 0;
6728   bool IsFinalized = false;
6729   SmallVector<int, 4> Mask;
6730   /// Holds all of the instructions that we gathered.
6731   SetVector<Instruction *> &GatherShuffleSeq;
6732   /// A list of blocks that we are going to CSE.
6733   SetVector<BasicBlock *> &CSEBlocks;
6734 
6735 public:
6736   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6737                             SetVector<Instruction *> &GatherShuffleSeq,
6738                             SetVector<BasicBlock *> &CSEBlocks)
6739       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6740         CSEBlocks(CSEBlocks) {}
6741 
6742   /// Adds a mask, inverting it before applying.
6743   void addInversedMask(ArrayRef<unsigned> SubMask) {
6744     if (SubMask.empty())
6745       return;
6746     SmallVector<int, 4> NewMask;
6747     inversePermutation(SubMask, NewMask);
6748     addMask(NewMask);
6749   }
6750 
6751   /// Functions adds masks, merging them into  single one.
6752   void addMask(ArrayRef<unsigned> SubMask) {
6753     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6754     addMask(NewMask);
6755   }
6756 
6757   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6758 
6759   Value *finalize(Value *V) {
6760     IsFinalized = true;
6761     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6762     if (VF == ValueVF && Mask.empty())
6763       return V;
6764     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6765     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6766     addMask(NormalizedMask);
6767 
6768     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6769       return V;
6770     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6771     if (auto *I = dyn_cast<Instruction>(Vec)) {
6772       GatherShuffleSeq.insert(I);
6773       CSEBlocks.insert(I->getParent());
6774     }
6775     return Vec;
6776   }
6777 
6778   ~ShuffleInstructionBuilder() {
6779     assert((IsFinalized || Mask.empty()) &&
6780            "Shuffle construction must be finalized.");
6781   }
6782 };
6783 } // namespace
6784 
6785 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6786   const unsigned VF = VL.size();
6787   InstructionsState S = getSameOpcode(VL);
6788   if (S.getOpcode()) {
6789     if (TreeEntry *E = getTreeEntry(S.OpValue))
6790       if (E->isSame(VL)) {
6791         Value *V = vectorizeTree(E);
6792         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6793           if (!E->ReuseShuffleIndices.empty()) {
6794             // Reshuffle to get only unique values.
6795             // If some of the scalars are duplicated in the vectorization tree
6796             // entry, we do not vectorize them but instead generate a mask for
6797             // the reuses. But if there are several users of the same entry,
6798             // they may have different vectorization factors. This is especially
6799             // important for PHI nodes. In this case, we need to adapt the
6800             // resulting instruction for the user vectorization factor and have
6801             // to reshuffle it again to take only unique elements of the vector.
6802             // Without this code the function incorrectly returns reduced vector
6803             // instruction with the same elements, not with the unique ones.
6804 
6805             // block:
6806             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6807             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6808             // ... (use %2)
6809             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6810             // br %block
6811             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6812             SmallSet<int, 4> UsedIdxs;
6813             int Pos = 0;
6814             int Sz = VL.size();
6815             for (int Idx : E->ReuseShuffleIndices) {
6816               if (Idx != Sz && Idx != UndefMaskElem &&
6817                   UsedIdxs.insert(Idx).second)
6818                 UniqueIdxs[Idx] = Pos;
6819               ++Pos;
6820             }
6821             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6822                                             "less than original vector size.");
6823             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6824             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6825           } else {
6826             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6827                    "Expected vectorization factor less "
6828                    "than original vector size.");
6829             SmallVector<int> UniformMask(VF, 0);
6830             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6831             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6832           }
6833           if (auto *I = dyn_cast<Instruction>(V)) {
6834             GatherShuffleSeq.insert(I);
6835             CSEBlocks.insert(I->getParent());
6836           }
6837         }
6838         return V;
6839       }
6840   }
6841 
6842   // Can't vectorize this, so simply build a new vector with each lane
6843   // corresponding to the requested value.
6844   return createBuildVector(VL);
6845 }
6846 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6847   unsigned VF = VL.size();
6848   // Exploit possible reuse of values across lanes.
6849   SmallVector<int> ReuseShuffleIndicies;
6850   SmallVector<Value *> UniqueValues;
6851   if (VL.size() > 2) {
6852     DenseMap<Value *, unsigned> UniquePositions;
6853     unsigned NumValues =
6854         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6855                                     return !isa<UndefValue>(V);
6856                                   }).base());
6857     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6858     int UniqueVals = 0;
6859     for (Value *V : VL.drop_back(VL.size() - VF)) {
6860       if (isa<UndefValue>(V)) {
6861         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6862         continue;
6863       }
6864       if (isConstant(V)) {
6865         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6866         UniqueValues.emplace_back(V);
6867         continue;
6868       }
6869       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6870       ReuseShuffleIndicies.emplace_back(Res.first->second);
6871       if (Res.second) {
6872         UniqueValues.emplace_back(V);
6873         ++UniqueVals;
6874       }
6875     }
6876     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6877       // Emit pure splat vector.
6878       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6879                                   UndefMaskElem);
6880     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6881       ReuseShuffleIndicies.clear();
6882       UniqueValues.clear();
6883       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6884     }
6885     UniqueValues.append(VF - UniqueValues.size(),
6886                         PoisonValue::get(VL[0]->getType()));
6887     VL = UniqueValues;
6888   }
6889 
6890   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6891                                            CSEBlocks);
6892   Value *Vec = gather(VL);
6893   if (!ReuseShuffleIndicies.empty()) {
6894     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6895     Vec = ShuffleBuilder.finalize(Vec);
6896   }
6897   return Vec;
6898 }
6899 
6900 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6901   IRBuilder<>::InsertPointGuard Guard(Builder);
6902 
6903   if (E->VectorizedValue) {
6904     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6905     return E->VectorizedValue;
6906   }
6907 
6908   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6909   unsigned VF = E->getVectorFactor();
6910   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6911                                            CSEBlocks);
6912   if (E->State == TreeEntry::NeedToGather) {
6913     if (E->getMainOp())
6914       setInsertPointAfterBundle(E);
6915     Value *Vec;
6916     SmallVector<int> Mask;
6917     SmallVector<const TreeEntry *> Entries;
6918     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6919         isGatherShuffledEntry(E, Mask, Entries);
6920     if (Shuffle.hasValue()) {
6921       assert((Entries.size() == 1 || Entries.size() == 2) &&
6922              "Expected shuffle of 1 or 2 entries.");
6923       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6924                                         Entries.back()->VectorizedValue, Mask);
6925       if (auto *I = dyn_cast<Instruction>(Vec)) {
6926         GatherShuffleSeq.insert(I);
6927         CSEBlocks.insert(I->getParent());
6928       }
6929     } else {
6930       Vec = gather(E->Scalars);
6931     }
6932     if (NeedToShuffleReuses) {
6933       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6934       Vec = ShuffleBuilder.finalize(Vec);
6935     }
6936     E->VectorizedValue = Vec;
6937     return Vec;
6938   }
6939 
6940   assert((E->State == TreeEntry::Vectorize ||
6941           E->State == TreeEntry::ScatterVectorize) &&
6942          "Unhandled state");
6943   unsigned ShuffleOrOp =
6944       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6945   Instruction *VL0 = E->getMainOp();
6946   Type *ScalarTy = VL0->getType();
6947   if (auto *Store = dyn_cast<StoreInst>(VL0))
6948     ScalarTy = Store->getValueOperand()->getType();
6949   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6950     ScalarTy = IE->getOperand(1)->getType();
6951   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6952   switch (ShuffleOrOp) {
6953     case Instruction::PHI: {
6954       assert(
6955           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6956           "PHI reordering is free.");
6957       auto *PH = cast<PHINode>(VL0);
6958       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6959       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6960       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6961       Value *V = NewPhi;
6962 
6963       // Adjust insertion point once all PHI's have been generated.
6964       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6965       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6966 
6967       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6968       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6969       V = ShuffleBuilder.finalize(V);
6970 
6971       E->VectorizedValue = V;
6972 
6973       // PHINodes may have multiple entries from the same block. We want to
6974       // visit every block once.
6975       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6976 
6977       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6978         ValueList Operands;
6979         BasicBlock *IBB = PH->getIncomingBlock(i);
6980 
6981         if (!VisitedBBs.insert(IBB).second) {
6982           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6983           continue;
6984         }
6985 
6986         Builder.SetInsertPoint(IBB->getTerminator());
6987         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6988         Value *Vec = vectorizeTree(E->getOperand(i));
6989         NewPhi->addIncoming(Vec, IBB);
6990       }
6991 
6992       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6993              "Invalid number of incoming values");
6994       return V;
6995     }
6996 
6997     case Instruction::ExtractElement: {
6998       Value *V = E->getSingleOperand(0);
6999       Builder.SetInsertPoint(VL0);
7000       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7001       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7002       V = ShuffleBuilder.finalize(V);
7003       E->VectorizedValue = V;
7004       return V;
7005     }
7006     case Instruction::ExtractValue: {
7007       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7008       Builder.SetInsertPoint(LI);
7009       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7010       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7011       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7012       Value *NewV = propagateMetadata(V, E->Scalars);
7013       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7014       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7015       NewV = ShuffleBuilder.finalize(NewV);
7016       E->VectorizedValue = NewV;
7017       return NewV;
7018     }
7019     case Instruction::InsertElement: {
7020       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7021       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7022       Value *V = vectorizeTree(E->getOperand(1));
7023 
7024       // Create InsertVector shuffle if necessary
7025       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7026         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7027       }));
7028       const unsigned NumElts =
7029           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7030       const unsigned NumScalars = E->Scalars.size();
7031 
7032       unsigned Offset = *getInsertIndex(VL0);
7033       assert(Offset < NumElts && "Failed to find vector index offset");
7034 
7035       // Create shuffle to resize vector
7036       SmallVector<int> Mask;
7037       if (!E->ReorderIndices.empty()) {
7038         inversePermutation(E->ReorderIndices, Mask);
7039         Mask.append(NumElts - NumScalars, UndefMaskElem);
7040       } else {
7041         Mask.assign(NumElts, UndefMaskElem);
7042         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7043       }
7044       // Create InsertVector shuffle if necessary
7045       bool IsIdentity = true;
7046       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7047       Mask.swap(PrevMask);
7048       for (unsigned I = 0; I < NumScalars; ++I) {
7049         Value *Scalar = E->Scalars[PrevMask[I]];
7050         unsigned InsertIdx = *getInsertIndex(Scalar);
7051         IsIdentity &= InsertIdx - Offset == I;
7052         Mask[InsertIdx - Offset] = I;
7053       }
7054       if (!IsIdentity || NumElts != NumScalars) {
7055         V = Builder.CreateShuffleVector(V, Mask);
7056         if (auto *I = dyn_cast<Instruction>(V)) {
7057           GatherShuffleSeq.insert(I);
7058           CSEBlocks.insert(I->getParent());
7059         }
7060       }
7061 
7062       if ((!IsIdentity || Offset != 0 ||
7063            !isUndefVector(FirstInsert->getOperand(0))) &&
7064           NumElts != NumScalars) {
7065         SmallVector<int> InsertMask(NumElts);
7066         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7067         for (unsigned I = 0; I < NumElts; I++) {
7068           if (Mask[I] != UndefMaskElem)
7069             InsertMask[Offset + I] = NumElts + I;
7070         }
7071 
7072         V = Builder.CreateShuffleVector(
7073             FirstInsert->getOperand(0), V, InsertMask,
7074             cast<Instruction>(E->Scalars.back())->getName());
7075         if (auto *I = dyn_cast<Instruction>(V)) {
7076           GatherShuffleSeq.insert(I);
7077           CSEBlocks.insert(I->getParent());
7078         }
7079       }
7080 
7081       ++NumVectorInstructions;
7082       E->VectorizedValue = V;
7083       return V;
7084     }
7085     case Instruction::ZExt:
7086     case Instruction::SExt:
7087     case Instruction::FPToUI:
7088     case Instruction::FPToSI:
7089     case Instruction::FPExt:
7090     case Instruction::PtrToInt:
7091     case Instruction::IntToPtr:
7092     case Instruction::SIToFP:
7093     case Instruction::UIToFP:
7094     case Instruction::Trunc:
7095     case Instruction::FPTrunc:
7096     case Instruction::BitCast: {
7097       setInsertPointAfterBundle(E);
7098 
7099       Value *InVec = vectorizeTree(E->getOperand(0));
7100 
7101       if (E->VectorizedValue) {
7102         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7103         return E->VectorizedValue;
7104       }
7105 
7106       auto *CI = cast<CastInst>(VL0);
7107       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7108       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7109       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7110       V = ShuffleBuilder.finalize(V);
7111 
7112       E->VectorizedValue = V;
7113       ++NumVectorInstructions;
7114       return V;
7115     }
7116     case Instruction::FCmp:
7117     case Instruction::ICmp: {
7118       setInsertPointAfterBundle(E);
7119 
7120       Value *L = vectorizeTree(E->getOperand(0));
7121       Value *R = vectorizeTree(E->getOperand(1));
7122 
7123       if (E->VectorizedValue) {
7124         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7125         return E->VectorizedValue;
7126       }
7127 
7128       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7129       Value *V = Builder.CreateCmp(P0, L, R);
7130       propagateIRFlags(V, E->Scalars, VL0);
7131       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7132       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7133       V = ShuffleBuilder.finalize(V);
7134 
7135       E->VectorizedValue = V;
7136       ++NumVectorInstructions;
7137       return V;
7138     }
7139     case Instruction::Select: {
7140       setInsertPointAfterBundle(E);
7141 
7142       Value *Cond = vectorizeTree(E->getOperand(0));
7143       Value *True = vectorizeTree(E->getOperand(1));
7144       Value *False = vectorizeTree(E->getOperand(2));
7145 
7146       if (E->VectorizedValue) {
7147         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7148         return E->VectorizedValue;
7149       }
7150 
7151       Value *V = Builder.CreateSelect(Cond, True, False);
7152       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7153       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7154       V = ShuffleBuilder.finalize(V);
7155 
7156       E->VectorizedValue = V;
7157       ++NumVectorInstructions;
7158       return V;
7159     }
7160     case Instruction::FNeg: {
7161       setInsertPointAfterBundle(E);
7162 
7163       Value *Op = vectorizeTree(E->getOperand(0));
7164 
7165       if (E->VectorizedValue) {
7166         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7167         return E->VectorizedValue;
7168       }
7169 
7170       Value *V = Builder.CreateUnOp(
7171           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7172       propagateIRFlags(V, E->Scalars, VL0);
7173       if (auto *I = dyn_cast<Instruction>(V))
7174         V = propagateMetadata(I, E->Scalars);
7175 
7176       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7177       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7178       V = ShuffleBuilder.finalize(V);
7179 
7180       E->VectorizedValue = V;
7181       ++NumVectorInstructions;
7182 
7183       return V;
7184     }
7185     case Instruction::Add:
7186     case Instruction::FAdd:
7187     case Instruction::Sub:
7188     case Instruction::FSub:
7189     case Instruction::Mul:
7190     case Instruction::FMul:
7191     case Instruction::UDiv:
7192     case Instruction::SDiv:
7193     case Instruction::FDiv:
7194     case Instruction::URem:
7195     case Instruction::SRem:
7196     case Instruction::FRem:
7197     case Instruction::Shl:
7198     case Instruction::LShr:
7199     case Instruction::AShr:
7200     case Instruction::And:
7201     case Instruction::Or:
7202     case Instruction::Xor: {
7203       setInsertPointAfterBundle(E);
7204 
7205       Value *LHS = vectorizeTree(E->getOperand(0));
7206       Value *RHS = vectorizeTree(E->getOperand(1));
7207 
7208       if (E->VectorizedValue) {
7209         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7210         return E->VectorizedValue;
7211       }
7212 
7213       Value *V = Builder.CreateBinOp(
7214           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7215           RHS);
7216       propagateIRFlags(V, E->Scalars, VL0);
7217       if (auto *I = dyn_cast<Instruction>(V))
7218         V = propagateMetadata(I, E->Scalars);
7219 
7220       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7221       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7222       V = ShuffleBuilder.finalize(V);
7223 
7224       E->VectorizedValue = V;
7225       ++NumVectorInstructions;
7226 
7227       return V;
7228     }
7229     case Instruction::Load: {
7230       // Loads are inserted at the head of the tree because we don't want to
7231       // sink them all the way down past store instructions.
7232       setInsertPointAfterBundle(E);
7233 
7234       LoadInst *LI = cast<LoadInst>(VL0);
7235       Instruction *NewLI;
7236       unsigned AS = LI->getPointerAddressSpace();
7237       Value *PO = LI->getPointerOperand();
7238       if (E->State == TreeEntry::Vectorize) {
7239         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7240         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7241 
7242         // The pointer operand uses an in-tree scalar so we add the new BitCast
7243         // or LoadInst to ExternalUses list to make sure that an extract will
7244         // be generated in the future.
7245         if (TreeEntry *Entry = getTreeEntry(PO)) {
7246           // Find which lane we need to extract.
7247           unsigned FoundLane = Entry->findLaneForValue(PO);
7248           ExternalUses.emplace_back(
7249               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7250         }
7251       } else {
7252         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7253         Value *VecPtr = vectorizeTree(E->getOperand(0));
7254         // Use the minimum alignment of the gathered loads.
7255         Align CommonAlignment = LI->getAlign();
7256         for (Value *V : E->Scalars)
7257           CommonAlignment =
7258               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7259         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7260       }
7261       Value *V = propagateMetadata(NewLI, E->Scalars);
7262 
7263       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7264       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7265       V = ShuffleBuilder.finalize(V);
7266       E->VectorizedValue = V;
7267       ++NumVectorInstructions;
7268       return V;
7269     }
7270     case Instruction::Store: {
7271       auto *SI = cast<StoreInst>(VL0);
7272       unsigned AS = SI->getPointerAddressSpace();
7273 
7274       setInsertPointAfterBundle(E);
7275 
7276       Value *VecValue = vectorizeTree(E->getOperand(0));
7277       ShuffleBuilder.addMask(E->ReorderIndices);
7278       VecValue = ShuffleBuilder.finalize(VecValue);
7279 
7280       Value *ScalarPtr = SI->getPointerOperand();
7281       Value *VecPtr = Builder.CreateBitCast(
7282           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7283       StoreInst *ST =
7284           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7285 
7286       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7287       // StoreInst to ExternalUses to make sure that an extract will be
7288       // generated in the future.
7289       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7290         // Find which lane we need to extract.
7291         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7292         ExternalUses.push_back(ExternalUser(
7293             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7294             FoundLane));
7295       }
7296 
7297       Value *V = propagateMetadata(ST, E->Scalars);
7298 
7299       E->VectorizedValue = V;
7300       ++NumVectorInstructions;
7301       return V;
7302     }
7303     case Instruction::GetElementPtr: {
7304       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7305       setInsertPointAfterBundle(E);
7306 
7307       Value *Op0 = vectorizeTree(E->getOperand(0));
7308 
7309       SmallVector<Value *> OpVecs;
7310       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7311         Value *OpVec = vectorizeTree(E->getOperand(J));
7312         OpVecs.push_back(OpVec);
7313       }
7314 
7315       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7316       if (Instruction *I = dyn_cast<Instruction>(V))
7317         V = propagateMetadata(I, E->Scalars);
7318 
7319       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7320       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7321       V = ShuffleBuilder.finalize(V);
7322 
7323       E->VectorizedValue = V;
7324       ++NumVectorInstructions;
7325 
7326       return V;
7327     }
7328     case Instruction::Call: {
7329       CallInst *CI = cast<CallInst>(VL0);
7330       setInsertPointAfterBundle(E);
7331 
7332       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7333       if (Function *FI = CI->getCalledFunction())
7334         IID = FI->getIntrinsicID();
7335 
7336       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7337 
7338       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7339       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7340                           VecCallCosts.first <= VecCallCosts.second;
7341 
7342       Value *ScalarArg = nullptr;
7343       std::vector<Value *> OpVecs;
7344       SmallVector<Type *, 2> TysForDecl =
7345           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7346       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7347         ValueList OpVL;
7348         // Some intrinsics have scalar arguments. This argument should not be
7349         // vectorized.
7350         if (UseIntrinsic && hasVectorIntrinsicScalarOpd(IID, j)) {
7351           CallInst *CEI = cast<CallInst>(VL0);
7352           ScalarArg = CEI->getArgOperand(j);
7353           OpVecs.push_back(CEI->getArgOperand(j));
7354           if (hasVectorIntrinsicOverloadedScalarOpd(IID, j))
7355             TysForDecl.push_back(ScalarArg->getType());
7356           continue;
7357         }
7358 
7359         Value *OpVec = vectorizeTree(E->getOperand(j));
7360         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7361         OpVecs.push_back(OpVec);
7362       }
7363 
7364       Function *CF;
7365       if (!UseIntrinsic) {
7366         VFShape Shape =
7367             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7368                                   VecTy->getNumElements())),
7369                          false /*HasGlobalPred*/);
7370         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7371       } else {
7372         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7373       }
7374 
7375       SmallVector<OperandBundleDef, 1> OpBundles;
7376       CI->getOperandBundlesAsDefs(OpBundles);
7377       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7378 
7379       // The scalar argument uses an in-tree scalar so we add the new vectorized
7380       // call to ExternalUses list to make sure that an extract will be
7381       // generated in the future.
7382       if (ScalarArg) {
7383         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7384           // Find which lane we need to extract.
7385           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7386           ExternalUses.push_back(
7387               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7388         }
7389       }
7390 
7391       propagateIRFlags(V, E->Scalars, VL0);
7392       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7393       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7394       V = ShuffleBuilder.finalize(V);
7395 
7396       E->VectorizedValue = V;
7397       ++NumVectorInstructions;
7398       return V;
7399     }
7400     case Instruction::ShuffleVector: {
7401       assert(E->isAltShuffle() &&
7402              ((Instruction::isBinaryOp(E->getOpcode()) &&
7403                Instruction::isBinaryOp(E->getAltOpcode())) ||
7404               (Instruction::isCast(E->getOpcode()) &&
7405                Instruction::isCast(E->getAltOpcode())) ||
7406               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7407              "Invalid Shuffle Vector Operand");
7408 
7409       Value *LHS = nullptr, *RHS = nullptr;
7410       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7411         setInsertPointAfterBundle(E);
7412         LHS = vectorizeTree(E->getOperand(0));
7413         RHS = vectorizeTree(E->getOperand(1));
7414       } else {
7415         setInsertPointAfterBundle(E);
7416         LHS = vectorizeTree(E->getOperand(0));
7417       }
7418 
7419       if (E->VectorizedValue) {
7420         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7421         return E->VectorizedValue;
7422       }
7423 
7424       Value *V0, *V1;
7425       if (Instruction::isBinaryOp(E->getOpcode())) {
7426         V0 = Builder.CreateBinOp(
7427             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7428         V1 = Builder.CreateBinOp(
7429             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7430       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7431         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7432         auto *AltCI = cast<CmpInst>(E->getAltOp());
7433         CmpInst::Predicate AltPred = AltCI->getPredicate();
7434         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7435       } else {
7436         V0 = Builder.CreateCast(
7437             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7438         V1 = Builder.CreateCast(
7439             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7440       }
7441       // Add V0 and V1 to later analysis to try to find and remove matching
7442       // instruction, if any.
7443       for (Value *V : {V0, V1}) {
7444         if (auto *I = dyn_cast<Instruction>(V)) {
7445           GatherShuffleSeq.insert(I);
7446           CSEBlocks.insert(I->getParent());
7447         }
7448       }
7449 
7450       // Create shuffle to take alternate operations from the vector.
7451       // Also, gather up main and alt scalar ops to propagate IR flags to
7452       // each vector operation.
7453       ValueList OpScalars, AltScalars;
7454       SmallVector<int> Mask;
7455       buildShuffleEntryMask(
7456           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7457           [E](Instruction *I) {
7458             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7459             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7460           },
7461           Mask, &OpScalars, &AltScalars);
7462 
7463       propagateIRFlags(V0, OpScalars);
7464       propagateIRFlags(V1, AltScalars);
7465 
7466       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7467       if (auto *I = dyn_cast<Instruction>(V)) {
7468         V = propagateMetadata(I, E->Scalars);
7469         GatherShuffleSeq.insert(I);
7470         CSEBlocks.insert(I->getParent());
7471       }
7472       V = ShuffleBuilder.finalize(V);
7473 
7474       E->VectorizedValue = V;
7475       ++NumVectorInstructions;
7476 
7477       return V;
7478     }
7479     default:
7480     llvm_unreachable("unknown inst");
7481   }
7482   return nullptr;
7483 }
7484 
7485 Value *BoUpSLP::vectorizeTree() {
7486   ExtraValueToDebugLocsMap ExternallyUsedValues;
7487   return vectorizeTree(ExternallyUsedValues);
7488 }
7489 
7490 Value *
7491 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7492   // All blocks must be scheduled before any instructions are inserted.
7493   for (auto &BSIter : BlocksSchedules) {
7494     scheduleBlock(BSIter.second.get());
7495   }
7496 
7497   Builder.SetInsertPoint(&F->getEntryBlock().front());
7498   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7499 
7500   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7501   // vectorized root. InstCombine will then rewrite the entire expression. We
7502   // sign extend the extracted values below.
7503   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7504   if (MinBWs.count(ScalarRoot)) {
7505     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7506       // If current instr is a phi and not the last phi, insert it after the
7507       // last phi node.
7508       if (isa<PHINode>(I))
7509         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7510       else
7511         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7512     }
7513     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7514     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7515     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7516     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7517     VectorizableTree[0]->VectorizedValue = Trunc;
7518   }
7519 
7520   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7521                     << " values .\n");
7522 
7523   // Extract all of the elements with the external uses.
7524   for (const auto &ExternalUse : ExternalUses) {
7525     Value *Scalar = ExternalUse.Scalar;
7526     llvm::User *User = ExternalUse.User;
7527 
7528     // Skip users that we already RAUW. This happens when one instruction
7529     // has multiple uses of the same value.
7530     if (User && !is_contained(Scalar->users(), User))
7531       continue;
7532     TreeEntry *E = getTreeEntry(Scalar);
7533     assert(E && "Invalid scalar");
7534     assert(E->State != TreeEntry::NeedToGather &&
7535            "Extracting from a gather list");
7536 
7537     Value *Vec = E->VectorizedValue;
7538     assert(Vec && "Can't find vectorizable value");
7539 
7540     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7541     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7542       if (Scalar->getType() != Vec->getType()) {
7543         Value *Ex;
7544         // "Reuse" the existing extract to improve final codegen.
7545         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7546           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7547                                             ES->getOperand(1));
7548         } else {
7549           Ex = Builder.CreateExtractElement(Vec, Lane);
7550         }
7551         // If necessary, sign-extend or zero-extend ScalarRoot
7552         // to the larger type.
7553         if (!MinBWs.count(ScalarRoot))
7554           return Ex;
7555         if (MinBWs[ScalarRoot].second)
7556           return Builder.CreateSExt(Ex, Scalar->getType());
7557         return Builder.CreateZExt(Ex, Scalar->getType());
7558       }
7559       assert(isa<FixedVectorType>(Scalar->getType()) &&
7560              isa<InsertElementInst>(Scalar) &&
7561              "In-tree scalar of vector type is not insertelement?");
7562       return Vec;
7563     };
7564     // If User == nullptr, the Scalar is used as extra arg. Generate
7565     // ExtractElement instruction and update the record for this scalar in
7566     // ExternallyUsedValues.
7567     if (!User) {
7568       assert(ExternallyUsedValues.count(Scalar) &&
7569              "Scalar with nullptr as an external user must be registered in "
7570              "ExternallyUsedValues map");
7571       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7572         Builder.SetInsertPoint(VecI->getParent(),
7573                                std::next(VecI->getIterator()));
7574       } else {
7575         Builder.SetInsertPoint(&F->getEntryBlock().front());
7576       }
7577       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7578       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7579       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7580       auto It = ExternallyUsedValues.find(Scalar);
7581       assert(It != ExternallyUsedValues.end() &&
7582              "Externally used scalar is not found in ExternallyUsedValues");
7583       NewInstLocs.append(It->second);
7584       ExternallyUsedValues.erase(Scalar);
7585       // Required to update internally referenced instructions.
7586       Scalar->replaceAllUsesWith(NewInst);
7587       continue;
7588     }
7589 
7590     // Generate extracts for out-of-tree users.
7591     // Find the insertion point for the extractelement lane.
7592     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7593       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7594         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7595           if (PH->getIncomingValue(i) == Scalar) {
7596             Instruction *IncomingTerminator =
7597                 PH->getIncomingBlock(i)->getTerminator();
7598             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7599               Builder.SetInsertPoint(VecI->getParent(),
7600                                      std::next(VecI->getIterator()));
7601             } else {
7602               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7603             }
7604             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7605             CSEBlocks.insert(PH->getIncomingBlock(i));
7606             PH->setOperand(i, NewInst);
7607           }
7608         }
7609       } else {
7610         Builder.SetInsertPoint(cast<Instruction>(User));
7611         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7612         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7613         User->replaceUsesOfWith(Scalar, NewInst);
7614       }
7615     } else {
7616       Builder.SetInsertPoint(&F->getEntryBlock().front());
7617       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7618       CSEBlocks.insert(&F->getEntryBlock());
7619       User->replaceUsesOfWith(Scalar, NewInst);
7620     }
7621 
7622     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7623   }
7624 
7625   // For each vectorized value:
7626   for (auto &TEPtr : VectorizableTree) {
7627     TreeEntry *Entry = TEPtr.get();
7628 
7629     // No need to handle users of gathered values.
7630     if (Entry->State == TreeEntry::NeedToGather)
7631       continue;
7632 
7633     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7634 
7635     // For each lane:
7636     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7637       Value *Scalar = Entry->Scalars[Lane];
7638 
7639 #ifndef NDEBUG
7640       Type *Ty = Scalar->getType();
7641       if (!Ty->isVoidTy()) {
7642         for (User *U : Scalar->users()) {
7643           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7644 
7645           // It is legal to delete users in the ignorelist.
7646           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7647                   (isa_and_nonnull<Instruction>(U) &&
7648                    isDeleted(cast<Instruction>(U)))) &&
7649                  "Deleting out-of-tree value");
7650         }
7651       }
7652 #endif
7653       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7654       eraseInstruction(cast<Instruction>(Scalar));
7655     }
7656   }
7657 
7658   Builder.ClearInsertionPoint();
7659   InstrElementSize.clear();
7660 
7661   return VectorizableTree[0]->VectorizedValue;
7662 }
7663 
7664 void BoUpSLP::optimizeGatherSequence() {
7665   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7666                     << " gather sequences instructions.\n");
7667   // LICM InsertElementInst sequences.
7668   for (Instruction *I : GatherShuffleSeq) {
7669     if (isDeleted(I))
7670       continue;
7671 
7672     // Check if this block is inside a loop.
7673     Loop *L = LI->getLoopFor(I->getParent());
7674     if (!L)
7675       continue;
7676 
7677     // Check if it has a preheader.
7678     BasicBlock *PreHeader = L->getLoopPreheader();
7679     if (!PreHeader)
7680       continue;
7681 
7682     // If the vector or the element that we insert into it are
7683     // instructions that are defined in this basic block then we can't
7684     // hoist this instruction.
7685     if (any_of(I->operands(), [L](Value *V) {
7686           auto *OpI = dyn_cast<Instruction>(V);
7687           return OpI && L->contains(OpI);
7688         }))
7689       continue;
7690 
7691     // We can hoist this instruction. Move it to the pre-header.
7692     I->moveBefore(PreHeader->getTerminator());
7693   }
7694 
7695   // Make a list of all reachable blocks in our CSE queue.
7696   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7697   CSEWorkList.reserve(CSEBlocks.size());
7698   for (BasicBlock *BB : CSEBlocks)
7699     if (DomTreeNode *N = DT->getNode(BB)) {
7700       assert(DT->isReachableFromEntry(N));
7701       CSEWorkList.push_back(N);
7702     }
7703 
7704   // Sort blocks by domination. This ensures we visit a block after all blocks
7705   // dominating it are visited.
7706   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7707     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7708            "Different nodes should have different DFS numbers");
7709     return A->getDFSNumIn() < B->getDFSNumIn();
7710   });
7711 
7712   // Less defined shuffles can be replaced by the more defined copies.
7713   // Between two shuffles one is less defined if it has the same vector operands
7714   // and its mask indeces are the same as in the first one or undefs. E.g.
7715   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7716   // poison, <0, 0, 0, 0>.
7717   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7718                                            SmallVectorImpl<int> &NewMask) {
7719     if (I1->getType() != I2->getType())
7720       return false;
7721     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7722     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7723     if (!SI1 || !SI2)
7724       return I1->isIdenticalTo(I2);
7725     if (SI1->isIdenticalTo(SI2))
7726       return true;
7727     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7728       if (SI1->getOperand(I) != SI2->getOperand(I))
7729         return false;
7730     // Check if the second instruction is more defined than the first one.
7731     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7732     ArrayRef<int> SM1 = SI1->getShuffleMask();
7733     // Count trailing undefs in the mask to check the final number of used
7734     // registers.
7735     unsigned LastUndefsCnt = 0;
7736     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7737       if (SM1[I] == UndefMaskElem)
7738         ++LastUndefsCnt;
7739       else
7740         LastUndefsCnt = 0;
7741       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7742           NewMask[I] != SM1[I])
7743         return false;
7744       if (NewMask[I] == UndefMaskElem)
7745         NewMask[I] = SM1[I];
7746     }
7747     // Check if the last undefs actually change the final number of used vector
7748     // registers.
7749     return SM1.size() - LastUndefsCnt > 1 &&
7750            TTI->getNumberOfParts(SI1->getType()) ==
7751                TTI->getNumberOfParts(
7752                    FixedVectorType::get(SI1->getType()->getElementType(),
7753                                         SM1.size() - LastUndefsCnt));
7754   };
7755   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7756   // instructions. TODO: We can further optimize this scan if we split the
7757   // instructions into different buckets based on the insert lane.
7758   SmallVector<Instruction *, 16> Visited;
7759   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7760     assert(*I &&
7761            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7762            "Worklist not sorted properly!");
7763     BasicBlock *BB = (*I)->getBlock();
7764     // For all instructions in blocks containing gather sequences:
7765     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7766       if (isDeleted(&In))
7767         continue;
7768       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7769           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7770         continue;
7771 
7772       // Check if we can replace this instruction with any of the
7773       // visited instructions.
7774       bool Replaced = false;
7775       for (Instruction *&V : Visited) {
7776         SmallVector<int> NewMask;
7777         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7778             DT->dominates(V->getParent(), In.getParent())) {
7779           In.replaceAllUsesWith(V);
7780           eraseInstruction(&In);
7781           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7782             if (!NewMask.empty())
7783               SI->setShuffleMask(NewMask);
7784           Replaced = true;
7785           break;
7786         }
7787         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7788             GatherShuffleSeq.contains(V) &&
7789             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7790             DT->dominates(In.getParent(), V->getParent())) {
7791           In.moveAfter(V);
7792           V->replaceAllUsesWith(&In);
7793           eraseInstruction(V);
7794           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7795             if (!NewMask.empty())
7796               SI->setShuffleMask(NewMask);
7797           V = &In;
7798           Replaced = true;
7799           break;
7800         }
7801       }
7802       if (!Replaced) {
7803         assert(!is_contained(Visited, &In));
7804         Visited.push_back(&In);
7805       }
7806     }
7807   }
7808   CSEBlocks.clear();
7809   GatherShuffleSeq.clear();
7810 }
7811 
7812 BoUpSLP::ScheduleData *
7813 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7814   ScheduleData *Bundle = nullptr;
7815   ScheduleData *PrevInBundle = nullptr;
7816   for (Value *V : VL) {
7817     if (doesNotNeedToBeScheduled(V))
7818       continue;
7819     ScheduleData *BundleMember = getScheduleData(V);
7820     assert(BundleMember &&
7821            "no ScheduleData for bundle member "
7822            "(maybe not in same basic block)");
7823     assert(BundleMember->isSchedulingEntity() &&
7824            "bundle member already part of other bundle");
7825     if (PrevInBundle) {
7826       PrevInBundle->NextInBundle = BundleMember;
7827     } else {
7828       Bundle = BundleMember;
7829     }
7830 
7831     // Group the instructions to a bundle.
7832     BundleMember->FirstInBundle = Bundle;
7833     PrevInBundle = BundleMember;
7834   }
7835   assert(Bundle && "Failed to find schedule bundle");
7836   return Bundle;
7837 }
7838 
7839 // Groups the instructions to a bundle (which is then a single scheduling entity)
7840 // and schedules instructions until the bundle gets ready.
7841 Optional<BoUpSLP::ScheduleData *>
7842 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7843                                             const InstructionsState &S) {
7844   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7845   // instructions.
7846   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7847       doesNotNeedToSchedule(VL))
7848     return nullptr;
7849 
7850   // Initialize the instruction bundle.
7851   Instruction *OldScheduleEnd = ScheduleEnd;
7852   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7853 
7854   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7855                                                          ScheduleData *Bundle) {
7856     // The scheduling region got new instructions at the lower end (or it is a
7857     // new region for the first bundle). This makes it necessary to
7858     // recalculate all dependencies.
7859     // It is seldom that this needs to be done a second time after adding the
7860     // initial bundle to the region.
7861     if (ScheduleEnd != OldScheduleEnd) {
7862       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7863         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7864       ReSchedule = true;
7865     }
7866     if (Bundle) {
7867       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7868                         << " in block " << BB->getName() << "\n");
7869       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7870     }
7871 
7872     if (ReSchedule) {
7873       resetSchedule();
7874       initialFillReadyList(ReadyInsts);
7875     }
7876 
7877     // Now try to schedule the new bundle or (if no bundle) just calculate
7878     // dependencies. As soon as the bundle is "ready" it means that there are no
7879     // cyclic dependencies and we can schedule it. Note that's important that we
7880     // don't "schedule" the bundle yet (see cancelScheduling).
7881     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7882            !ReadyInsts.empty()) {
7883       ScheduleData *Picked = ReadyInsts.pop_back_val();
7884       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7885              "must be ready to schedule");
7886       schedule(Picked, ReadyInsts);
7887     }
7888   };
7889 
7890   // Make sure that the scheduling region contains all
7891   // instructions of the bundle.
7892   for (Value *V : VL) {
7893     if (doesNotNeedToBeScheduled(V))
7894       continue;
7895     if (!extendSchedulingRegion(V, S)) {
7896       // If the scheduling region got new instructions at the lower end (or it
7897       // is a new region for the first bundle). This makes it necessary to
7898       // recalculate all dependencies.
7899       // Otherwise the compiler may crash trying to incorrectly calculate
7900       // dependencies and emit instruction in the wrong order at the actual
7901       // scheduling.
7902       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7903       return None;
7904     }
7905   }
7906 
7907   bool ReSchedule = false;
7908   for (Value *V : VL) {
7909     if (doesNotNeedToBeScheduled(V))
7910       continue;
7911     ScheduleData *BundleMember = getScheduleData(V);
7912     assert(BundleMember &&
7913            "no ScheduleData for bundle member (maybe not in same basic block)");
7914 
7915     // Make sure we don't leave the pieces of the bundle in the ready list when
7916     // whole bundle might not be ready.
7917     ReadyInsts.remove(BundleMember);
7918 
7919     if (!BundleMember->IsScheduled)
7920       continue;
7921     // A bundle member was scheduled as single instruction before and now
7922     // needs to be scheduled as part of the bundle. We just get rid of the
7923     // existing schedule.
7924     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7925                       << " was already scheduled\n");
7926     ReSchedule = true;
7927   }
7928 
7929   auto *Bundle = buildBundle(VL);
7930   TryScheduleBundleImpl(ReSchedule, Bundle);
7931   if (!Bundle->isReady()) {
7932     cancelScheduling(VL, S.OpValue);
7933     return None;
7934   }
7935   return Bundle;
7936 }
7937 
7938 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7939                                                 Value *OpValue) {
7940   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7941       doesNotNeedToSchedule(VL))
7942     return;
7943 
7944   if (doesNotNeedToBeScheduled(OpValue))
7945     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7946   ScheduleData *Bundle = getScheduleData(OpValue);
7947   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7948   assert(!Bundle->IsScheduled &&
7949          "Can't cancel bundle which is already scheduled");
7950   assert(Bundle->isSchedulingEntity() &&
7951          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7952          "tried to unbundle something which is not a bundle");
7953 
7954   // Remove the bundle from the ready list.
7955   if (Bundle->isReady())
7956     ReadyInsts.remove(Bundle);
7957 
7958   // Un-bundle: make single instructions out of the bundle.
7959   ScheduleData *BundleMember = Bundle;
7960   while (BundleMember) {
7961     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7962     BundleMember->FirstInBundle = BundleMember;
7963     ScheduleData *Next = BundleMember->NextInBundle;
7964     BundleMember->NextInBundle = nullptr;
7965     BundleMember->TE = nullptr;
7966     if (BundleMember->unscheduledDepsInBundle() == 0) {
7967       ReadyInsts.insert(BundleMember);
7968     }
7969     BundleMember = Next;
7970   }
7971 }
7972 
7973 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7974   // Allocate a new ScheduleData for the instruction.
7975   if (ChunkPos >= ChunkSize) {
7976     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7977     ChunkPos = 0;
7978   }
7979   return &(ScheduleDataChunks.back()[ChunkPos++]);
7980 }
7981 
7982 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7983                                                       const InstructionsState &S) {
7984   if (getScheduleData(V, isOneOf(S, V)))
7985     return true;
7986   Instruction *I = dyn_cast<Instruction>(V);
7987   assert(I && "bundle member must be an instruction");
7988   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7989          !doesNotNeedToBeScheduled(I) &&
7990          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7991          "be scheduled");
7992   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7993     ScheduleData *ISD = getScheduleData(I);
7994     if (!ISD)
7995       return false;
7996     assert(isInSchedulingRegion(ISD) &&
7997            "ScheduleData not in scheduling region");
7998     ScheduleData *SD = allocateScheduleDataChunks();
7999     SD->Inst = I;
8000     SD->init(SchedulingRegionID, S.OpValue);
8001     ExtraScheduleDataMap[I][S.OpValue] = SD;
8002     return true;
8003   };
8004   if (CheckScheduleForI(I))
8005     return true;
8006   if (!ScheduleStart) {
8007     // It's the first instruction in the new region.
8008     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8009     ScheduleStart = I;
8010     ScheduleEnd = I->getNextNode();
8011     if (isOneOf(S, I) != I)
8012       CheckScheduleForI(I);
8013     assert(ScheduleEnd && "tried to vectorize a terminator?");
8014     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8015     return true;
8016   }
8017   // Search up and down at the same time, because we don't know if the new
8018   // instruction is above or below the existing scheduling region.
8019   BasicBlock::reverse_iterator UpIter =
8020       ++ScheduleStart->getIterator().getReverse();
8021   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8022   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8023   BasicBlock::iterator LowerEnd = BB->end();
8024   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8025          &*DownIter != I) {
8026     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8027       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8028       return false;
8029     }
8030 
8031     ++UpIter;
8032     ++DownIter;
8033   }
8034   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8035     assert(I->getParent() == ScheduleStart->getParent() &&
8036            "Instruction is in wrong basic block.");
8037     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8038     ScheduleStart = I;
8039     if (isOneOf(S, I) != I)
8040       CheckScheduleForI(I);
8041     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8042                       << "\n");
8043     return true;
8044   }
8045   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8046          "Expected to reach top of the basic block or instruction down the "
8047          "lower end.");
8048   assert(I->getParent() == ScheduleEnd->getParent() &&
8049          "Instruction is in wrong basic block.");
8050   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8051                    nullptr);
8052   ScheduleEnd = I->getNextNode();
8053   if (isOneOf(S, I) != I)
8054     CheckScheduleForI(I);
8055   assert(ScheduleEnd && "tried to vectorize a terminator?");
8056   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8057   return true;
8058 }
8059 
8060 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8061                                                 Instruction *ToI,
8062                                                 ScheduleData *PrevLoadStore,
8063                                                 ScheduleData *NextLoadStore) {
8064   ScheduleData *CurrentLoadStore = PrevLoadStore;
8065   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8066     // No need to allocate data for non-schedulable instructions.
8067     if (doesNotNeedToBeScheduled(I))
8068       continue;
8069     ScheduleData *SD = ScheduleDataMap.lookup(I);
8070     if (!SD) {
8071       SD = allocateScheduleDataChunks();
8072       ScheduleDataMap[I] = SD;
8073       SD->Inst = I;
8074     }
8075     assert(!isInSchedulingRegion(SD) &&
8076            "new ScheduleData already in scheduling region");
8077     SD->init(SchedulingRegionID, I);
8078 
8079     if (I->mayReadOrWriteMemory() &&
8080         (!isa<IntrinsicInst>(I) ||
8081          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8082           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8083               Intrinsic::pseudoprobe))) {
8084       // Update the linked list of memory accessing instructions.
8085       if (CurrentLoadStore) {
8086         CurrentLoadStore->NextLoadStore = SD;
8087       } else {
8088         FirstLoadStoreInRegion = SD;
8089       }
8090       CurrentLoadStore = SD;
8091     }
8092 
8093     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8094         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8095       RegionHasStackSave = true;
8096   }
8097   if (NextLoadStore) {
8098     if (CurrentLoadStore)
8099       CurrentLoadStore->NextLoadStore = NextLoadStore;
8100   } else {
8101     LastLoadStoreInRegion = CurrentLoadStore;
8102   }
8103 }
8104 
8105 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8106                                                      bool InsertInReadyList,
8107                                                      BoUpSLP *SLP) {
8108   assert(SD->isSchedulingEntity());
8109 
8110   SmallVector<ScheduleData *, 10> WorkList;
8111   WorkList.push_back(SD);
8112 
8113   while (!WorkList.empty()) {
8114     ScheduleData *SD = WorkList.pop_back_val();
8115     for (ScheduleData *BundleMember = SD; BundleMember;
8116          BundleMember = BundleMember->NextInBundle) {
8117       assert(isInSchedulingRegion(BundleMember));
8118       if (BundleMember->hasValidDependencies())
8119         continue;
8120 
8121       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8122                  << "\n");
8123       BundleMember->Dependencies = 0;
8124       BundleMember->resetUnscheduledDeps();
8125 
8126       // Handle def-use chain dependencies.
8127       if (BundleMember->OpValue != BundleMember->Inst) {
8128         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8129           BundleMember->Dependencies++;
8130           ScheduleData *DestBundle = UseSD->FirstInBundle;
8131           if (!DestBundle->IsScheduled)
8132             BundleMember->incrementUnscheduledDeps(1);
8133           if (!DestBundle->hasValidDependencies())
8134             WorkList.push_back(DestBundle);
8135         }
8136       } else {
8137         for (User *U : BundleMember->Inst->users()) {
8138           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8139             BundleMember->Dependencies++;
8140             ScheduleData *DestBundle = UseSD->FirstInBundle;
8141             if (!DestBundle->IsScheduled)
8142               BundleMember->incrementUnscheduledDeps(1);
8143             if (!DestBundle->hasValidDependencies())
8144               WorkList.push_back(DestBundle);
8145           }
8146         }
8147       }
8148 
8149       auto makeControlDependent = [&](Instruction *I) {
8150         auto *DepDest = getScheduleData(I);
8151         assert(DepDest && "must be in schedule window");
8152         DepDest->ControlDependencies.push_back(BundleMember);
8153         BundleMember->Dependencies++;
8154         ScheduleData *DestBundle = DepDest->FirstInBundle;
8155         if (!DestBundle->IsScheduled)
8156           BundleMember->incrementUnscheduledDeps(1);
8157         if (!DestBundle->hasValidDependencies())
8158           WorkList.push_back(DestBundle);
8159       };
8160 
8161       // Any instruction which isn't safe to speculate at the begining of the
8162       // block is control dependend on any early exit or non-willreturn call
8163       // which proceeds it.
8164       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8165         for (Instruction *I = BundleMember->Inst->getNextNode();
8166              I != ScheduleEnd; I = I->getNextNode()) {
8167           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8168             continue;
8169 
8170           // Add the dependency
8171           makeControlDependent(I);
8172 
8173           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8174             // Everything past here must be control dependent on I.
8175             break;
8176         }
8177       }
8178 
8179       if (RegionHasStackSave) {
8180         // If we have an inalloc alloca instruction, it needs to be scheduled
8181         // after any preceeding stacksave.  We also need to prevent any alloca
8182         // from reordering above a preceeding stackrestore.
8183         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8184             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8185           for (Instruction *I = BundleMember->Inst->getNextNode();
8186                I != ScheduleEnd; I = I->getNextNode()) {
8187             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8188                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8189               // Any allocas past here must be control dependent on I, and I
8190               // must be memory dependend on BundleMember->Inst.
8191               break;
8192 
8193             if (!isa<AllocaInst>(I))
8194               continue;
8195 
8196             // Add the dependency
8197             makeControlDependent(I);
8198           }
8199         }
8200 
8201         // In addition to the cases handle just above, we need to prevent
8202         // allocas from moving below a stacksave.  The stackrestore case
8203         // is currently thought to be conservatism.
8204         if (isa<AllocaInst>(BundleMember->Inst)) {
8205           for (Instruction *I = BundleMember->Inst->getNextNode();
8206                I != ScheduleEnd; I = I->getNextNode()) {
8207             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8208                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8209               continue;
8210 
8211             // Add the dependency
8212             makeControlDependent(I);
8213             break;
8214           }
8215         }
8216       }
8217 
8218       // Handle the memory dependencies (if any).
8219       ScheduleData *DepDest = BundleMember->NextLoadStore;
8220       if (!DepDest)
8221         continue;
8222       Instruction *SrcInst = BundleMember->Inst;
8223       assert(SrcInst->mayReadOrWriteMemory() &&
8224              "NextLoadStore list for non memory effecting bundle?");
8225       MemoryLocation SrcLoc = getLocation(SrcInst);
8226       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8227       unsigned numAliased = 0;
8228       unsigned DistToSrc = 1;
8229 
8230       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8231         assert(isInSchedulingRegion(DepDest));
8232 
8233         // We have two limits to reduce the complexity:
8234         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8235         //    SLP->isAliased (which is the expensive part in this loop).
8236         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8237         //    the whole loop (even if the loop is fast, it's quadratic).
8238         //    It's important for the loop break condition (see below) to
8239         //    check this limit even between two read-only instructions.
8240         if (DistToSrc >= MaxMemDepDistance ||
8241             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8242              (numAliased >= AliasedCheckLimit ||
8243               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8244 
8245           // We increment the counter only if the locations are aliased
8246           // (instead of counting all alias checks). This gives a better
8247           // balance between reduced runtime and accurate dependencies.
8248           numAliased++;
8249 
8250           DepDest->MemoryDependencies.push_back(BundleMember);
8251           BundleMember->Dependencies++;
8252           ScheduleData *DestBundle = DepDest->FirstInBundle;
8253           if (!DestBundle->IsScheduled) {
8254             BundleMember->incrementUnscheduledDeps(1);
8255           }
8256           if (!DestBundle->hasValidDependencies()) {
8257             WorkList.push_back(DestBundle);
8258           }
8259         }
8260 
8261         // Example, explaining the loop break condition: Let's assume our
8262         // starting instruction is i0 and MaxMemDepDistance = 3.
8263         //
8264         //                      +--------v--v--v
8265         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8266         //             +--------^--^--^
8267         //
8268         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8269         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8270         // Previously we already added dependencies from i3 to i6,i7,i8
8271         // (because of MaxMemDepDistance). As we added a dependency from
8272         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8273         // and we can abort this loop at i6.
8274         if (DistToSrc >= 2 * MaxMemDepDistance)
8275           break;
8276         DistToSrc++;
8277       }
8278     }
8279     if (InsertInReadyList && SD->isReady()) {
8280       ReadyInsts.insert(SD);
8281       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8282                         << "\n");
8283     }
8284   }
8285 }
8286 
8287 void BoUpSLP::BlockScheduling::resetSchedule() {
8288   assert(ScheduleStart &&
8289          "tried to reset schedule on block which has not been scheduled");
8290   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8291     doForAllOpcodes(I, [&](ScheduleData *SD) {
8292       assert(isInSchedulingRegion(SD) &&
8293              "ScheduleData not in scheduling region");
8294       SD->IsScheduled = false;
8295       SD->resetUnscheduledDeps();
8296     });
8297   }
8298   ReadyInsts.clear();
8299 }
8300 
8301 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8302   if (!BS->ScheduleStart)
8303     return;
8304 
8305   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8306 
8307   // A key point - if we got here, pre-scheduling was able to find a valid
8308   // scheduling of the sub-graph of the scheduling window which consists
8309   // of all vector bundles and their transitive users.  As such, we do not
8310   // need to reschedule anything *outside of* that subgraph.
8311 
8312   BS->resetSchedule();
8313 
8314   // For the real scheduling we use a more sophisticated ready-list: it is
8315   // sorted by the original instruction location. This lets the final schedule
8316   // be as  close as possible to the original instruction order.
8317   // WARNING: If changing this order causes a correctness issue, that means
8318   // there is some missing dependence edge in the schedule data graph.
8319   struct ScheduleDataCompare {
8320     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8321       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8322     }
8323   };
8324   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8325 
8326   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8327   // and fill the ready-list with initial instructions.
8328   int Idx = 0;
8329   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8330        I = I->getNextNode()) {
8331     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8332       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8333       (void)SDTE;
8334       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8335               SD->isPartOfBundle() ==
8336                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8337              "scheduler and vectorizer bundle mismatch");
8338       SD->FirstInBundle->SchedulingPriority = Idx++;
8339 
8340       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8341         BS->calculateDependencies(SD, false, this);
8342     });
8343   }
8344   BS->initialFillReadyList(ReadyInsts);
8345 
8346   Instruction *LastScheduledInst = BS->ScheduleEnd;
8347 
8348   // Do the "real" scheduling.
8349   while (!ReadyInsts.empty()) {
8350     ScheduleData *picked = *ReadyInsts.begin();
8351     ReadyInsts.erase(ReadyInsts.begin());
8352 
8353     // Move the scheduled instruction(s) to their dedicated places, if not
8354     // there yet.
8355     for (ScheduleData *BundleMember = picked; BundleMember;
8356          BundleMember = BundleMember->NextInBundle) {
8357       Instruction *pickedInst = BundleMember->Inst;
8358       if (pickedInst->getNextNode() != LastScheduledInst)
8359         pickedInst->moveBefore(LastScheduledInst);
8360       LastScheduledInst = pickedInst;
8361     }
8362 
8363     BS->schedule(picked, ReadyInsts);
8364   }
8365 
8366   // Check that we didn't break any of our invariants.
8367 #ifdef EXPENSIVE_CHECKS
8368   BS->verify();
8369 #endif
8370 
8371 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8372   // Check that all schedulable entities got scheduled
8373   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8374     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8375       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8376         assert(SD->IsScheduled && "must be scheduled at this point");
8377       }
8378     });
8379   }
8380 #endif
8381 
8382   // Avoid duplicate scheduling of the block.
8383   BS->ScheduleStart = nullptr;
8384 }
8385 
8386 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8387   // If V is a store, just return the width of the stored value (or value
8388   // truncated just before storing) without traversing the expression tree.
8389   // This is the common case.
8390   if (auto *Store = dyn_cast<StoreInst>(V)) {
8391     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8392       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8393     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8394   }
8395 
8396   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8397     return getVectorElementSize(IEI->getOperand(1));
8398 
8399   auto E = InstrElementSize.find(V);
8400   if (E != InstrElementSize.end())
8401     return E->second;
8402 
8403   // If V is not a store, we can traverse the expression tree to find loads
8404   // that feed it. The type of the loaded value may indicate a more suitable
8405   // width than V's type. We want to base the vector element size on the width
8406   // of memory operations where possible.
8407   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8408   SmallPtrSet<Instruction *, 16> Visited;
8409   if (auto *I = dyn_cast<Instruction>(V)) {
8410     Worklist.emplace_back(I, I->getParent());
8411     Visited.insert(I);
8412   }
8413 
8414   // Traverse the expression tree in bottom-up order looking for loads. If we
8415   // encounter an instruction we don't yet handle, we give up.
8416   auto Width = 0u;
8417   while (!Worklist.empty()) {
8418     Instruction *I;
8419     BasicBlock *Parent;
8420     std::tie(I, Parent) = Worklist.pop_back_val();
8421 
8422     // We should only be looking at scalar instructions here. If the current
8423     // instruction has a vector type, skip.
8424     auto *Ty = I->getType();
8425     if (isa<VectorType>(Ty))
8426       continue;
8427 
8428     // If the current instruction is a load, update MaxWidth to reflect the
8429     // width of the loaded value.
8430     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8431         isa<ExtractValueInst>(I))
8432       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8433 
8434     // Otherwise, we need to visit the operands of the instruction. We only
8435     // handle the interesting cases from buildTree here. If an operand is an
8436     // instruction we haven't yet visited and from the same basic block as the
8437     // user or the use is a PHI node, we add it to the worklist.
8438     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8439              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8440              isa<UnaryOperator>(I)) {
8441       for (Use &U : I->operands())
8442         if (auto *J = dyn_cast<Instruction>(U.get()))
8443           if (Visited.insert(J).second &&
8444               (isa<PHINode>(I) || J->getParent() == Parent))
8445             Worklist.emplace_back(J, J->getParent());
8446     } else {
8447       break;
8448     }
8449   }
8450 
8451   // If we didn't encounter a memory access in the expression tree, or if we
8452   // gave up for some reason, just return the width of V. Otherwise, return the
8453   // maximum width we found.
8454   if (!Width) {
8455     if (auto *CI = dyn_cast<CmpInst>(V))
8456       V = CI->getOperand(0);
8457     Width = DL->getTypeSizeInBits(V->getType());
8458   }
8459 
8460   for (Instruction *I : Visited)
8461     InstrElementSize[I] = Width;
8462 
8463   return Width;
8464 }
8465 
8466 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8467 // smaller type with a truncation. We collect the values that will be demoted
8468 // in ToDemote and additional roots that require investigating in Roots.
8469 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8470                                   SmallVectorImpl<Value *> &ToDemote,
8471                                   SmallVectorImpl<Value *> &Roots) {
8472   // We can always demote constants.
8473   if (isa<Constant>(V)) {
8474     ToDemote.push_back(V);
8475     return true;
8476   }
8477 
8478   // If the value is not an instruction in the expression with only one use, it
8479   // cannot be demoted.
8480   auto *I = dyn_cast<Instruction>(V);
8481   if (!I || !I->hasOneUse() || !Expr.count(I))
8482     return false;
8483 
8484   switch (I->getOpcode()) {
8485 
8486   // We can always demote truncations and extensions. Since truncations can
8487   // seed additional demotion, we save the truncated value.
8488   case Instruction::Trunc:
8489     Roots.push_back(I->getOperand(0));
8490     break;
8491   case Instruction::ZExt:
8492   case Instruction::SExt:
8493     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8494         isa<InsertElementInst>(I->getOperand(0)))
8495       return false;
8496     break;
8497 
8498   // We can demote certain binary operations if we can demote both of their
8499   // operands.
8500   case Instruction::Add:
8501   case Instruction::Sub:
8502   case Instruction::Mul:
8503   case Instruction::And:
8504   case Instruction::Or:
8505   case Instruction::Xor:
8506     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8507         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8508       return false;
8509     break;
8510 
8511   // We can demote selects if we can demote their true and false values.
8512   case Instruction::Select: {
8513     SelectInst *SI = cast<SelectInst>(I);
8514     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8515         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8516       return false;
8517     break;
8518   }
8519 
8520   // We can demote phis if we can demote all their incoming operands. Note that
8521   // we don't need to worry about cycles since we ensure single use above.
8522   case Instruction::PHI: {
8523     PHINode *PN = cast<PHINode>(I);
8524     for (Value *IncValue : PN->incoming_values())
8525       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8526         return false;
8527     break;
8528   }
8529 
8530   // Otherwise, conservatively give up.
8531   default:
8532     return false;
8533   }
8534 
8535   // Record the value that we can demote.
8536   ToDemote.push_back(V);
8537   return true;
8538 }
8539 
8540 void BoUpSLP::computeMinimumValueSizes() {
8541   // If there are no external uses, the expression tree must be rooted by a
8542   // store. We can't demote in-memory values, so there is nothing to do here.
8543   if (ExternalUses.empty())
8544     return;
8545 
8546   // We only attempt to truncate integer expressions.
8547   auto &TreeRoot = VectorizableTree[0]->Scalars;
8548   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8549   if (!TreeRootIT)
8550     return;
8551 
8552   // If the expression is not rooted by a store, these roots should have
8553   // external uses. We will rely on InstCombine to rewrite the expression in
8554   // the narrower type. However, InstCombine only rewrites single-use values.
8555   // This means that if a tree entry other than a root is used externally, it
8556   // must have multiple uses and InstCombine will not rewrite it. The code
8557   // below ensures that only the roots are used externally.
8558   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8559   for (auto &EU : ExternalUses)
8560     if (!Expr.erase(EU.Scalar))
8561       return;
8562   if (!Expr.empty())
8563     return;
8564 
8565   // Collect the scalar values of the vectorizable expression. We will use this
8566   // context to determine which values can be demoted. If we see a truncation,
8567   // we mark it as seeding another demotion.
8568   for (auto &EntryPtr : VectorizableTree)
8569     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8570 
8571   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8572   // have a single external user that is not in the vectorizable tree.
8573   for (auto *Root : TreeRoot)
8574     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8575       return;
8576 
8577   // Conservatively determine if we can actually truncate the roots of the
8578   // expression. Collect the values that can be demoted in ToDemote and
8579   // additional roots that require investigating in Roots.
8580   SmallVector<Value *, 32> ToDemote;
8581   SmallVector<Value *, 4> Roots;
8582   for (auto *Root : TreeRoot)
8583     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8584       return;
8585 
8586   // The maximum bit width required to represent all the values that can be
8587   // demoted without loss of precision. It would be safe to truncate the roots
8588   // of the expression to this width.
8589   auto MaxBitWidth = 8u;
8590 
8591   // We first check if all the bits of the roots are demanded. If they're not,
8592   // we can truncate the roots to this narrower type.
8593   for (auto *Root : TreeRoot) {
8594     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8595     MaxBitWidth = std::max<unsigned>(
8596         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8597   }
8598 
8599   // True if the roots can be zero-extended back to their original type, rather
8600   // than sign-extended. We know that if the leading bits are not demanded, we
8601   // can safely zero-extend. So we initialize IsKnownPositive to True.
8602   bool IsKnownPositive = true;
8603 
8604   // If all the bits of the roots are demanded, we can try a little harder to
8605   // compute a narrower type. This can happen, for example, if the roots are
8606   // getelementptr indices. InstCombine promotes these indices to the pointer
8607   // width. Thus, all their bits are technically demanded even though the
8608   // address computation might be vectorized in a smaller type.
8609   //
8610   // We start by looking at each entry that can be demoted. We compute the
8611   // maximum bit width required to store the scalar by using ValueTracking to
8612   // compute the number of high-order bits we can truncate.
8613   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8614       llvm::all_of(TreeRoot, [](Value *R) {
8615         assert(R->hasOneUse() && "Root should have only one use!");
8616         return isa<GetElementPtrInst>(R->user_back());
8617       })) {
8618     MaxBitWidth = 8u;
8619 
8620     // Determine if the sign bit of all the roots is known to be zero. If not,
8621     // IsKnownPositive is set to False.
8622     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8623       KnownBits Known = computeKnownBits(R, *DL);
8624       return Known.isNonNegative();
8625     });
8626 
8627     // Determine the maximum number of bits required to store the scalar
8628     // values.
8629     for (auto *Scalar : ToDemote) {
8630       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8631       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8632       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8633     }
8634 
8635     // If we can't prove that the sign bit is zero, we must add one to the
8636     // maximum bit width to account for the unknown sign bit. This preserves
8637     // the existing sign bit so we can safely sign-extend the root back to the
8638     // original type. Otherwise, if we know the sign bit is zero, we will
8639     // zero-extend the root instead.
8640     //
8641     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8642     //        one to the maximum bit width will yield a larger-than-necessary
8643     //        type. In general, we need to add an extra bit only if we can't
8644     //        prove that the upper bit of the original type is equal to the
8645     //        upper bit of the proposed smaller type. If these two bits are the
8646     //        same (either zero or one) we know that sign-extending from the
8647     //        smaller type will result in the same value. Here, since we can't
8648     //        yet prove this, we are just making the proposed smaller type
8649     //        larger to ensure correctness.
8650     if (!IsKnownPositive)
8651       ++MaxBitWidth;
8652   }
8653 
8654   // Round MaxBitWidth up to the next power-of-two.
8655   if (!isPowerOf2_64(MaxBitWidth))
8656     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8657 
8658   // If the maximum bit width we compute is less than the with of the roots'
8659   // type, we can proceed with the narrowing. Otherwise, do nothing.
8660   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8661     return;
8662 
8663   // If we can truncate the root, we must collect additional values that might
8664   // be demoted as a result. That is, those seeded by truncations we will
8665   // modify.
8666   while (!Roots.empty())
8667     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8668 
8669   // Finally, map the values we can demote to the maximum bit with we computed.
8670   for (auto *Scalar : ToDemote)
8671     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8672 }
8673 
8674 namespace {
8675 
8676 /// The SLPVectorizer Pass.
8677 struct SLPVectorizer : public FunctionPass {
8678   SLPVectorizerPass Impl;
8679 
8680   /// Pass identification, replacement for typeid
8681   static char ID;
8682 
8683   explicit SLPVectorizer() : FunctionPass(ID) {
8684     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8685   }
8686 
8687   bool doInitialization(Module &M) override { return false; }
8688 
8689   bool runOnFunction(Function &F) override {
8690     if (skipFunction(F))
8691       return false;
8692 
8693     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8694     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8695     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8696     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8697     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8698     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8699     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8700     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8701     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8702     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8703 
8704     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8705   }
8706 
8707   void getAnalysisUsage(AnalysisUsage &AU) const override {
8708     FunctionPass::getAnalysisUsage(AU);
8709     AU.addRequired<AssumptionCacheTracker>();
8710     AU.addRequired<ScalarEvolutionWrapperPass>();
8711     AU.addRequired<AAResultsWrapperPass>();
8712     AU.addRequired<TargetTransformInfoWrapperPass>();
8713     AU.addRequired<LoopInfoWrapperPass>();
8714     AU.addRequired<DominatorTreeWrapperPass>();
8715     AU.addRequired<DemandedBitsWrapperPass>();
8716     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8717     AU.addRequired<InjectTLIMappingsLegacy>();
8718     AU.addPreserved<LoopInfoWrapperPass>();
8719     AU.addPreserved<DominatorTreeWrapperPass>();
8720     AU.addPreserved<AAResultsWrapperPass>();
8721     AU.addPreserved<GlobalsAAWrapperPass>();
8722     AU.setPreservesCFG();
8723   }
8724 };
8725 
8726 } // end anonymous namespace
8727 
8728 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8729   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8730   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8731   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8732   auto *AA = &AM.getResult<AAManager>(F);
8733   auto *LI = &AM.getResult<LoopAnalysis>(F);
8734   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8735   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8736   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8737   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8738 
8739   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8740   if (!Changed)
8741     return PreservedAnalyses::all();
8742 
8743   PreservedAnalyses PA;
8744   PA.preserveSet<CFGAnalyses>();
8745   return PA;
8746 }
8747 
8748 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8749                                 TargetTransformInfo *TTI_,
8750                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8751                                 LoopInfo *LI_, DominatorTree *DT_,
8752                                 AssumptionCache *AC_, DemandedBits *DB_,
8753                                 OptimizationRemarkEmitter *ORE_) {
8754   if (!RunSLPVectorization)
8755     return false;
8756   SE = SE_;
8757   TTI = TTI_;
8758   TLI = TLI_;
8759   AA = AA_;
8760   LI = LI_;
8761   DT = DT_;
8762   AC = AC_;
8763   DB = DB_;
8764   DL = &F.getParent()->getDataLayout();
8765 
8766   Stores.clear();
8767   GEPs.clear();
8768   bool Changed = false;
8769 
8770   // If the target claims to have no vector registers don't attempt
8771   // vectorization.
8772   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8773     LLVM_DEBUG(
8774         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8775     return false;
8776   }
8777 
8778   // Don't vectorize when the attribute NoImplicitFloat is used.
8779   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8780     return false;
8781 
8782   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8783 
8784   // Use the bottom up slp vectorizer to construct chains that start with
8785   // store instructions.
8786   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8787 
8788   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8789   // delete instructions.
8790 
8791   // Update DFS numbers now so that we can use them for ordering.
8792   DT->updateDFSNumbers();
8793 
8794   // Scan the blocks in the function in post order.
8795   for (auto BB : post_order(&F.getEntryBlock())) {
8796     collectSeedInstructions(BB);
8797 
8798     // Vectorize trees that end at stores.
8799     if (!Stores.empty()) {
8800       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8801                         << " underlying objects.\n");
8802       Changed |= vectorizeStoreChains(R);
8803     }
8804 
8805     // Vectorize trees that end at reductions.
8806     Changed |= vectorizeChainsInBlock(BB, R);
8807 
8808     // Vectorize the index computations of getelementptr instructions. This
8809     // is primarily intended to catch gather-like idioms ending at
8810     // non-consecutive loads.
8811     if (!GEPs.empty()) {
8812       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8813                         << " underlying objects.\n");
8814       Changed |= vectorizeGEPIndices(BB, R);
8815     }
8816   }
8817 
8818   if (Changed) {
8819     R.optimizeGatherSequence();
8820     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8821   }
8822   return Changed;
8823 }
8824 
8825 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8826                                             unsigned Idx) {
8827   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8828                     << "\n");
8829   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8830   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8831   unsigned VF = Chain.size();
8832 
8833   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8834     return false;
8835 
8836   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8837                     << "\n");
8838 
8839   R.buildTree(Chain);
8840   if (R.isTreeTinyAndNotFullyVectorizable())
8841     return false;
8842   if (R.isLoadCombineCandidate())
8843     return false;
8844   R.reorderTopToBottom();
8845   R.reorderBottomToTop();
8846   R.buildExternalUses();
8847 
8848   R.computeMinimumValueSizes();
8849 
8850   InstructionCost Cost = R.getTreeCost();
8851 
8852   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8853   if (Cost < -SLPCostThreshold) {
8854     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8855 
8856     using namespace ore;
8857 
8858     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8859                                         cast<StoreInst>(Chain[0]))
8860                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8861                      << " and with tree size "
8862                      << NV("TreeSize", R.getTreeSize()));
8863 
8864     R.vectorizeTree();
8865     return true;
8866   }
8867 
8868   return false;
8869 }
8870 
8871 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8872                                         BoUpSLP &R) {
8873   // We may run into multiple chains that merge into a single chain. We mark the
8874   // stores that we vectorized so that we don't visit the same store twice.
8875   BoUpSLP::ValueSet VectorizedStores;
8876   bool Changed = false;
8877 
8878   int E = Stores.size();
8879   SmallBitVector Tails(E, false);
8880   int MaxIter = MaxStoreLookup.getValue();
8881   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8882       E, std::make_pair(E, INT_MAX));
8883   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8884   int IterCnt;
8885   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8886                                   &CheckedPairs,
8887                                   &ConsecutiveChain](int K, int Idx) {
8888     if (IterCnt >= MaxIter)
8889       return true;
8890     if (CheckedPairs[Idx].test(K))
8891       return ConsecutiveChain[K].second == 1 &&
8892              ConsecutiveChain[K].first == Idx;
8893     ++IterCnt;
8894     CheckedPairs[Idx].set(K);
8895     CheckedPairs[K].set(Idx);
8896     Optional<int> Diff = getPointersDiff(
8897         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8898         Stores[Idx]->getValueOperand()->getType(),
8899         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8900     if (!Diff || *Diff == 0)
8901       return false;
8902     int Val = *Diff;
8903     if (Val < 0) {
8904       if (ConsecutiveChain[Idx].second > -Val) {
8905         Tails.set(K);
8906         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8907       }
8908       return false;
8909     }
8910     if (ConsecutiveChain[K].second <= Val)
8911       return false;
8912 
8913     Tails.set(Idx);
8914     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8915     return Val == 1;
8916   };
8917   // Do a quadratic search on all of the given stores in reverse order and find
8918   // all of the pairs of stores that follow each other.
8919   for (int Idx = E - 1; Idx >= 0; --Idx) {
8920     // If a store has multiple consecutive store candidates, search according
8921     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8922     // This is because usually pairing with immediate succeeding or preceding
8923     // candidate create the best chance to find slp vectorization opportunity.
8924     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8925     IterCnt = 0;
8926     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8927       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8928           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8929         break;
8930   }
8931 
8932   // Tracks if we tried to vectorize stores starting from the given tail
8933   // already.
8934   SmallBitVector TriedTails(E, false);
8935   // For stores that start but don't end a link in the chain:
8936   for (int Cnt = E; Cnt > 0; --Cnt) {
8937     int I = Cnt - 1;
8938     if (ConsecutiveChain[I].first == E || Tails.test(I))
8939       continue;
8940     // We found a store instr that starts a chain. Now follow the chain and try
8941     // to vectorize it.
8942     BoUpSLP::ValueList Operands;
8943     // Collect the chain into a list.
8944     while (I != E && !VectorizedStores.count(Stores[I])) {
8945       Operands.push_back(Stores[I]);
8946       Tails.set(I);
8947       if (ConsecutiveChain[I].second != 1) {
8948         // Mark the new end in the chain and go back, if required. It might be
8949         // required if the original stores come in reversed order, for example.
8950         if (ConsecutiveChain[I].first != E &&
8951             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8952             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8953           TriedTails.set(I);
8954           Tails.reset(ConsecutiveChain[I].first);
8955           if (Cnt < ConsecutiveChain[I].first + 2)
8956             Cnt = ConsecutiveChain[I].first + 2;
8957         }
8958         break;
8959       }
8960       // Move to the next value in the chain.
8961       I = ConsecutiveChain[I].first;
8962     }
8963     assert(!Operands.empty() && "Expected non-empty list of stores.");
8964 
8965     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8966     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8967     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8968 
8969     unsigned MinVF = R.getMinVF(EltSize);
8970     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8971                               MaxElts);
8972 
8973     // FIXME: Is division-by-2 the correct step? Should we assert that the
8974     // register size is a power-of-2?
8975     unsigned StartIdx = 0;
8976     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8977       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8978         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8979         if (!VectorizedStores.count(Slice.front()) &&
8980             !VectorizedStores.count(Slice.back()) &&
8981             vectorizeStoreChain(Slice, R, Cnt)) {
8982           // Mark the vectorized stores so that we don't vectorize them again.
8983           VectorizedStores.insert(Slice.begin(), Slice.end());
8984           Changed = true;
8985           // If we vectorized initial block, no need to try to vectorize it
8986           // again.
8987           if (Cnt == StartIdx)
8988             StartIdx += Size;
8989           Cnt += Size;
8990           continue;
8991         }
8992         ++Cnt;
8993       }
8994       // Check if the whole array was vectorized already - exit.
8995       if (StartIdx >= Operands.size())
8996         break;
8997     }
8998   }
8999 
9000   return Changed;
9001 }
9002 
9003 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9004   // Initialize the collections. We will make a single pass over the block.
9005   Stores.clear();
9006   GEPs.clear();
9007 
9008   // Visit the store and getelementptr instructions in BB and organize them in
9009   // Stores and GEPs according to the underlying objects of their pointer
9010   // operands.
9011   for (Instruction &I : *BB) {
9012     // Ignore store instructions that are volatile or have a pointer operand
9013     // that doesn't point to a scalar type.
9014     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9015       if (!SI->isSimple())
9016         continue;
9017       if (!isValidElementType(SI->getValueOperand()->getType()))
9018         continue;
9019       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9020     }
9021 
9022     // Ignore getelementptr instructions that have more than one index, a
9023     // constant index, or a pointer operand that doesn't point to a scalar
9024     // type.
9025     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9026       auto Idx = GEP->idx_begin()->get();
9027       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9028         continue;
9029       if (!isValidElementType(Idx->getType()))
9030         continue;
9031       if (GEP->getType()->isVectorTy())
9032         continue;
9033       GEPs[GEP->getPointerOperand()].push_back(GEP);
9034     }
9035   }
9036 }
9037 
9038 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9039   if (!A || !B)
9040     return false;
9041   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9042     return false;
9043   Value *VL[] = {A, B};
9044   return tryToVectorizeList(VL, R);
9045 }
9046 
9047 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9048                                            bool LimitForRegisterSize) {
9049   if (VL.size() < 2)
9050     return false;
9051 
9052   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9053                     << VL.size() << ".\n");
9054 
9055   // Check that all of the parts are instructions of the same type,
9056   // we permit an alternate opcode via InstructionsState.
9057   InstructionsState S = getSameOpcode(VL);
9058   if (!S.getOpcode())
9059     return false;
9060 
9061   Instruction *I0 = cast<Instruction>(S.OpValue);
9062   // Make sure invalid types (including vector type) are rejected before
9063   // determining vectorization factor for scalar instructions.
9064   for (Value *V : VL) {
9065     Type *Ty = V->getType();
9066     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9067       // NOTE: the following will give user internal llvm type name, which may
9068       // not be useful.
9069       R.getORE()->emit([&]() {
9070         std::string type_str;
9071         llvm::raw_string_ostream rso(type_str);
9072         Ty->print(rso);
9073         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9074                << "Cannot SLP vectorize list: type "
9075                << rso.str() + " is unsupported by vectorizer";
9076       });
9077       return false;
9078     }
9079   }
9080 
9081   unsigned Sz = R.getVectorElementSize(I0);
9082   unsigned MinVF = R.getMinVF(Sz);
9083   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9084   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9085   if (MaxVF < 2) {
9086     R.getORE()->emit([&]() {
9087       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9088              << "Cannot SLP vectorize list: vectorization factor "
9089              << "less than 2 is not supported";
9090     });
9091     return false;
9092   }
9093 
9094   bool Changed = false;
9095   bool CandidateFound = false;
9096   InstructionCost MinCost = SLPCostThreshold.getValue();
9097   Type *ScalarTy = VL[0]->getType();
9098   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9099     ScalarTy = IE->getOperand(1)->getType();
9100 
9101   unsigned NextInst = 0, MaxInst = VL.size();
9102   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9103     // No actual vectorization should happen, if number of parts is the same as
9104     // provided vectorization factor (i.e. the scalar type is used for vector
9105     // code during codegen).
9106     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9107     if (TTI->getNumberOfParts(VecTy) == VF)
9108       continue;
9109     for (unsigned I = NextInst; I < MaxInst; ++I) {
9110       unsigned OpsWidth = 0;
9111 
9112       if (I + VF > MaxInst)
9113         OpsWidth = MaxInst - I;
9114       else
9115         OpsWidth = VF;
9116 
9117       if (!isPowerOf2_32(OpsWidth))
9118         continue;
9119 
9120       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9121           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9122         break;
9123 
9124       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9125       // Check that a previous iteration of this loop did not delete the Value.
9126       if (llvm::any_of(Ops, [&R](Value *V) {
9127             auto *I = dyn_cast<Instruction>(V);
9128             return I && R.isDeleted(I);
9129           }))
9130         continue;
9131 
9132       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9133                         << "\n");
9134 
9135       R.buildTree(Ops);
9136       if (R.isTreeTinyAndNotFullyVectorizable())
9137         continue;
9138       R.reorderTopToBottom();
9139       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9140       R.buildExternalUses();
9141 
9142       R.computeMinimumValueSizes();
9143       InstructionCost Cost = R.getTreeCost();
9144       CandidateFound = true;
9145       MinCost = std::min(MinCost, Cost);
9146 
9147       if (Cost < -SLPCostThreshold) {
9148         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9149         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9150                                                     cast<Instruction>(Ops[0]))
9151                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9152                                  << " and with tree size "
9153                                  << ore::NV("TreeSize", R.getTreeSize()));
9154 
9155         R.vectorizeTree();
9156         // Move to the next bundle.
9157         I += VF - 1;
9158         NextInst = I + 1;
9159         Changed = true;
9160       }
9161     }
9162   }
9163 
9164   if (!Changed && CandidateFound) {
9165     R.getORE()->emit([&]() {
9166       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9167              << "List vectorization was possible but not beneficial with cost "
9168              << ore::NV("Cost", MinCost) << " >= "
9169              << ore::NV("Treshold", -SLPCostThreshold);
9170     });
9171   } else if (!Changed) {
9172     R.getORE()->emit([&]() {
9173       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9174              << "Cannot SLP vectorize list: vectorization was impossible"
9175              << " with available vectorization factors";
9176     });
9177   }
9178   return Changed;
9179 }
9180 
9181 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9182   if (!I)
9183     return false;
9184 
9185   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9186       isa<VectorType>(I->getType()))
9187     return false;
9188 
9189   Value *P = I->getParent();
9190 
9191   // Vectorize in current basic block only.
9192   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9193   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9194   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9195     return false;
9196 
9197   // First collect all possible candidates
9198   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9199   Candidates.emplace_back(Op0, Op1);
9200 
9201   auto *A = dyn_cast<BinaryOperator>(Op0);
9202   auto *B = dyn_cast<BinaryOperator>(Op1);
9203   // Try to skip B.
9204   if (A && B && B->hasOneUse()) {
9205     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9206     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9207     if (B0 && B0->getParent() == P)
9208       Candidates.emplace_back(A, B0);
9209     if (B1 && B1->getParent() == P)
9210       Candidates.emplace_back(A, B1);
9211   }
9212   // Try to skip A.
9213   if (B && A && A->hasOneUse()) {
9214     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9215     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9216     if (A0 && A0->getParent() == P)
9217       Candidates.emplace_back(A0, B);
9218     if (A1 && A1->getParent() == P)
9219       Candidates.emplace_back(A1, B);
9220   }
9221 
9222   if (Candidates.size() == 1)
9223     return tryToVectorizePair(Op0, Op1, R);
9224 
9225   // We have multiple options. Try to pick the single best.
9226   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9227   if (!BestCandidate)
9228     return false;
9229   return tryToVectorizePair(Candidates[*BestCandidate].first,
9230                             Candidates[*BestCandidate].second, R);
9231 }
9232 
9233 namespace {
9234 
9235 /// Model horizontal reductions.
9236 ///
9237 /// A horizontal reduction is a tree of reduction instructions that has values
9238 /// that can be put into a vector as its leaves. For example:
9239 ///
9240 /// mul mul mul mul
9241 ///  \  /    \  /
9242 ///   +       +
9243 ///    \     /
9244 ///       +
9245 /// This tree has "mul" as its leaf values and "+" as its reduction
9246 /// instructions. A reduction can feed into a store or a binary operation
9247 /// feeding a phi.
9248 ///    ...
9249 ///    \  /
9250 ///     +
9251 ///     |
9252 ///  phi +=
9253 ///
9254 ///  Or:
9255 ///    ...
9256 ///    \  /
9257 ///     +
9258 ///     |
9259 ///   *p =
9260 ///
9261 class HorizontalReduction {
9262   using ReductionOpsType = SmallVector<Value *, 16>;
9263   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9264   ReductionOpsListType ReductionOps;
9265   SmallVector<Value *, 32> ReducedVals;
9266   // Use map vector to make stable output.
9267   MapVector<Instruction *, Value *> ExtraArgs;
9268   WeakTrackingVH ReductionRoot;
9269   /// The type of reduction operation.
9270   RecurKind RdxKind;
9271 
9272   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9273 
9274   static bool isCmpSelMinMax(Instruction *I) {
9275     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9276            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9277   }
9278 
9279   // And/or are potentially poison-safe logical patterns like:
9280   // select x, y, false
9281   // select x, true, y
9282   static bool isBoolLogicOp(Instruction *I) {
9283     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9284            match(I, m_LogicalOr(m_Value(), m_Value()));
9285   }
9286 
9287   /// Checks if instruction is associative and can be vectorized.
9288   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9289     if (Kind == RecurKind::None)
9290       return false;
9291 
9292     // Integer ops that map to select instructions or intrinsics are fine.
9293     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9294         isBoolLogicOp(I))
9295       return true;
9296 
9297     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9298       // FP min/max are associative except for NaN and -0.0. We do not
9299       // have to rule out -0.0 here because the intrinsic semantics do not
9300       // specify a fixed result for it.
9301       return I->getFastMathFlags().noNaNs();
9302     }
9303 
9304     return I->isAssociative();
9305   }
9306 
9307   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9308     // Poison-safe 'or' takes the form: select X, true, Y
9309     // To make that work with the normal operand processing, we skip the
9310     // true value operand.
9311     // TODO: Change the code and data structures to handle this without a hack.
9312     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9313       return I->getOperand(2);
9314     return I->getOperand(Index);
9315   }
9316 
9317   /// Checks if the ParentStackElem.first should be marked as a reduction
9318   /// operation with an extra argument or as extra argument itself.
9319   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9320                     Value *ExtraArg) {
9321     if (ExtraArgs.count(ParentStackElem.first)) {
9322       ExtraArgs[ParentStackElem.first] = nullptr;
9323       // We ran into something like:
9324       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9325       // The whole ParentStackElem.first should be considered as an extra value
9326       // in this case.
9327       // Do not perform analysis of remaining operands of ParentStackElem.first
9328       // instruction, this whole instruction is an extra argument.
9329       ParentStackElem.second = INVALID_OPERAND_INDEX;
9330     } else {
9331       // We ran into something like:
9332       // ParentStackElem.first += ... + ExtraArg + ...
9333       ExtraArgs[ParentStackElem.first] = ExtraArg;
9334     }
9335   }
9336 
9337   /// Creates reduction operation with the current opcode.
9338   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9339                          Value *RHS, const Twine &Name, bool UseSelect) {
9340     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9341     switch (Kind) {
9342     case RecurKind::Or:
9343       if (UseSelect &&
9344           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9345         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9346       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9347                                  Name);
9348     case RecurKind::And:
9349       if (UseSelect &&
9350           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9351         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9352       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9353                                  Name);
9354     case RecurKind::Add:
9355     case RecurKind::Mul:
9356     case RecurKind::Xor:
9357     case RecurKind::FAdd:
9358     case RecurKind::FMul:
9359       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9360                                  Name);
9361     case RecurKind::FMax:
9362       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9363     case RecurKind::FMin:
9364       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9365     case RecurKind::SMax:
9366       if (UseSelect) {
9367         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9368         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9369       }
9370       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9371     case RecurKind::SMin:
9372       if (UseSelect) {
9373         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9374         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9375       }
9376       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9377     case RecurKind::UMax:
9378       if (UseSelect) {
9379         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9380         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9381       }
9382       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9383     case RecurKind::UMin:
9384       if (UseSelect) {
9385         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9386         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9387       }
9388       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9389     default:
9390       llvm_unreachable("Unknown reduction operation.");
9391     }
9392   }
9393 
9394   /// Creates reduction operation with the current opcode with the IR flags
9395   /// from \p ReductionOps.
9396   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9397                          Value *RHS, const Twine &Name,
9398                          const ReductionOpsListType &ReductionOps) {
9399     bool UseSelect = ReductionOps.size() == 2 ||
9400                      // Logical or/and.
9401                      (ReductionOps.size() == 1 &&
9402                       isa<SelectInst>(ReductionOps.front().front()));
9403     assert((!UseSelect || ReductionOps.size() != 2 ||
9404             isa<SelectInst>(ReductionOps[1][0])) &&
9405            "Expected cmp + select pairs for reduction");
9406     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9407     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9408       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9409         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9410         propagateIRFlags(Op, ReductionOps[1]);
9411         return Op;
9412       }
9413     }
9414     propagateIRFlags(Op, ReductionOps[0]);
9415     return Op;
9416   }
9417 
9418   /// Creates reduction operation with the current opcode with the IR flags
9419   /// from \p I.
9420   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9421                          Value *RHS, const Twine &Name, Instruction *I) {
9422     auto *SelI = dyn_cast<SelectInst>(I);
9423     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9424     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9425       if (auto *Sel = dyn_cast<SelectInst>(Op))
9426         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9427     }
9428     propagateIRFlags(Op, I);
9429     return Op;
9430   }
9431 
9432   static RecurKind getRdxKind(Instruction *I) {
9433     assert(I && "Expected instruction for reduction matching");
9434     if (match(I, m_Add(m_Value(), m_Value())))
9435       return RecurKind::Add;
9436     if (match(I, m_Mul(m_Value(), m_Value())))
9437       return RecurKind::Mul;
9438     if (match(I, m_And(m_Value(), m_Value())) ||
9439         match(I, m_LogicalAnd(m_Value(), m_Value())))
9440       return RecurKind::And;
9441     if (match(I, m_Or(m_Value(), m_Value())) ||
9442         match(I, m_LogicalOr(m_Value(), m_Value())))
9443       return RecurKind::Or;
9444     if (match(I, m_Xor(m_Value(), m_Value())))
9445       return RecurKind::Xor;
9446     if (match(I, m_FAdd(m_Value(), m_Value())))
9447       return RecurKind::FAdd;
9448     if (match(I, m_FMul(m_Value(), m_Value())))
9449       return RecurKind::FMul;
9450 
9451     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9452       return RecurKind::FMax;
9453     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9454       return RecurKind::FMin;
9455 
9456     // This matches either cmp+select or intrinsics. SLP is expected to handle
9457     // either form.
9458     // TODO: If we are canonicalizing to intrinsics, we can remove several
9459     //       special-case paths that deal with selects.
9460     if (match(I, m_SMax(m_Value(), m_Value())))
9461       return RecurKind::SMax;
9462     if (match(I, m_SMin(m_Value(), m_Value())))
9463       return RecurKind::SMin;
9464     if (match(I, m_UMax(m_Value(), m_Value())))
9465       return RecurKind::UMax;
9466     if (match(I, m_UMin(m_Value(), m_Value())))
9467       return RecurKind::UMin;
9468 
9469     if (auto *Select = dyn_cast<SelectInst>(I)) {
9470       // Try harder: look for min/max pattern based on instructions producing
9471       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9472       // During the intermediate stages of SLP, it's very common to have
9473       // pattern like this (since optimizeGatherSequence is run only once
9474       // at the end):
9475       // %1 = extractelement <2 x i32> %a, i32 0
9476       // %2 = extractelement <2 x i32> %a, i32 1
9477       // %cond = icmp sgt i32 %1, %2
9478       // %3 = extractelement <2 x i32> %a, i32 0
9479       // %4 = extractelement <2 x i32> %a, i32 1
9480       // %select = select i1 %cond, i32 %3, i32 %4
9481       CmpInst::Predicate Pred;
9482       Instruction *L1;
9483       Instruction *L2;
9484 
9485       Value *LHS = Select->getTrueValue();
9486       Value *RHS = Select->getFalseValue();
9487       Value *Cond = Select->getCondition();
9488 
9489       // TODO: Support inverse predicates.
9490       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9491         if (!isa<ExtractElementInst>(RHS) ||
9492             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9493           return RecurKind::None;
9494       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9495         if (!isa<ExtractElementInst>(LHS) ||
9496             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9497           return RecurKind::None;
9498       } else {
9499         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9500           return RecurKind::None;
9501         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9502             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9503             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9504           return RecurKind::None;
9505       }
9506 
9507       switch (Pred) {
9508       default:
9509         return RecurKind::None;
9510       case CmpInst::ICMP_SGT:
9511       case CmpInst::ICMP_SGE:
9512         return RecurKind::SMax;
9513       case CmpInst::ICMP_SLT:
9514       case CmpInst::ICMP_SLE:
9515         return RecurKind::SMin;
9516       case CmpInst::ICMP_UGT:
9517       case CmpInst::ICMP_UGE:
9518         return RecurKind::UMax;
9519       case CmpInst::ICMP_ULT:
9520       case CmpInst::ICMP_ULE:
9521         return RecurKind::UMin;
9522       }
9523     }
9524     return RecurKind::None;
9525   }
9526 
9527   /// Get the index of the first operand.
9528   static unsigned getFirstOperandIndex(Instruction *I) {
9529     return isCmpSelMinMax(I) ? 1 : 0;
9530   }
9531 
9532   /// Total number of operands in the reduction operation.
9533   static unsigned getNumberOfOperands(Instruction *I) {
9534     return isCmpSelMinMax(I) ? 3 : 2;
9535   }
9536 
9537   /// Checks if the instruction is in basic block \p BB.
9538   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9539   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9540     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9541       auto *Sel = cast<SelectInst>(I);
9542       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9543       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9544     }
9545     return I->getParent() == BB;
9546   }
9547 
9548   /// Expected number of uses for reduction operations/reduced values.
9549   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9550     if (IsCmpSelMinMax) {
9551       // SelectInst must be used twice while the condition op must have single
9552       // use only.
9553       if (auto *Sel = dyn_cast<SelectInst>(I))
9554         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9555       return I->hasNUses(2);
9556     }
9557 
9558     // Arithmetic reduction operation must be used once only.
9559     return I->hasOneUse();
9560   }
9561 
9562   /// Initializes the list of reduction operations.
9563   void initReductionOps(Instruction *I) {
9564     if (isCmpSelMinMax(I))
9565       ReductionOps.assign(2, ReductionOpsType());
9566     else
9567       ReductionOps.assign(1, ReductionOpsType());
9568   }
9569 
9570   /// Add all reduction operations for the reduction instruction \p I.
9571   void addReductionOps(Instruction *I) {
9572     if (isCmpSelMinMax(I)) {
9573       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9574       ReductionOps[1].emplace_back(I);
9575     } else {
9576       ReductionOps[0].emplace_back(I);
9577     }
9578   }
9579 
9580   static Value *getLHS(RecurKind Kind, Instruction *I) {
9581     if (Kind == RecurKind::None)
9582       return nullptr;
9583     return I->getOperand(getFirstOperandIndex(I));
9584   }
9585   static Value *getRHS(RecurKind Kind, Instruction *I) {
9586     if (Kind == RecurKind::None)
9587       return nullptr;
9588     return I->getOperand(getFirstOperandIndex(I) + 1);
9589   }
9590 
9591 public:
9592   HorizontalReduction() = default;
9593 
9594   /// Try to find a reduction tree.
9595   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9596     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9597            "Phi needs to use the binary operator");
9598     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9599             isa<IntrinsicInst>(Inst)) &&
9600            "Expected binop, select, or intrinsic for reduction matching");
9601     RdxKind = getRdxKind(Inst);
9602 
9603     // We could have a initial reductions that is not an add.
9604     //  r *= v1 + v2 + v3 + v4
9605     // In such a case start looking for a tree rooted in the first '+'.
9606     if (Phi) {
9607       if (getLHS(RdxKind, Inst) == Phi) {
9608         Phi = nullptr;
9609         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9610         if (!Inst)
9611           return false;
9612         RdxKind = getRdxKind(Inst);
9613       } else if (getRHS(RdxKind, Inst) == Phi) {
9614         Phi = nullptr;
9615         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9616         if (!Inst)
9617           return false;
9618         RdxKind = getRdxKind(Inst);
9619       }
9620     }
9621 
9622     if (!isVectorizable(RdxKind, Inst))
9623       return false;
9624 
9625     // Analyze "regular" integer/FP types for reductions - no target-specific
9626     // types or pointers.
9627     Type *Ty = Inst->getType();
9628     if (!isValidElementType(Ty) || Ty->isPointerTy())
9629       return false;
9630 
9631     // Though the ultimate reduction may have multiple uses, its condition must
9632     // have only single use.
9633     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9634       if (!Sel->getCondition()->hasOneUse())
9635         return false;
9636 
9637     ReductionRoot = Inst;
9638 
9639     // The opcode for leaf values that we perform a reduction on.
9640     // For example: load(x) + load(y) + load(z) + fptoui(w)
9641     // The leaf opcode for 'w' does not match, so we don't include it as a
9642     // potential candidate for the reduction.
9643     unsigned LeafOpcode = 0;
9644 
9645     // Post-order traverse the reduction tree starting at Inst. We only handle
9646     // true trees containing binary operators or selects.
9647     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9648     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9649     initReductionOps(Inst);
9650     while (!Stack.empty()) {
9651       Instruction *TreeN = Stack.back().first;
9652       unsigned EdgeToVisit = Stack.back().second++;
9653       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9654       bool IsReducedValue = TreeRdxKind != RdxKind;
9655 
9656       // Postorder visit.
9657       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9658         if (IsReducedValue)
9659           ReducedVals.push_back(TreeN);
9660         else {
9661           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9662           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9663             // Check if TreeN is an extra argument of its parent operation.
9664             if (Stack.size() <= 1) {
9665               // TreeN can't be an extra argument as it is a root reduction
9666               // operation.
9667               return false;
9668             }
9669             // Yes, TreeN is an extra argument, do not add it to a list of
9670             // reduction operations.
9671             // Stack[Stack.size() - 2] always points to the parent operation.
9672             markExtraArg(Stack[Stack.size() - 2], TreeN);
9673             ExtraArgs.erase(TreeN);
9674           } else
9675             addReductionOps(TreeN);
9676         }
9677         // Retract.
9678         Stack.pop_back();
9679         continue;
9680       }
9681 
9682       // Visit operands.
9683       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9684       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9685       if (!EdgeInst) {
9686         // Edge value is not a reduction instruction or a leaf instruction.
9687         // (It may be a constant, function argument, or something else.)
9688         markExtraArg(Stack.back(), EdgeVal);
9689         continue;
9690       }
9691       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9692       // Continue analysis if the next operand is a reduction operation or
9693       // (possibly) a leaf value. If the leaf value opcode is not set,
9694       // the first met operation != reduction operation is considered as the
9695       // leaf opcode.
9696       // Only handle trees in the current basic block.
9697       // Each tree node needs to have minimal number of users except for the
9698       // ultimate reduction.
9699       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9700       if (EdgeInst != Phi && EdgeInst != Inst &&
9701           hasSameParent(EdgeInst, Inst->getParent()) &&
9702           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9703           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9704         if (IsRdxInst) {
9705           // We need to be able to reassociate the reduction operations.
9706           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9707             // I is an extra argument for TreeN (its parent operation).
9708             markExtraArg(Stack.back(), EdgeInst);
9709             continue;
9710           }
9711         } else if (!LeafOpcode) {
9712           LeafOpcode = EdgeInst->getOpcode();
9713         }
9714         Stack.push_back(
9715             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9716         continue;
9717       }
9718       // I is an extra argument for TreeN (its parent operation).
9719       markExtraArg(Stack.back(), EdgeInst);
9720     }
9721     return true;
9722   }
9723 
9724   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9725   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9726     // If there are a sufficient number of reduction values, reduce
9727     // to a nearby power-of-2. We can safely generate oversized
9728     // vectors and rely on the backend to split them to legal sizes.
9729     unsigned NumReducedVals = ReducedVals.size();
9730     if (NumReducedVals < 4)
9731       return nullptr;
9732 
9733     // Intersect the fast-math-flags from all reduction operations.
9734     FastMathFlags RdxFMF;
9735     RdxFMF.set();
9736     for (ReductionOpsType &RdxOp : ReductionOps) {
9737       for (Value *RdxVal : RdxOp) {
9738         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9739           RdxFMF &= FPMO->getFastMathFlags();
9740       }
9741     }
9742 
9743     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9744     Builder.setFastMathFlags(RdxFMF);
9745 
9746     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9747     // The same extra argument may be used several times, so log each attempt
9748     // to use it.
9749     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9750       assert(Pair.first && "DebugLoc must be set.");
9751       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9752     }
9753 
9754     // The compare instruction of a min/max is the insertion point for new
9755     // instructions and may be replaced with a new compare instruction.
9756     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9757       assert(isa<SelectInst>(RdxRootInst) &&
9758              "Expected min/max reduction to have select root instruction");
9759       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9760       assert(isa<Instruction>(ScalarCond) &&
9761              "Expected min/max reduction to have compare condition");
9762       return cast<Instruction>(ScalarCond);
9763     };
9764 
9765     // The reduction root is used as the insertion point for new instructions,
9766     // so set it as externally used to prevent it from being deleted.
9767     ExternallyUsedValues[ReductionRoot];
9768     SmallVector<Value *, 16> IgnoreList;
9769     for (ReductionOpsType &RdxOp : ReductionOps)
9770       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9771 
9772     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9773     if (NumReducedVals > ReduxWidth) {
9774       // In the loop below, we are building a tree based on a window of
9775       // 'ReduxWidth' values.
9776       // If the operands of those values have common traits (compare predicate,
9777       // constant operand, etc), then we want to group those together to
9778       // minimize the cost of the reduction.
9779 
9780       // TODO: This should be extended to count common operands for
9781       //       compares and binops.
9782 
9783       // Step 1: Count the number of times each compare predicate occurs.
9784       SmallDenseMap<unsigned, unsigned> PredCountMap;
9785       for (Value *RdxVal : ReducedVals) {
9786         CmpInst::Predicate Pred;
9787         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9788           ++PredCountMap[Pred];
9789       }
9790       // Step 2: Sort the values so the most common predicates come first.
9791       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9792         CmpInst::Predicate PredA, PredB;
9793         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9794             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9795           return PredCountMap[PredA] > PredCountMap[PredB];
9796         }
9797         return false;
9798       });
9799     }
9800 
9801     Value *VectorizedTree = nullptr;
9802     unsigned i = 0;
9803     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9804       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9805       V.buildTree(VL, IgnoreList);
9806       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9807         break;
9808       if (V.isLoadCombineReductionCandidate(RdxKind))
9809         break;
9810       V.reorderTopToBottom();
9811       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9812       V.buildExternalUses(ExternallyUsedValues);
9813 
9814       // For a poison-safe boolean logic reduction, do not replace select
9815       // instructions with logic ops. All reduced values will be frozen (see
9816       // below) to prevent leaking poison.
9817       if (isa<SelectInst>(ReductionRoot) &&
9818           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9819           NumReducedVals != ReduxWidth)
9820         break;
9821 
9822       V.computeMinimumValueSizes();
9823 
9824       // Estimate cost.
9825       InstructionCost TreeCost =
9826           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9827       InstructionCost ReductionCost =
9828           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9829       InstructionCost Cost = TreeCost + ReductionCost;
9830       if (!Cost.isValid()) {
9831         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9832         return nullptr;
9833       }
9834       if (Cost >= -SLPCostThreshold) {
9835         V.getORE()->emit([&]() {
9836           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9837                                           cast<Instruction>(VL[0]))
9838                  << "Vectorizing horizontal reduction is possible"
9839                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9840                  << " and threshold "
9841                  << ore::NV("Threshold", -SLPCostThreshold);
9842         });
9843         break;
9844       }
9845 
9846       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9847                         << Cost << ". (HorRdx)\n");
9848       V.getORE()->emit([&]() {
9849         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9850                                   cast<Instruction>(VL[0]))
9851                << "Vectorized horizontal reduction with cost "
9852                << ore::NV("Cost", Cost) << " and with tree size "
9853                << ore::NV("TreeSize", V.getTreeSize());
9854       });
9855 
9856       // Vectorize a tree.
9857       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9858       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9859 
9860       // Emit a reduction. If the root is a select (min/max idiom), the insert
9861       // point is the compare condition of that select.
9862       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9863       if (isCmpSelMinMax(RdxRootInst))
9864         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9865       else
9866         Builder.SetInsertPoint(RdxRootInst);
9867 
9868       // To prevent poison from leaking across what used to be sequential, safe,
9869       // scalar boolean logic operations, the reduction operand must be frozen.
9870       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9871         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9872 
9873       Value *ReducedSubTree =
9874           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9875 
9876       if (!VectorizedTree) {
9877         // Initialize the final value in the reduction.
9878         VectorizedTree = ReducedSubTree;
9879       } else {
9880         // Update the final value in the reduction.
9881         Builder.SetCurrentDebugLocation(Loc);
9882         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9883                                   ReducedSubTree, "op.rdx", ReductionOps);
9884       }
9885       i += ReduxWidth;
9886       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9887     }
9888 
9889     if (VectorizedTree) {
9890       // Finish the reduction.
9891       for (; i < NumReducedVals; ++i) {
9892         auto *I = cast<Instruction>(ReducedVals[i]);
9893         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9894         VectorizedTree =
9895             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9896       }
9897       for (auto &Pair : ExternallyUsedValues) {
9898         // Add each externally used value to the final reduction.
9899         for (auto *I : Pair.second) {
9900           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9901           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9902                                     Pair.first, "op.extra", I);
9903         }
9904       }
9905 
9906       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9907 
9908       // The original scalar reduction is expected to have no remaining
9909       // uses outside the reduction tree itself.  Assert that we got this
9910       // correct, replace internal uses with undef, and mark for eventual
9911       // deletion.
9912 #ifndef NDEBUG
9913       SmallSet<Value *, 4> IgnoreSet;
9914       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
9915 #endif
9916       for (auto *Ignore : IgnoreList) {
9917 #ifndef NDEBUG
9918         for (auto *U : Ignore->users()) {
9919           assert(IgnoreSet.count(U));
9920         }
9921 #endif
9922         if (!Ignore->use_empty()) {
9923           Value *Undef = UndefValue::get(Ignore->getType());
9924           Ignore->replaceAllUsesWith(Undef);
9925         }
9926         V.eraseInstruction(cast<Instruction>(Ignore));
9927       }
9928     }
9929     return VectorizedTree;
9930   }
9931 
9932   unsigned numReductionValues() const { return ReducedVals.size(); }
9933 
9934 private:
9935   /// Calculate the cost of a reduction.
9936   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9937                                    Value *FirstReducedVal, unsigned ReduxWidth,
9938                                    FastMathFlags FMF) {
9939     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9940     Type *ScalarTy = FirstReducedVal->getType();
9941     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9942     InstructionCost VectorCost, ScalarCost;
9943     switch (RdxKind) {
9944     case RecurKind::Add:
9945     case RecurKind::Mul:
9946     case RecurKind::Or:
9947     case RecurKind::And:
9948     case RecurKind::Xor:
9949     case RecurKind::FAdd:
9950     case RecurKind::FMul: {
9951       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9952       VectorCost =
9953           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9954       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9955       break;
9956     }
9957     case RecurKind::FMax:
9958     case RecurKind::FMin: {
9959       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9960       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9961       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9962                                                /*IsUnsigned=*/false, CostKind);
9963       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9964       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9965                                            SclCondTy, RdxPred, CostKind) +
9966                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9967                                            SclCondTy, RdxPred, CostKind);
9968       break;
9969     }
9970     case RecurKind::SMax:
9971     case RecurKind::SMin:
9972     case RecurKind::UMax:
9973     case RecurKind::UMin: {
9974       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9975       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9976       bool IsUnsigned =
9977           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9978       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9979                                                CostKind);
9980       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9981       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9982                                            SclCondTy, RdxPred, CostKind) +
9983                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9984                                            SclCondTy, RdxPred, CostKind);
9985       break;
9986     }
9987     default:
9988       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9989     }
9990 
9991     // Scalar cost is repeated for N-1 elements.
9992     ScalarCost *= (ReduxWidth - 1);
9993     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9994                       << " for reduction that starts with " << *FirstReducedVal
9995                       << " (It is a splitting reduction)\n");
9996     return VectorCost - ScalarCost;
9997   }
9998 
9999   /// Emit a horizontal reduction of the vectorized value.
10000   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10001                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10002     assert(VectorizedValue && "Need to have a vectorized tree node");
10003     assert(isPowerOf2_32(ReduxWidth) &&
10004            "We only handle power-of-two reductions for now");
10005     assert(RdxKind != RecurKind::FMulAdd &&
10006            "A call to the llvm.fmuladd intrinsic is not handled yet");
10007 
10008     ++NumVectorInstructions;
10009     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10010   }
10011 };
10012 
10013 } // end anonymous namespace
10014 
10015 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10016   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10017     return cast<FixedVectorType>(IE->getType())->getNumElements();
10018 
10019   unsigned AggregateSize = 1;
10020   auto *IV = cast<InsertValueInst>(InsertInst);
10021   Type *CurrentType = IV->getType();
10022   do {
10023     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10024       for (auto *Elt : ST->elements())
10025         if (Elt != ST->getElementType(0)) // check homogeneity
10026           return None;
10027       AggregateSize *= ST->getNumElements();
10028       CurrentType = ST->getElementType(0);
10029     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10030       AggregateSize *= AT->getNumElements();
10031       CurrentType = AT->getElementType();
10032     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10033       AggregateSize *= VT->getNumElements();
10034       return AggregateSize;
10035     } else if (CurrentType->isSingleValueType()) {
10036       return AggregateSize;
10037     } else {
10038       return None;
10039     }
10040   } while (true);
10041 }
10042 
10043 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10044                                    TargetTransformInfo *TTI,
10045                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10046                                    SmallVectorImpl<Value *> &InsertElts,
10047                                    unsigned OperandOffset) {
10048   do {
10049     Value *InsertedOperand = LastInsertInst->getOperand(1);
10050     Optional<unsigned> OperandIndex =
10051         getInsertIndex(LastInsertInst, OperandOffset);
10052     if (!OperandIndex)
10053       return;
10054     if (isa<InsertElementInst>(InsertedOperand) ||
10055         isa<InsertValueInst>(InsertedOperand)) {
10056       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10057                              BuildVectorOpds, InsertElts, *OperandIndex);
10058 
10059     } else {
10060       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10061       InsertElts[*OperandIndex] = LastInsertInst;
10062     }
10063     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10064   } while (LastInsertInst != nullptr &&
10065            (isa<InsertValueInst>(LastInsertInst) ||
10066             isa<InsertElementInst>(LastInsertInst)) &&
10067            LastInsertInst->hasOneUse());
10068 }
10069 
10070 /// Recognize construction of vectors like
10071 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10072 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10073 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10074 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10075 ///  starting from the last insertelement or insertvalue instruction.
10076 ///
10077 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10078 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10079 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10080 ///
10081 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10082 ///
10083 /// \return true if it matches.
10084 static bool findBuildAggregate(Instruction *LastInsertInst,
10085                                TargetTransformInfo *TTI,
10086                                SmallVectorImpl<Value *> &BuildVectorOpds,
10087                                SmallVectorImpl<Value *> &InsertElts) {
10088 
10089   assert((isa<InsertElementInst>(LastInsertInst) ||
10090           isa<InsertValueInst>(LastInsertInst)) &&
10091          "Expected insertelement or insertvalue instruction!");
10092 
10093   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10094          "Expected empty result vectors!");
10095 
10096   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10097   if (!AggregateSize)
10098     return false;
10099   BuildVectorOpds.resize(*AggregateSize);
10100   InsertElts.resize(*AggregateSize);
10101 
10102   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10103   llvm::erase_value(BuildVectorOpds, nullptr);
10104   llvm::erase_value(InsertElts, nullptr);
10105   if (BuildVectorOpds.size() >= 2)
10106     return true;
10107 
10108   return false;
10109 }
10110 
10111 /// Try and get a reduction value from a phi node.
10112 ///
10113 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10114 /// if they come from either \p ParentBB or a containing loop latch.
10115 ///
10116 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10117 /// if not possible.
10118 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10119                                 BasicBlock *ParentBB, LoopInfo *LI) {
10120   // There are situations where the reduction value is not dominated by the
10121   // reduction phi. Vectorizing such cases has been reported to cause
10122   // miscompiles. See PR25787.
10123   auto DominatedReduxValue = [&](Value *R) {
10124     return isa<Instruction>(R) &&
10125            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10126   };
10127 
10128   Value *Rdx = nullptr;
10129 
10130   // Return the incoming value if it comes from the same BB as the phi node.
10131   if (P->getIncomingBlock(0) == ParentBB) {
10132     Rdx = P->getIncomingValue(0);
10133   } else if (P->getIncomingBlock(1) == ParentBB) {
10134     Rdx = P->getIncomingValue(1);
10135   }
10136 
10137   if (Rdx && DominatedReduxValue(Rdx))
10138     return Rdx;
10139 
10140   // Otherwise, check whether we have a loop latch to look at.
10141   Loop *BBL = LI->getLoopFor(ParentBB);
10142   if (!BBL)
10143     return nullptr;
10144   BasicBlock *BBLatch = BBL->getLoopLatch();
10145   if (!BBLatch)
10146     return nullptr;
10147 
10148   // There is a loop latch, return the incoming value if it comes from
10149   // that. This reduction pattern occasionally turns up.
10150   if (P->getIncomingBlock(0) == BBLatch) {
10151     Rdx = P->getIncomingValue(0);
10152   } else if (P->getIncomingBlock(1) == BBLatch) {
10153     Rdx = P->getIncomingValue(1);
10154   }
10155 
10156   if (Rdx && DominatedReduxValue(Rdx))
10157     return Rdx;
10158 
10159   return nullptr;
10160 }
10161 
10162 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10163   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10164     return true;
10165   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10166     return true;
10167   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10168     return true;
10169   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10170     return true;
10171   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10172     return true;
10173   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10174     return true;
10175   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10176     return true;
10177   return false;
10178 }
10179 
10180 /// Attempt to reduce a horizontal reduction.
10181 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10182 /// with reduction operators \a Root (or one of its operands) in a basic block
10183 /// \a BB, then check if it can be done. If horizontal reduction is not found
10184 /// and root instruction is a binary operation, vectorization of the operands is
10185 /// attempted.
10186 /// \returns true if a horizontal reduction was matched and reduced or operands
10187 /// of one of the binary instruction were vectorized.
10188 /// \returns false if a horizontal reduction was not matched (or not possible)
10189 /// or no vectorization of any binary operation feeding \a Root instruction was
10190 /// performed.
10191 static bool tryToVectorizeHorReductionOrInstOperands(
10192     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10193     TargetTransformInfo *TTI,
10194     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10195   if (!ShouldVectorizeHor)
10196     return false;
10197 
10198   if (!Root)
10199     return false;
10200 
10201   if (Root->getParent() != BB || isa<PHINode>(Root))
10202     return false;
10203   // Start analysis starting from Root instruction. If horizontal reduction is
10204   // found, try to vectorize it. If it is not a horizontal reduction or
10205   // vectorization is not possible or not effective, and currently analyzed
10206   // instruction is a binary operation, try to vectorize the operands, using
10207   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10208   // the same procedure considering each operand as a possible root of the
10209   // horizontal reduction.
10210   // Interrupt the process if the Root instruction itself was vectorized or all
10211   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10212   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10213   // CmpInsts so we can skip extra attempts in
10214   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10215   std::queue<std::pair<Instruction *, unsigned>> Stack;
10216   Stack.emplace(Root, 0);
10217   SmallPtrSet<Value *, 8> VisitedInstrs;
10218   SmallVector<WeakTrackingVH> PostponedInsts;
10219   bool Res = false;
10220   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10221                                      Value *&B1) -> Value * {
10222     bool IsBinop = matchRdxBop(Inst, B0, B1);
10223     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10224     if (IsBinop || IsSelect) {
10225       HorizontalReduction HorRdx;
10226       if (HorRdx.matchAssociativeReduction(P, Inst))
10227         return HorRdx.tryToReduce(R, TTI);
10228     }
10229     return nullptr;
10230   };
10231   while (!Stack.empty()) {
10232     Instruction *Inst;
10233     unsigned Level;
10234     std::tie(Inst, Level) = Stack.front();
10235     Stack.pop();
10236     // Do not try to analyze instruction that has already been vectorized.
10237     // This may happen when we vectorize instruction operands on a previous
10238     // iteration while stack was populated before that happened.
10239     if (R.isDeleted(Inst))
10240       continue;
10241     Value *B0 = nullptr, *B1 = nullptr;
10242     if (Value *V = TryToReduce(Inst, B0, B1)) {
10243       Res = true;
10244       // Set P to nullptr to avoid re-analysis of phi node in
10245       // matchAssociativeReduction function unless this is the root node.
10246       P = nullptr;
10247       if (auto *I = dyn_cast<Instruction>(V)) {
10248         // Try to find another reduction.
10249         Stack.emplace(I, Level);
10250         continue;
10251       }
10252     } else {
10253       bool IsBinop = B0 && B1;
10254       if (P && IsBinop) {
10255         Inst = dyn_cast<Instruction>(B0);
10256         if (Inst == P)
10257           Inst = dyn_cast<Instruction>(B1);
10258         if (!Inst) {
10259           // Set P to nullptr to avoid re-analysis of phi node in
10260           // matchAssociativeReduction function unless this is the root node.
10261           P = nullptr;
10262           continue;
10263         }
10264       }
10265       // Set P to nullptr to avoid re-analysis of phi node in
10266       // matchAssociativeReduction function unless this is the root node.
10267       P = nullptr;
10268       // Do not try to vectorize CmpInst operands, this is done separately.
10269       // Final attempt for binop args vectorization should happen after the loop
10270       // to try to find reductions.
10271       if (!isa<CmpInst>(Inst))
10272         PostponedInsts.push_back(Inst);
10273     }
10274 
10275     // Try to vectorize operands.
10276     // Continue analysis for the instruction from the same basic block only to
10277     // save compile time.
10278     if (++Level < RecursionMaxDepth)
10279       for (auto *Op : Inst->operand_values())
10280         if (VisitedInstrs.insert(Op).second)
10281           if (auto *I = dyn_cast<Instruction>(Op))
10282             // Do not try to vectorize CmpInst operands,  this is done
10283             // separately.
10284             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10285                 I->getParent() == BB)
10286               Stack.emplace(I, Level);
10287   }
10288   // Try to vectorized binops where reductions were not found.
10289   for (Value *V : PostponedInsts)
10290     if (auto *Inst = dyn_cast<Instruction>(V))
10291       if (!R.isDeleted(Inst))
10292         Res |= Vectorize(Inst, R);
10293   return Res;
10294 }
10295 
10296 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10297                                                  BasicBlock *BB, BoUpSLP &R,
10298                                                  TargetTransformInfo *TTI) {
10299   auto *I = dyn_cast_or_null<Instruction>(V);
10300   if (!I)
10301     return false;
10302 
10303   if (!isa<BinaryOperator>(I))
10304     P = nullptr;
10305   // Try to match and vectorize a horizontal reduction.
10306   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10307     return tryToVectorize(I, R);
10308   };
10309   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10310                                                   ExtraVectorization);
10311 }
10312 
10313 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10314                                                  BasicBlock *BB, BoUpSLP &R) {
10315   const DataLayout &DL = BB->getModule()->getDataLayout();
10316   if (!R.canMapToVector(IVI->getType(), DL))
10317     return false;
10318 
10319   SmallVector<Value *, 16> BuildVectorOpds;
10320   SmallVector<Value *, 16> BuildVectorInsts;
10321   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10322     return false;
10323 
10324   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10325   // Aggregate value is unlikely to be processed in vector register.
10326   return tryToVectorizeList(BuildVectorOpds, R);
10327 }
10328 
10329 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10330                                                    BasicBlock *BB, BoUpSLP &R) {
10331   SmallVector<Value *, 16> BuildVectorInsts;
10332   SmallVector<Value *, 16> BuildVectorOpds;
10333   SmallVector<int> Mask;
10334   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10335       (llvm::all_of(
10336            BuildVectorOpds,
10337            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10338        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10339     return false;
10340 
10341   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10342   return tryToVectorizeList(BuildVectorInsts, R);
10343 }
10344 
10345 template <typename T>
10346 static bool
10347 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10348                        function_ref<unsigned(T *)> Limit,
10349                        function_ref<bool(T *, T *)> Comparator,
10350                        function_ref<bool(T *, T *)> AreCompatible,
10351                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10352                        bool LimitForRegisterSize) {
10353   bool Changed = false;
10354   // Sort by type, parent, operands.
10355   stable_sort(Incoming, Comparator);
10356 
10357   // Try to vectorize elements base on their type.
10358   SmallVector<T *> Candidates;
10359   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10360     // Look for the next elements with the same type, parent and operand
10361     // kinds.
10362     auto *SameTypeIt = IncIt;
10363     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10364       ++SameTypeIt;
10365 
10366     // Try to vectorize them.
10367     unsigned NumElts = (SameTypeIt - IncIt);
10368     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10369                       << NumElts << ")\n");
10370     // The vectorization is a 3-state attempt:
10371     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10372     // size of maximal register at first.
10373     // 2. Try to vectorize remaining instructions with the same type, if
10374     // possible. This may result in the better vectorization results rather than
10375     // if we try just to vectorize instructions with the same/alternate opcodes.
10376     // 3. Final attempt to try to vectorize all instructions with the
10377     // same/alternate ops only, this may result in some extra final
10378     // vectorization.
10379     if (NumElts > 1 &&
10380         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10381       // Success start over because instructions might have been changed.
10382       Changed = true;
10383     } else if (NumElts < Limit(*IncIt) &&
10384                (Candidates.empty() ||
10385                 Candidates.front()->getType() == (*IncIt)->getType())) {
10386       Candidates.append(IncIt, std::next(IncIt, NumElts));
10387     }
10388     // Final attempt to vectorize instructions with the same types.
10389     if (Candidates.size() > 1 &&
10390         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10391       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10392         // Success start over because instructions might have been changed.
10393         Changed = true;
10394       } else if (LimitForRegisterSize) {
10395         // Try to vectorize using small vectors.
10396         for (auto *It = Candidates.begin(), *End = Candidates.end();
10397              It != End;) {
10398           auto *SameTypeIt = It;
10399           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10400             ++SameTypeIt;
10401           unsigned NumElts = (SameTypeIt - It);
10402           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10403                                             /*LimitForRegisterSize=*/false))
10404             Changed = true;
10405           It = SameTypeIt;
10406         }
10407       }
10408       Candidates.clear();
10409     }
10410 
10411     // Start over at the next instruction of a different type (or the end).
10412     IncIt = SameTypeIt;
10413   }
10414   return Changed;
10415 }
10416 
10417 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10418 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10419 /// operands. If IsCompatibility is false, function implements strict weak
10420 /// ordering relation between two cmp instructions, returning true if the first
10421 /// instruction is "less" than the second, i.e. its predicate is less than the
10422 /// predicate of the second or the operands IDs are less than the operands IDs
10423 /// of the second cmp instruction.
10424 template <bool IsCompatibility>
10425 static bool compareCmp(Value *V, Value *V2,
10426                        function_ref<bool(Instruction *)> IsDeleted) {
10427   auto *CI1 = cast<CmpInst>(V);
10428   auto *CI2 = cast<CmpInst>(V2);
10429   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10430     return false;
10431   if (CI1->getOperand(0)->getType()->getTypeID() <
10432       CI2->getOperand(0)->getType()->getTypeID())
10433     return !IsCompatibility;
10434   if (CI1->getOperand(0)->getType()->getTypeID() >
10435       CI2->getOperand(0)->getType()->getTypeID())
10436     return false;
10437   CmpInst::Predicate Pred1 = CI1->getPredicate();
10438   CmpInst::Predicate Pred2 = CI2->getPredicate();
10439   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10440   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10441   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10442   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10443   if (BasePred1 < BasePred2)
10444     return !IsCompatibility;
10445   if (BasePred1 > BasePred2)
10446     return false;
10447   // Compare operands.
10448   bool LEPreds = Pred1 <= Pred2;
10449   bool GEPreds = Pred1 >= Pred2;
10450   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10451     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10452     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10453     if (Op1->getValueID() < Op2->getValueID())
10454       return !IsCompatibility;
10455     if (Op1->getValueID() > Op2->getValueID())
10456       return false;
10457     if (auto *I1 = dyn_cast<Instruction>(Op1))
10458       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10459         if (I1->getParent() != I2->getParent())
10460           return false;
10461         InstructionsState S = getSameOpcode({I1, I2});
10462         if (S.getOpcode())
10463           continue;
10464         return false;
10465       }
10466   }
10467   return IsCompatibility;
10468 }
10469 
10470 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10471     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10472     bool AtTerminator) {
10473   bool OpsChanged = false;
10474   SmallVector<Instruction *, 4> PostponedCmps;
10475   for (auto *I : reverse(Instructions)) {
10476     if (R.isDeleted(I))
10477       continue;
10478     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10479       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10480     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10481       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10482     else if (isa<CmpInst>(I))
10483       PostponedCmps.push_back(I);
10484   }
10485   if (AtTerminator) {
10486     // Try to find reductions first.
10487     for (Instruction *I : PostponedCmps) {
10488       if (R.isDeleted(I))
10489         continue;
10490       for (Value *Op : I->operands())
10491         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10492     }
10493     // Try to vectorize operands as vector bundles.
10494     for (Instruction *I : PostponedCmps) {
10495       if (R.isDeleted(I))
10496         continue;
10497       OpsChanged |= tryToVectorize(I, R);
10498     }
10499     // Try to vectorize list of compares.
10500     // Sort by type, compare predicate, etc.
10501     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10502       return compareCmp<false>(V, V2,
10503                                [&R](Instruction *I) { return R.isDeleted(I); });
10504     };
10505 
10506     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10507       if (V1 == V2)
10508         return true;
10509       return compareCmp<true>(V1, V2,
10510                               [&R](Instruction *I) { return R.isDeleted(I); });
10511     };
10512     auto Limit = [&R](Value *V) {
10513       unsigned EltSize = R.getVectorElementSize(V);
10514       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10515     };
10516 
10517     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10518     OpsChanged |= tryToVectorizeSequence<Value>(
10519         Vals, Limit, CompareSorter, AreCompatibleCompares,
10520         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10521           // Exclude possible reductions from other blocks.
10522           bool ArePossiblyReducedInOtherBlock =
10523               any_of(Candidates, [](Value *V) {
10524                 return any_of(V->users(), [V](User *U) {
10525                   return isa<SelectInst>(U) &&
10526                          cast<SelectInst>(U)->getParent() !=
10527                              cast<Instruction>(V)->getParent();
10528                 });
10529               });
10530           if (ArePossiblyReducedInOtherBlock)
10531             return false;
10532           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10533         },
10534         /*LimitForRegisterSize=*/true);
10535     Instructions.clear();
10536   } else {
10537     // Insert in reverse order since the PostponedCmps vector was filled in
10538     // reverse order.
10539     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10540   }
10541   return OpsChanged;
10542 }
10543 
10544 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10545   bool Changed = false;
10546   SmallVector<Value *, 4> Incoming;
10547   SmallPtrSet<Value *, 16> VisitedInstrs;
10548   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10549   // node. Allows better to identify the chains that can be vectorized in the
10550   // better way.
10551   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10552   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10553     assert(isValidElementType(V1->getType()) &&
10554            isValidElementType(V2->getType()) &&
10555            "Expected vectorizable types only.");
10556     // It is fine to compare type IDs here, since we expect only vectorizable
10557     // types, like ints, floats and pointers, we don't care about other type.
10558     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10559       return true;
10560     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10561       return false;
10562     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10563     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10564     if (Opcodes1.size() < Opcodes2.size())
10565       return true;
10566     if (Opcodes1.size() > Opcodes2.size())
10567       return false;
10568     Optional<bool> ConstOrder;
10569     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10570       // Undefs are compatible with any other value.
10571       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10572         if (!ConstOrder)
10573           ConstOrder =
10574               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10575         continue;
10576       }
10577       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10578         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10579           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10580           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10581           if (!NodeI1)
10582             return NodeI2 != nullptr;
10583           if (!NodeI2)
10584             return false;
10585           assert((NodeI1 == NodeI2) ==
10586                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10587                  "Different nodes should have different DFS numbers");
10588           if (NodeI1 != NodeI2)
10589             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10590           InstructionsState S = getSameOpcode({I1, I2});
10591           if (S.getOpcode())
10592             continue;
10593           return I1->getOpcode() < I2->getOpcode();
10594         }
10595       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10596         if (!ConstOrder)
10597           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10598         continue;
10599       }
10600       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10601         return true;
10602       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10603         return false;
10604     }
10605     return ConstOrder && *ConstOrder;
10606   };
10607   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10608     if (V1 == V2)
10609       return true;
10610     if (V1->getType() != V2->getType())
10611       return false;
10612     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10613     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10614     if (Opcodes1.size() != Opcodes2.size())
10615       return false;
10616     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10617       // Undefs are compatible with any other value.
10618       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10619         continue;
10620       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10621         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10622           if (I1->getParent() != I2->getParent())
10623             return false;
10624           InstructionsState S = getSameOpcode({I1, I2});
10625           if (S.getOpcode())
10626             continue;
10627           return false;
10628         }
10629       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10630         continue;
10631       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10632         return false;
10633     }
10634     return true;
10635   };
10636   auto Limit = [&R](Value *V) {
10637     unsigned EltSize = R.getVectorElementSize(V);
10638     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10639   };
10640 
10641   bool HaveVectorizedPhiNodes = false;
10642   do {
10643     // Collect the incoming values from the PHIs.
10644     Incoming.clear();
10645     for (Instruction &I : *BB) {
10646       PHINode *P = dyn_cast<PHINode>(&I);
10647       if (!P)
10648         break;
10649 
10650       // No need to analyze deleted, vectorized and non-vectorizable
10651       // instructions.
10652       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10653           isValidElementType(P->getType()))
10654         Incoming.push_back(P);
10655     }
10656 
10657     // Find the corresponding non-phi nodes for better matching when trying to
10658     // build the tree.
10659     for (Value *V : Incoming) {
10660       SmallVectorImpl<Value *> &Opcodes =
10661           PHIToOpcodes.try_emplace(V).first->getSecond();
10662       if (!Opcodes.empty())
10663         continue;
10664       SmallVector<Value *, 4> Nodes(1, V);
10665       SmallPtrSet<Value *, 4> Visited;
10666       while (!Nodes.empty()) {
10667         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10668         if (!Visited.insert(PHI).second)
10669           continue;
10670         for (Value *V : PHI->incoming_values()) {
10671           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10672             Nodes.push_back(PHI1);
10673             continue;
10674           }
10675           Opcodes.emplace_back(V);
10676         }
10677       }
10678     }
10679 
10680     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10681         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10682         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10683           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10684         },
10685         /*LimitForRegisterSize=*/true);
10686     Changed |= HaveVectorizedPhiNodes;
10687     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10688   } while (HaveVectorizedPhiNodes);
10689 
10690   VisitedInstrs.clear();
10691 
10692   SmallVector<Instruction *, 8> PostProcessInstructions;
10693   SmallDenseSet<Instruction *, 4> KeyNodes;
10694   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10695     // Skip instructions with scalable type. The num of elements is unknown at
10696     // compile-time for scalable type.
10697     if (isa<ScalableVectorType>(it->getType()))
10698       continue;
10699 
10700     // Skip instructions marked for the deletion.
10701     if (R.isDeleted(&*it))
10702       continue;
10703     // We may go through BB multiple times so skip the one we have checked.
10704     if (!VisitedInstrs.insert(&*it).second) {
10705       if (it->use_empty() && KeyNodes.contains(&*it) &&
10706           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10707                                       it->isTerminator())) {
10708         // We would like to start over since some instructions are deleted
10709         // and the iterator may become invalid value.
10710         Changed = true;
10711         it = BB->begin();
10712         e = BB->end();
10713       }
10714       continue;
10715     }
10716 
10717     if (isa<DbgInfoIntrinsic>(it))
10718       continue;
10719 
10720     // Try to vectorize reductions that use PHINodes.
10721     if (PHINode *P = dyn_cast<PHINode>(it)) {
10722       // Check that the PHI is a reduction PHI.
10723       if (P->getNumIncomingValues() == 2) {
10724         // Try to match and vectorize a horizontal reduction.
10725         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10726                                      TTI)) {
10727           Changed = true;
10728           it = BB->begin();
10729           e = BB->end();
10730           continue;
10731         }
10732       }
10733       // Try to vectorize the incoming values of the PHI, to catch reductions
10734       // that feed into PHIs.
10735       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10736         // Skip if the incoming block is the current BB for now. Also, bypass
10737         // unreachable IR for efficiency and to avoid crashing.
10738         // TODO: Collect the skipped incoming values and try to vectorize them
10739         // after processing BB.
10740         if (BB == P->getIncomingBlock(I) ||
10741             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10742           continue;
10743 
10744         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10745                                             P->getIncomingBlock(I), R, TTI);
10746       }
10747       continue;
10748     }
10749 
10750     // Ran into an instruction without users, like terminator, or function call
10751     // with ignored return value, store. Ignore unused instructions (basing on
10752     // instruction type, except for CallInst and InvokeInst).
10753     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10754                             isa<InvokeInst>(it))) {
10755       KeyNodes.insert(&*it);
10756       bool OpsChanged = false;
10757       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10758         for (auto *V : it->operand_values()) {
10759           // Try to match and vectorize a horizontal reduction.
10760           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10761         }
10762       }
10763       // Start vectorization of post-process list of instructions from the
10764       // top-tree instructions to try to vectorize as many instructions as
10765       // possible.
10766       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10767                                                 it->isTerminator());
10768       if (OpsChanged) {
10769         // We would like to start over since some instructions are deleted
10770         // and the iterator may become invalid value.
10771         Changed = true;
10772         it = BB->begin();
10773         e = BB->end();
10774         continue;
10775       }
10776     }
10777 
10778     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10779         isa<InsertValueInst>(it))
10780       PostProcessInstructions.push_back(&*it);
10781   }
10782 
10783   return Changed;
10784 }
10785 
10786 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10787   auto Changed = false;
10788   for (auto &Entry : GEPs) {
10789     // If the getelementptr list has fewer than two elements, there's nothing
10790     // to do.
10791     if (Entry.second.size() < 2)
10792       continue;
10793 
10794     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10795                       << Entry.second.size() << ".\n");
10796 
10797     // Process the GEP list in chunks suitable for the target's supported
10798     // vector size. If a vector register can't hold 1 element, we are done. We
10799     // are trying to vectorize the index computations, so the maximum number of
10800     // elements is based on the size of the index expression, rather than the
10801     // size of the GEP itself (the target's pointer size).
10802     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10803     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10804     if (MaxVecRegSize < EltSize)
10805       continue;
10806 
10807     unsigned MaxElts = MaxVecRegSize / EltSize;
10808     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10809       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10810       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10811 
10812       // Initialize a set a candidate getelementptrs. Note that we use a
10813       // SetVector here to preserve program order. If the index computations
10814       // are vectorizable and begin with loads, we want to minimize the chance
10815       // of having to reorder them later.
10816       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10817 
10818       // Some of the candidates may have already been vectorized after we
10819       // initially collected them. If so, they are marked as deleted, so remove
10820       // them from the set of candidates.
10821       Candidates.remove_if(
10822           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10823 
10824       // Remove from the set of candidates all pairs of getelementptrs with
10825       // constant differences. Such getelementptrs are likely not good
10826       // candidates for vectorization in a bottom-up phase since one can be
10827       // computed from the other. We also ensure all candidate getelementptr
10828       // indices are unique.
10829       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10830         auto *GEPI = GEPList[I];
10831         if (!Candidates.count(GEPI))
10832           continue;
10833         auto *SCEVI = SE->getSCEV(GEPList[I]);
10834         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10835           auto *GEPJ = GEPList[J];
10836           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10837           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10838             Candidates.remove(GEPI);
10839             Candidates.remove(GEPJ);
10840           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10841             Candidates.remove(GEPJ);
10842           }
10843         }
10844       }
10845 
10846       // We break out of the above computation as soon as we know there are
10847       // fewer than two candidates remaining.
10848       if (Candidates.size() < 2)
10849         continue;
10850 
10851       // Add the single, non-constant index of each candidate to the bundle. We
10852       // ensured the indices met these constraints when we originally collected
10853       // the getelementptrs.
10854       SmallVector<Value *, 16> Bundle(Candidates.size());
10855       auto BundleIndex = 0u;
10856       for (auto *V : Candidates) {
10857         auto *GEP = cast<GetElementPtrInst>(V);
10858         auto *GEPIdx = GEP->idx_begin()->get();
10859         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10860         Bundle[BundleIndex++] = GEPIdx;
10861       }
10862 
10863       // Try and vectorize the indices. We are currently only interested in
10864       // gather-like cases of the form:
10865       //
10866       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10867       //
10868       // where the loads of "a", the loads of "b", and the subtractions can be
10869       // performed in parallel. It's likely that detecting this pattern in a
10870       // bottom-up phase will be simpler and less costly than building a
10871       // full-blown top-down phase beginning at the consecutive loads.
10872       Changed |= tryToVectorizeList(Bundle, R);
10873     }
10874   }
10875   return Changed;
10876 }
10877 
10878 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10879   bool Changed = false;
10880   // Sort by type, base pointers and values operand. Value operands must be
10881   // compatible (have the same opcode, same parent), otherwise it is
10882   // definitely not profitable to try to vectorize them.
10883   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10884     if (V->getPointerOperandType()->getTypeID() <
10885         V2->getPointerOperandType()->getTypeID())
10886       return true;
10887     if (V->getPointerOperandType()->getTypeID() >
10888         V2->getPointerOperandType()->getTypeID())
10889       return false;
10890     // UndefValues are compatible with all other values.
10891     if (isa<UndefValue>(V->getValueOperand()) ||
10892         isa<UndefValue>(V2->getValueOperand()))
10893       return false;
10894     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10895       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10896         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10897             DT->getNode(I1->getParent());
10898         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10899             DT->getNode(I2->getParent());
10900         assert(NodeI1 && "Should only process reachable instructions");
10901         assert(NodeI1 && "Should only process reachable instructions");
10902         assert((NodeI1 == NodeI2) ==
10903                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10904                "Different nodes should have different DFS numbers");
10905         if (NodeI1 != NodeI2)
10906           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10907         InstructionsState S = getSameOpcode({I1, I2});
10908         if (S.getOpcode())
10909           return false;
10910         return I1->getOpcode() < I2->getOpcode();
10911       }
10912     if (isa<Constant>(V->getValueOperand()) &&
10913         isa<Constant>(V2->getValueOperand()))
10914       return false;
10915     return V->getValueOperand()->getValueID() <
10916            V2->getValueOperand()->getValueID();
10917   };
10918 
10919   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10920     if (V1 == V2)
10921       return true;
10922     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10923       return false;
10924     // Undefs are compatible with any other value.
10925     if (isa<UndefValue>(V1->getValueOperand()) ||
10926         isa<UndefValue>(V2->getValueOperand()))
10927       return true;
10928     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10929       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10930         if (I1->getParent() != I2->getParent())
10931           return false;
10932         InstructionsState S = getSameOpcode({I1, I2});
10933         return S.getOpcode() > 0;
10934       }
10935     if (isa<Constant>(V1->getValueOperand()) &&
10936         isa<Constant>(V2->getValueOperand()))
10937       return true;
10938     return V1->getValueOperand()->getValueID() ==
10939            V2->getValueOperand()->getValueID();
10940   };
10941   auto Limit = [&R, this](StoreInst *SI) {
10942     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10943     return R.getMinVF(EltSize);
10944   };
10945 
10946   // Attempt to sort and vectorize each of the store-groups.
10947   for (auto &Pair : Stores) {
10948     if (Pair.second.size() < 2)
10949       continue;
10950 
10951     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10952                       << Pair.second.size() << ".\n");
10953 
10954     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10955       continue;
10956 
10957     Changed |= tryToVectorizeSequence<StoreInst>(
10958         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10959         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10960           return vectorizeStores(Candidates, R);
10961         },
10962         /*LimitForRegisterSize=*/false);
10963   }
10964   return Changed;
10965 }
10966 
10967 char SLPVectorizer::ID = 0;
10968 
10969 static const char lv_name[] = "SLP Vectorizer";
10970 
10971 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10972 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10973 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10974 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10975 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10976 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10977 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10978 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10979 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10980 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10981 
10982 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10983