1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(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   /// Sort loads into increasing pointers offsets to allow greater clustering.
933   Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
934 
935   /// Gets reordering data for the given tree entry. If the entry is vectorized
936   /// - just return ReorderIndices, otherwise check if the scalars can be
937   /// reordered and return the most optimal order.
938   /// \param TopToBottom If true, include the order of vectorized stores and
939   /// insertelement nodes, otherwise skip them.
940   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
941 
942   /// Reorders the current graph to the most profitable order starting from the
943   /// root node to the leaf nodes. The best order is chosen only from the nodes
944   /// of the same size (vectorization factor). Smaller nodes are considered
945   /// parts of subgraph with smaller VF and they are reordered independently. We
946   /// can make it because we still need to extend smaller nodes to the wider VF
947   /// and we can merge reordering shuffles with the widening shuffles.
948   void reorderTopToBottom();
949 
950   /// Reorders the current graph to the most profitable order starting from
951   /// leaves to the root. It allows to rotate small subgraphs and reduce the
952   /// number of reshuffles if the leaf nodes use the same order. In this case we
953   /// can merge the orders and just shuffle user node instead of shuffling its
954   /// operands. Plus, even the leaf nodes have different orders, it allows to
955   /// sink reordering in the graph closer to the root node and merge it later
956   /// during analysis.
957   void reorderBottomToTop(bool IgnoreReorder = false);
958 
959   /// \return The vector element size in bits to use when vectorizing the
960   /// expression tree ending at \p V. If V is a store, the size is the width of
961   /// the stored value. Otherwise, the size is the width of the largest loaded
962   /// value reaching V. This method is used by the vectorizer to calculate
963   /// vectorization factors.
964   unsigned getVectorElementSize(Value *V);
965 
966   /// Compute the minimum type sizes required to represent the entries in a
967   /// vectorizable tree.
968   void computeMinimumValueSizes();
969 
970   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
971   unsigned getMaxVecRegSize() const {
972     return MaxVecRegSize;
973   }
974 
975   // \returns minimum vector register size as set by cl::opt.
976   unsigned getMinVecRegSize() const {
977     return MinVecRegSize;
978   }
979 
980   unsigned getMinVF(unsigned Sz) const {
981     return std::max(2U, getMinVecRegSize() / Sz);
982   }
983 
984   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
985     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
986       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
987     return MaxVF ? MaxVF : UINT_MAX;
988   }
989 
990   /// Check if homogeneous aggregate is isomorphic to some VectorType.
991   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
992   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
993   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
994   ///
995   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
996   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
997 
998   /// \returns True if the VectorizableTree is both tiny and not fully
999   /// vectorizable. We do not vectorize such trees.
1000   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1001 
1002   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1003   /// can be load combined in the backend. Load combining may not be allowed in
1004   /// the IR optimizer, so we do not want to alter the pattern. For example,
1005   /// partially transforming a scalar bswap() pattern into vector code is
1006   /// effectively impossible for the backend to undo.
1007   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1008   ///       may not be necessary.
1009   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1010 
1011   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1012   /// can be load combined in the backend. Load combining may not be allowed in
1013   /// the IR optimizer, so we do not want to alter the pattern. For example,
1014   /// partially transforming a scalar bswap() pattern into vector code is
1015   /// effectively impossible for the backend to undo.
1016   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1017   ///       may not be necessary.
1018   bool isLoadCombineCandidate() const;
1019 
1020   OptimizationRemarkEmitter *getORE() { return ORE; }
1021 
1022   /// This structure holds any data we need about the edges being traversed
1023   /// during buildTree_rec(). We keep track of:
1024   /// (i) the user TreeEntry index, and
1025   /// (ii) the index of the edge.
1026   struct EdgeInfo {
1027     EdgeInfo() = default;
1028     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1029         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1030     /// The user TreeEntry.
1031     TreeEntry *UserTE = nullptr;
1032     /// The operand index of the use.
1033     unsigned EdgeIdx = UINT_MAX;
1034 #ifndef NDEBUG
1035     friend inline raw_ostream &operator<<(raw_ostream &OS,
1036                                           const BoUpSLP::EdgeInfo &EI) {
1037       EI.dump(OS);
1038       return OS;
1039     }
1040     /// Debug print.
1041     void dump(raw_ostream &OS) const {
1042       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1043          << " EdgeIdx:" << EdgeIdx << "}";
1044     }
1045     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1046 #endif
1047   };
1048 
1049   /// A helper class used for scoring candidates for two consecutive lanes.
1050   class LookAheadHeuristics {
1051     const DataLayout &DL;
1052     ScalarEvolution &SE;
1053     const BoUpSLP &R;
1054     int NumLanes; // Total number of lanes (aka vectorization factor).
1055     int MaxLevel; // The maximum recursion depth for accumulating score.
1056 
1057   public:
1058     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1059                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1060         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1061 
1062     // The hard-coded scores listed here are not very important, though it shall
1063     // be higher for better matches to improve the resulting cost. When
1064     // computing the scores of matching one sub-tree with another, we are
1065     // basically counting the number of values that are matching. So even if all
1066     // scores are set to 1, we would still get a decent matching result.
1067     // However, sometimes we have to break ties. For example we may have to
1068     // choose between matching loads vs matching opcodes. This is what these
1069     // scores are helping us with: they provide the order of preference. Also,
1070     // this is important if the scalar is externally used or used in another
1071     // tree entry node in the different lane.
1072 
1073     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1074     static const int ScoreConsecutiveLoads = 4;
1075     /// The same load multiple times. This should have a better score than
1076     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1077     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1078     /// a vector load and 1.0 for a broadcast.
1079     static const int ScoreSplatLoads = 3;
1080     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1081     static const int ScoreReversedLoads = 3;
1082     /// ExtractElementInst from same vector and consecutive indexes.
1083     static const int ScoreConsecutiveExtracts = 4;
1084     /// ExtractElementInst from same vector and reversed indices.
1085     static const int ScoreReversedExtracts = 3;
1086     /// Constants.
1087     static const int ScoreConstants = 2;
1088     /// Instructions with the same opcode.
1089     static const int ScoreSameOpcode = 2;
1090     /// Instructions with alt opcodes (e.g, add + sub).
1091     static const int ScoreAltOpcodes = 1;
1092     /// Identical instructions (a.k.a. splat or broadcast).
1093     static const int ScoreSplat = 1;
1094     /// Matching with an undef is preferable to failing.
1095     static const int ScoreUndef = 1;
1096     /// Score for failing to find a decent match.
1097     static const int ScoreFail = 0;
1098     /// Score if all users are vectorized.
1099     static const int ScoreAllUserVectorized = 1;
1100 
1101     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1102     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1103     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1104     /// MainAltOps.
1105     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1106                         ArrayRef<Value *> MainAltOps) const {
1107       if (V1 == V2) {
1108         if (isa<LoadInst>(V1)) {
1109           // Retruns true if the users of V1 and V2 won't need to be extracted.
1110           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1111             // Bail out if we have too many uses to save compilation time.
1112             static constexpr unsigned Limit = 8;
1113             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1114               return false;
1115 
1116             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1117               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1118                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1119               });
1120             };
1121             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1122           };
1123           // A broadcast of a load can be cheaper on some targets.
1124           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1125                                           ElementCount::getFixed(NumLanes)) &&
1126               ((int)V1->getNumUses() == NumLanes ||
1127                AllUsersAreInternal(V1, V2)))
1128             return LookAheadHeuristics::ScoreSplatLoads;
1129         }
1130         return LookAheadHeuristics::ScoreSplat;
1131       }
1132 
1133       auto *LI1 = dyn_cast<LoadInst>(V1);
1134       auto *LI2 = dyn_cast<LoadInst>(V2);
1135       if (LI1 && LI2) {
1136         if (LI1->getParent() != LI2->getParent())
1137           return LookAheadHeuristics::ScoreFail;
1138 
1139         Optional<int> Dist = getPointersDiff(
1140             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1141             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1142         if (!Dist || *Dist == 0)
1143           return LookAheadHeuristics::ScoreFail;
1144         // The distance is too large - still may be profitable to use masked
1145         // loads/gathers.
1146         if (std::abs(*Dist) > NumLanes / 2)
1147           return LookAheadHeuristics::ScoreAltOpcodes;
1148         // This still will detect consecutive loads, but we might have "holes"
1149         // in some cases. It is ok for non-power-2 vectorization and may produce
1150         // better results. It should not affect current vectorization.
1151         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1152                            : LookAheadHeuristics::ScoreReversedLoads;
1153       }
1154 
1155       auto *C1 = dyn_cast<Constant>(V1);
1156       auto *C2 = dyn_cast<Constant>(V2);
1157       if (C1 && C2)
1158         return LookAheadHeuristics::ScoreConstants;
1159 
1160       // Extracts from consecutive indexes of the same vector better score as
1161       // the extracts could be optimized away.
1162       Value *EV1;
1163       ConstantInt *Ex1Idx;
1164       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1165         // Undefs are always profitable for extractelements.
1166         if (isa<UndefValue>(V2))
1167           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1168         Value *EV2 = nullptr;
1169         ConstantInt *Ex2Idx = nullptr;
1170         if (match(V2,
1171                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1172                                                          m_Undef())))) {
1173           // Undefs are always profitable for extractelements.
1174           if (!Ex2Idx)
1175             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1176           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1177             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1178           if (EV2 == EV1) {
1179             int Idx1 = Ex1Idx->getZExtValue();
1180             int Idx2 = Ex2Idx->getZExtValue();
1181             int Dist = Idx2 - Idx1;
1182             // The distance is too large - still may be profitable to use
1183             // shuffles.
1184             if (std::abs(Dist) == 0)
1185               return LookAheadHeuristics::ScoreSplat;
1186             if (std::abs(Dist) > NumLanes / 2)
1187               return LookAheadHeuristics::ScoreSameOpcode;
1188             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1189                               : LookAheadHeuristics::ScoreReversedExtracts;
1190           }
1191           return LookAheadHeuristics::ScoreAltOpcodes;
1192         }
1193         return LookAheadHeuristics::ScoreFail;
1194       }
1195 
1196       auto *I1 = dyn_cast<Instruction>(V1);
1197       auto *I2 = dyn_cast<Instruction>(V2);
1198       if (I1 && I2) {
1199         if (I1->getParent() != I2->getParent())
1200           return LookAheadHeuristics::ScoreFail;
1201         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1202         Ops.push_back(I1);
1203         Ops.push_back(I2);
1204         InstructionsState S = getSameOpcode(Ops);
1205         // Note: Only consider instructions with <= 2 operands to avoid
1206         // complexity explosion.
1207         if (S.getOpcode() &&
1208             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1209              !S.isAltShuffle()) &&
1210             all_of(Ops, [&S](Value *V) {
1211               return cast<Instruction>(V)->getNumOperands() ==
1212                      S.MainOp->getNumOperands();
1213             }))
1214           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1215                                   : LookAheadHeuristics::ScoreSameOpcode;
1216       }
1217 
1218       if (isa<UndefValue>(V2))
1219         return LookAheadHeuristics::ScoreUndef;
1220 
1221       return LookAheadHeuristics::ScoreFail;
1222     }
1223 
1224     /// Go through the operands of \p LHS and \p RHS recursively until
1225     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1226     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1227     /// of \p U1 and \p U2), except at the beginning of the recursion where
1228     /// these are set to nullptr.
1229     ///
1230     /// For example:
1231     /// \verbatim
1232     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1233     ///     \ /         \ /         \ /        \ /
1234     ///      +           +           +          +
1235     ///     G1          G2          G3         G4
1236     /// \endverbatim
1237     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1238     /// each level recursively, accumulating the score. It starts from matching
1239     /// the additions at level 0, then moves on to the loads (level 1). The
1240     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1241     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1242     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1243     /// Please note that the order of the operands does not matter, as we
1244     /// evaluate the score of all profitable combinations of operands. In
1245     /// other words the score of G1 and G4 is the same as G1 and G2. This
1246     /// heuristic is based on ideas described in:
1247     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1248     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1249     ///   Luís F. W. Góes
1250     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1251                            Instruction *U2, int CurrLevel,
1252                            ArrayRef<Value *> MainAltOps) const {
1253 
1254       // Get the shallow score of V1 and V2.
1255       int ShallowScoreAtThisLevel =
1256           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1257 
1258       // If reached MaxLevel,
1259       //  or if V1 and V2 are not instructions,
1260       //  or if they are SPLAT,
1261       //  or if they are not consecutive,
1262       //  or if profitable to vectorize loads or extractelements, early return
1263       //  the current cost.
1264       auto *I1 = dyn_cast<Instruction>(LHS);
1265       auto *I2 = dyn_cast<Instruction>(RHS);
1266       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1267           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1268           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1269             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1270             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1271            ShallowScoreAtThisLevel))
1272         return ShallowScoreAtThisLevel;
1273       assert(I1 && I2 && "Should have early exited.");
1274 
1275       // Contains the I2 operand indexes that got matched with I1 operands.
1276       SmallSet<unsigned, 4> Op2Used;
1277 
1278       // Recursion towards the operands of I1 and I2. We are trying all possible
1279       // operand pairs, and keeping track of the best score.
1280       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1281            OpIdx1 != NumOperands1; ++OpIdx1) {
1282         // Try to pair op1I with the best operand of I2.
1283         int MaxTmpScore = 0;
1284         unsigned MaxOpIdx2 = 0;
1285         bool FoundBest = false;
1286         // If I2 is commutative try all combinations.
1287         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1288         unsigned ToIdx = isCommutative(I2)
1289                              ? I2->getNumOperands()
1290                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1291         assert(FromIdx <= ToIdx && "Bad index");
1292         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1293           // Skip operands already paired with OpIdx1.
1294           if (Op2Used.count(OpIdx2))
1295             continue;
1296           // Recursively calculate the cost at each level
1297           int TmpScore =
1298               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1299                                  I1, I2, CurrLevel + 1, None);
1300           // Look for the best score.
1301           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1302               TmpScore > MaxTmpScore) {
1303             MaxTmpScore = TmpScore;
1304             MaxOpIdx2 = OpIdx2;
1305             FoundBest = true;
1306           }
1307         }
1308         if (FoundBest) {
1309           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1310           Op2Used.insert(MaxOpIdx2);
1311           ShallowScoreAtThisLevel += MaxTmpScore;
1312         }
1313       }
1314       return ShallowScoreAtThisLevel;
1315     }
1316   };
1317   /// A helper data structure to hold the operands of a vector of instructions.
1318   /// This supports a fixed vector length for all operand vectors.
1319   class VLOperands {
1320     /// For each operand we need (i) the value, and (ii) the opcode that it
1321     /// would be attached to if the expression was in a left-linearized form.
1322     /// This is required to avoid illegal operand reordering.
1323     /// For example:
1324     /// \verbatim
1325     ///                         0 Op1
1326     ///                         |/
1327     /// Op1 Op2   Linearized    + Op2
1328     ///   \ /     ---------->   |/
1329     ///    -                    -
1330     ///
1331     /// Op1 - Op2            (0 + Op1) - Op2
1332     /// \endverbatim
1333     ///
1334     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1335     ///
1336     /// Another way to think of this is to track all the operations across the
1337     /// path from the operand all the way to the root of the tree and to
1338     /// calculate the operation that corresponds to this path. For example, the
1339     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1340     /// corresponding operation is a '-' (which matches the one in the
1341     /// linearized tree, as shown above).
1342     ///
1343     /// For lack of a better term, we refer to this operation as Accumulated
1344     /// Path Operation (APO).
1345     struct OperandData {
1346       OperandData() = default;
1347       OperandData(Value *V, bool APO, bool IsUsed)
1348           : V(V), APO(APO), IsUsed(IsUsed) {}
1349       /// The operand value.
1350       Value *V = nullptr;
1351       /// TreeEntries only allow a single opcode, or an alternate sequence of
1352       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1353       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1354       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1355       /// (e.g., Add/Mul)
1356       bool APO = false;
1357       /// Helper data for the reordering function.
1358       bool IsUsed = false;
1359     };
1360 
1361     /// During operand reordering, we are trying to select the operand at lane
1362     /// that matches best with the operand at the neighboring lane. Our
1363     /// selection is based on the type of value we are looking for. For example,
1364     /// if the neighboring lane has a load, we need to look for a load that is
1365     /// accessing a consecutive address. These strategies are summarized in the
1366     /// 'ReorderingMode' enumerator.
1367     enum class ReorderingMode {
1368       Load,     ///< Matching loads to consecutive memory addresses
1369       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1370       Constant, ///< Matching constants
1371       Splat,    ///< Matching the same instruction multiple times (broadcast)
1372       Failed,   ///< We failed to create a vectorizable group
1373     };
1374 
1375     using OperandDataVec = SmallVector<OperandData, 2>;
1376 
1377     /// A vector of operand vectors.
1378     SmallVector<OperandDataVec, 4> OpsVec;
1379 
1380     const DataLayout &DL;
1381     ScalarEvolution &SE;
1382     const BoUpSLP &R;
1383 
1384     /// \returns the operand data at \p OpIdx and \p Lane.
1385     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1386       return OpsVec[OpIdx][Lane];
1387     }
1388 
1389     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1390     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1391       return OpsVec[OpIdx][Lane];
1392     }
1393 
1394     /// Clears the used flag for all entries.
1395     void clearUsed() {
1396       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1397            OpIdx != NumOperands; ++OpIdx)
1398         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1399              ++Lane)
1400           OpsVec[OpIdx][Lane].IsUsed = false;
1401     }
1402 
1403     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1404     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1405       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1406     }
1407 
1408     /// \param Lane lane of the operands under analysis.
1409     /// \param OpIdx operand index in \p Lane lane we're looking the best
1410     /// candidate for.
1411     /// \param Idx operand index of the current candidate value.
1412     /// \returns The additional score due to possible broadcasting of the
1413     /// elements in the lane. It is more profitable to have power-of-2 unique
1414     /// elements in the lane, it will be vectorized with higher probability
1415     /// after removing duplicates. Currently the SLP vectorizer supports only
1416     /// vectorization of the power-of-2 number of unique scalars.
1417     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1418       Value *IdxLaneV = getData(Idx, Lane).V;
1419       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1420         return 0;
1421       SmallPtrSet<Value *, 4> Uniques;
1422       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1423         if (Ln == Lane)
1424           continue;
1425         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1426         if (!isa<Instruction>(OpIdxLnV))
1427           return 0;
1428         Uniques.insert(OpIdxLnV);
1429       }
1430       int UniquesCount = Uniques.size();
1431       int UniquesCntWithIdxLaneV =
1432           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1434       int UniquesCntWithOpIdxLaneV =
1435           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1436       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1437         return 0;
1438       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1439               UniquesCntWithOpIdxLaneV) -
1440              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1441     }
1442 
1443     /// \param Lane lane of the operands under analysis.
1444     /// \param OpIdx operand index in \p Lane lane we're looking the best
1445     /// candidate for.
1446     /// \param Idx operand index of the current candidate value.
1447     /// \returns The additional score for the scalar which users are all
1448     /// vectorized.
1449     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1450       Value *IdxLaneV = getData(Idx, Lane).V;
1451       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1452       // Do not care about number of uses for vector-like instructions
1453       // (extractelement/extractvalue with constant indices), they are extracts
1454       // themselves and already externally used. Vectorization of such
1455       // instructions does not add extra extractelement instruction, just may
1456       // remove it.
1457       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1458           isVectorLikeInstWithConstOps(OpIdxLaneV))
1459         return LookAheadHeuristics::ScoreAllUserVectorized;
1460       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1461       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1462         return 0;
1463       return R.areAllUsersVectorized(IdxLaneI, None)
1464                  ? LookAheadHeuristics::ScoreAllUserVectorized
1465                  : 0;
1466     }
1467 
1468     /// Score scaling factor for fully compatible instructions but with
1469     /// different number of external uses. Allows better selection of the
1470     /// instructions with less external uses.
1471     static const int ScoreScaleFactor = 10;
1472 
1473     /// \Returns the look-ahead score, which tells us how much the sub-trees
1474     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1475     /// score. This helps break ties in an informed way when we cannot decide on
1476     /// the order of the operands by just considering the immediate
1477     /// predecessors.
1478     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1479                           int Lane, unsigned OpIdx, unsigned Idx,
1480                           bool &IsUsed) {
1481       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1482                                     LookAheadMaxDepth);
1483       // Keep track of the instruction stack as we recurse into the operands
1484       // during the look-ahead score exploration.
1485       int Score =
1486           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1487                                        /*CurrLevel=*/1, MainAltOps);
1488       if (Score) {
1489         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1490         if (Score <= -SplatScore) {
1491           // Set the minimum score for splat-like sequence to avoid setting
1492           // failed state.
1493           Score = 1;
1494         } else {
1495           Score += SplatScore;
1496           // Scale score to see the difference between different operands
1497           // and similar operands but all vectorized/not all vectorized
1498           // uses. It does not affect actual selection of the best
1499           // compatible operand in general, just allows to select the
1500           // operand with all vectorized uses.
1501           Score *= ScoreScaleFactor;
1502           Score += getExternalUseScore(Lane, OpIdx, Idx);
1503           IsUsed = true;
1504         }
1505       }
1506       return Score;
1507     }
1508 
1509     /// Best defined scores per lanes between the passes. Used to choose the
1510     /// best operand (with the highest score) between the passes.
1511     /// The key - {Operand Index, Lane}.
1512     /// The value - the best score between the passes for the lane and the
1513     /// operand.
1514     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1515         BestScoresPerLanes;
1516 
1517     // Search all operands in Ops[*][Lane] for the one that matches best
1518     // Ops[OpIdx][LastLane] and return its opreand index.
1519     // If no good match can be found, return None.
1520     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1521                                       ArrayRef<ReorderingMode> ReorderingModes,
1522                                       ArrayRef<Value *> MainAltOps) {
1523       unsigned NumOperands = getNumOperands();
1524 
1525       // The operand of the previous lane at OpIdx.
1526       Value *OpLastLane = getData(OpIdx, LastLane).V;
1527 
1528       // Our strategy mode for OpIdx.
1529       ReorderingMode RMode = ReorderingModes[OpIdx];
1530       if (RMode == ReorderingMode::Failed)
1531         return None;
1532 
1533       // The linearized opcode of the operand at OpIdx, Lane.
1534       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1535 
1536       // The best operand index and its score.
1537       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1538       // are using the score to differentiate between the two.
1539       struct BestOpData {
1540         Optional<unsigned> Idx = None;
1541         unsigned Score = 0;
1542       } BestOp;
1543       BestOp.Score =
1544           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1545               .first->second;
1546 
1547       // Track if the operand must be marked as used. If the operand is set to
1548       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1549       // want to reestimate the operands again on the following iterations).
1550       bool IsUsed =
1551           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1552       // Iterate through all unused operands and look for the best.
1553       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1554         // Get the operand at Idx and Lane.
1555         OperandData &OpData = getData(Idx, Lane);
1556         Value *Op = OpData.V;
1557         bool OpAPO = OpData.APO;
1558 
1559         // Skip already selected operands.
1560         if (OpData.IsUsed)
1561           continue;
1562 
1563         // Skip if we are trying to move the operand to a position with a
1564         // different opcode in the linearized tree form. This would break the
1565         // semantics.
1566         if (OpAPO != OpIdxAPO)
1567           continue;
1568 
1569         // Look for an operand that matches the current mode.
1570         switch (RMode) {
1571         case ReorderingMode::Load:
1572         case ReorderingMode::Constant:
1573         case ReorderingMode::Opcode: {
1574           bool LeftToRight = Lane > LastLane;
1575           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1576           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1577           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1578                                         OpIdx, Idx, IsUsed);
1579           if (Score > static_cast<int>(BestOp.Score)) {
1580             BestOp.Idx = Idx;
1581             BestOp.Score = Score;
1582             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1583           }
1584           break;
1585         }
1586         case ReorderingMode::Splat:
1587           if (Op == OpLastLane)
1588             BestOp.Idx = Idx;
1589           break;
1590         case ReorderingMode::Failed:
1591           llvm_unreachable("Not expected Failed reordering mode.");
1592         }
1593       }
1594 
1595       if (BestOp.Idx) {
1596         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1597         return BestOp.Idx;
1598       }
1599       // If we could not find a good match return None.
1600       return None;
1601     }
1602 
1603     /// Helper for reorderOperandVecs.
1604     /// \returns the lane that we should start reordering from. This is the one
1605     /// which has the least number of operands that can freely move about or
1606     /// less profitable because it already has the most optimal set of operands.
1607     unsigned getBestLaneToStartReordering() const {
1608       unsigned Min = UINT_MAX;
1609       unsigned SameOpNumber = 0;
1610       // std::pair<unsigned, unsigned> is used to implement a simple voting
1611       // algorithm and choose the lane with the least number of operands that
1612       // can freely move about or less profitable because it already has the
1613       // most optimal set of operands. The first unsigned is a counter for
1614       // voting, the second unsigned is the counter of lanes with instructions
1615       // with same/alternate opcodes and same parent basic block.
1616       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1617       // Try to be closer to the original results, if we have multiple lanes
1618       // with same cost. If 2 lanes have the same cost, use the one with the
1619       // lowest index.
1620       for (int I = getNumLanes(); I > 0; --I) {
1621         unsigned Lane = I - 1;
1622         OperandsOrderData NumFreeOpsHash =
1623             getMaxNumOperandsThatCanBeReordered(Lane);
1624         // Compare the number of operands that can move and choose the one with
1625         // the least number.
1626         if (NumFreeOpsHash.NumOfAPOs < Min) {
1627           Min = NumFreeOpsHash.NumOfAPOs;
1628           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1629           HashMap.clear();
1630           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1631         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1632                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1633           // Select the most optimal lane in terms of number of operands that
1634           // should be moved around.
1635           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1636           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1637         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1638                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1639           auto It = HashMap.find(NumFreeOpsHash.Hash);
1640           if (It == HashMap.end())
1641             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1642           else
1643             ++It->second.first;
1644         }
1645       }
1646       // Select the lane with the minimum counter.
1647       unsigned BestLane = 0;
1648       unsigned CntMin = UINT_MAX;
1649       for (const auto &Data : reverse(HashMap)) {
1650         if (Data.second.first < CntMin) {
1651           CntMin = Data.second.first;
1652           BestLane = Data.second.second;
1653         }
1654       }
1655       return BestLane;
1656     }
1657 
1658     /// Data structure that helps to reorder operands.
1659     struct OperandsOrderData {
1660       /// The best number of operands with the same APOs, which can be
1661       /// reordered.
1662       unsigned NumOfAPOs = UINT_MAX;
1663       /// Number of operands with the same/alternate instruction opcode and
1664       /// parent.
1665       unsigned NumOpsWithSameOpcodeParent = 0;
1666       /// Hash for the actual operands ordering.
1667       /// Used to count operands, actually their position id and opcode
1668       /// value. It is used in the voting mechanism to find the lane with the
1669       /// least number of operands that can freely move about or less profitable
1670       /// because it already has the most optimal set of operands. Can be
1671       /// replaced with SmallVector<unsigned> instead but hash code is faster
1672       /// and requires less memory.
1673       unsigned Hash = 0;
1674     };
1675     /// \returns the maximum number of operands that are allowed to be reordered
1676     /// for \p Lane and the number of compatible instructions(with the same
1677     /// parent/opcode). This is used as a heuristic for selecting the first lane
1678     /// to start operand reordering.
1679     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1680       unsigned CntTrue = 0;
1681       unsigned NumOperands = getNumOperands();
1682       // Operands with the same APO can be reordered. We therefore need to count
1683       // how many of them we have for each APO, like this: Cnt[APO] = x.
1684       // Since we only have two APOs, namely true and false, we can avoid using
1685       // a map. Instead we can simply count the number of operands that
1686       // correspond to one of them (in this case the 'true' APO), and calculate
1687       // the other by subtracting it from the total number of operands.
1688       // Operands with the same instruction opcode and parent are more
1689       // profitable since we don't need to move them in many cases, with a high
1690       // probability such lane already can be vectorized effectively.
1691       bool AllUndefs = true;
1692       unsigned NumOpsWithSameOpcodeParent = 0;
1693       Instruction *OpcodeI = nullptr;
1694       BasicBlock *Parent = nullptr;
1695       unsigned Hash = 0;
1696       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1697         const OperandData &OpData = getData(OpIdx, Lane);
1698         if (OpData.APO)
1699           ++CntTrue;
1700         // Use Boyer-Moore majority voting for finding the majority opcode and
1701         // the number of times it occurs.
1702         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1703           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1704               I->getParent() != Parent) {
1705             if (NumOpsWithSameOpcodeParent == 0) {
1706               NumOpsWithSameOpcodeParent = 1;
1707               OpcodeI = I;
1708               Parent = I->getParent();
1709             } else {
1710               --NumOpsWithSameOpcodeParent;
1711             }
1712           } else {
1713             ++NumOpsWithSameOpcodeParent;
1714           }
1715         }
1716         Hash = hash_combine(
1717             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1718         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1719       }
1720       if (AllUndefs)
1721         return {};
1722       OperandsOrderData Data;
1723       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1724       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1725       Data.Hash = Hash;
1726       return Data;
1727     }
1728 
1729     /// Go through the instructions in VL and append their operands.
1730     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1731       assert(!VL.empty() && "Bad VL");
1732       assert((empty() || VL.size() == getNumLanes()) &&
1733              "Expected same number of lanes");
1734       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1735       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1736       OpsVec.resize(NumOperands);
1737       unsigned NumLanes = VL.size();
1738       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1739         OpsVec[OpIdx].resize(NumLanes);
1740         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1741           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1742           // Our tree has just 3 nodes: the root and two operands.
1743           // It is therefore trivial to get the APO. We only need to check the
1744           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1745           // RHS operand. The LHS operand of both add and sub is never attached
1746           // to an inversese operation in the linearized form, therefore its APO
1747           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1748 
1749           // Since operand reordering is performed on groups of commutative
1750           // operations or alternating sequences (e.g., +, -), we can safely
1751           // tell the inverse operations by checking commutativity.
1752           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1753           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1754           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1755                                  APO, false};
1756         }
1757       }
1758     }
1759 
1760     /// \returns the number of operands.
1761     unsigned getNumOperands() const { return OpsVec.size(); }
1762 
1763     /// \returns the number of lanes.
1764     unsigned getNumLanes() const { return OpsVec[0].size(); }
1765 
1766     /// \returns the operand value at \p OpIdx and \p Lane.
1767     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1768       return getData(OpIdx, Lane).V;
1769     }
1770 
1771     /// \returns true if the data structure is empty.
1772     bool empty() const { return OpsVec.empty(); }
1773 
1774     /// Clears the data.
1775     void clear() { OpsVec.clear(); }
1776 
1777     /// \Returns true if there are enough operands identical to \p Op to fill
1778     /// the whole vector.
1779     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1780     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1781       bool OpAPO = getData(OpIdx, Lane).APO;
1782       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1783         if (Ln == Lane)
1784           continue;
1785         // This is set to true if we found a candidate for broadcast at Lane.
1786         bool FoundCandidate = false;
1787         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1788           OperandData &Data = getData(OpI, Ln);
1789           if (Data.APO != OpAPO || Data.IsUsed)
1790             continue;
1791           if (Data.V == Op) {
1792             FoundCandidate = true;
1793             Data.IsUsed = true;
1794             break;
1795           }
1796         }
1797         if (!FoundCandidate)
1798           return false;
1799       }
1800       return true;
1801     }
1802 
1803   public:
1804     /// Initialize with all the operands of the instruction vector \p RootVL.
1805     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1806                ScalarEvolution &SE, const BoUpSLP &R)
1807         : DL(DL), SE(SE), R(R) {
1808       // Append all the operands of RootVL.
1809       appendOperandsOfVL(RootVL);
1810     }
1811 
1812     /// \Returns a value vector with the operands across all lanes for the
1813     /// opearnd at \p OpIdx.
1814     ValueList getVL(unsigned OpIdx) const {
1815       ValueList OpVL(OpsVec[OpIdx].size());
1816       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1817              "Expected same num of lanes across all operands");
1818       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1819         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1820       return OpVL;
1821     }
1822 
1823     // Performs operand reordering for 2 or more operands.
1824     // The original operands are in OrigOps[OpIdx][Lane].
1825     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1826     void reorder() {
1827       unsigned NumOperands = getNumOperands();
1828       unsigned NumLanes = getNumLanes();
1829       // Each operand has its own mode. We are using this mode to help us select
1830       // the instructions for each lane, so that they match best with the ones
1831       // we have selected so far.
1832       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1833 
1834       // This is a greedy single-pass algorithm. We are going over each lane
1835       // once and deciding on the best order right away with no back-tracking.
1836       // However, in order to increase its effectiveness, we start with the lane
1837       // that has operands that can move the least. For example, given the
1838       // following lanes:
1839       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1840       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1841       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1842       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1843       // we will start at Lane 1, since the operands of the subtraction cannot
1844       // be reordered. Then we will visit the rest of the lanes in a circular
1845       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1846 
1847       // Find the first lane that we will start our search from.
1848       unsigned FirstLane = getBestLaneToStartReordering();
1849 
1850       // Initialize the modes.
1851       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1852         Value *OpLane0 = getValue(OpIdx, FirstLane);
1853         // Keep track if we have instructions with all the same opcode on one
1854         // side.
1855         if (isa<LoadInst>(OpLane0))
1856           ReorderingModes[OpIdx] = ReorderingMode::Load;
1857         else if (isa<Instruction>(OpLane0)) {
1858           // Check if OpLane0 should be broadcast.
1859           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1860             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1861           else
1862             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1863         }
1864         else if (isa<Constant>(OpLane0))
1865           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1866         else if (isa<Argument>(OpLane0))
1867           // Our best hope is a Splat. It may save some cost in some cases.
1868           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1869         else
1870           // NOTE: This should be unreachable.
1871           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1872       }
1873 
1874       // Check that we don't have same operands. No need to reorder if operands
1875       // are just perfect diamond or shuffled diamond match. Do not do it only
1876       // for possible broadcasts or non-power of 2 number of scalars (just for
1877       // now).
1878       auto &&SkipReordering = [this]() {
1879         SmallPtrSet<Value *, 4> UniqueValues;
1880         ArrayRef<OperandData> Op0 = OpsVec.front();
1881         for (const OperandData &Data : Op0)
1882           UniqueValues.insert(Data.V);
1883         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1884           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1885                 return !UniqueValues.contains(Data.V);
1886               }))
1887             return false;
1888         }
1889         // TODO: Check if we can remove a check for non-power-2 number of
1890         // scalars after full support of non-power-2 vectorization.
1891         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1892       };
1893 
1894       // If the initial strategy fails for any of the operand indexes, then we
1895       // perform reordering again in a second pass. This helps avoid assigning
1896       // high priority to the failed strategy, and should improve reordering for
1897       // the non-failed operand indexes.
1898       for (int Pass = 0; Pass != 2; ++Pass) {
1899         // Check if no need to reorder operands since they're are perfect or
1900         // shuffled diamond match.
1901         // Need to to do it to avoid extra external use cost counting for
1902         // shuffled matches, which may cause regressions.
1903         if (SkipReordering())
1904           break;
1905         // Skip the second pass if the first pass did not fail.
1906         bool StrategyFailed = false;
1907         // Mark all operand data as free to use.
1908         clearUsed();
1909         // We keep the original operand order for the FirstLane, so reorder the
1910         // rest of the lanes. We are visiting the nodes in a circular fashion,
1911         // using FirstLane as the center point and increasing the radius
1912         // distance.
1913         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1914         for (unsigned I = 0; I < NumOperands; ++I)
1915           MainAltOps[I].push_back(getData(I, FirstLane).V);
1916 
1917         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1918           // Visit the lane on the right and then the lane on the left.
1919           for (int Direction : {+1, -1}) {
1920             int Lane = FirstLane + Direction * Distance;
1921             if (Lane < 0 || Lane >= (int)NumLanes)
1922               continue;
1923             int LastLane = Lane - Direction;
1924             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1925                    "Out of bounds");
1926             // Look for a good match for each operand.
1927             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1928               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1929               Optional<unsigned> BestIdx = getBestOperand(
1930                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1931               // By not selecting a value, we allow the operands that follow to
1932               // select a better matching value. We will get a non-null value in
1933               // the next run of getBestOperand().
1934               if (BestIdx) {
1935                 // Swap the current operand with the one returned by
1936                 // getBestOperand().
1937                 swap(OpIdx, BestIdx.getValue(), Lane);
1938               } else {
1939                 // We failed to find a best operand, set mode to 'Failed'.
1940                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1941                 // Enable the second pass.
1942                 StrategyFailed = true;
1943               }
1944               // Try to get the alternate opcode and follow it during analysis.
1945               if (MainAltOps[OpIdx].size() != 2) {
1946                 OperandData &AltOp = getData(OpIdx, Lane);
1947                 InstructionsState OpS =
1948                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1949                 if (OpS.getOpcode() && OpS.isAltShuffle())
1950                   MainAltOps[OpIdx].push_back(AltOp.V);
1951               }
1952             }
1953           }
1954         }
1955         // Skip second pass if the strategy did not fail.
1956         if (!StrategyFailed)
1957           break;
1958       }
1959     }
1960 
1961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1962     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1963       switch (RMode) {
1964       case ReorderingMode::Load:
1965         return "Load";
1966       case ReorderingMode::Opcode:
1967         return "Opcode";
1968       case ReorderingMode::Constant:
1969         return "Constant";
1970       case ReorderingMode::Splat:
1971         return "Splat";
1972       case ReorderingMode::Failed:
1973         return "Failed";
1974       }
1975       llvm_unreachable("Unimplemented Reordering Type");
1976     }
1977 
1978     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1979                                                    raw_ostream &OS) {
1980       return OS << getModeStr(RMode);
1981     }
1982 
1983     /// Debug print.
1984     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1985       printMode(RMode, dbgs());
1986     }
1987 
1988     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1989       return printMode(RMode, OS);
1990     }
1991 
1992     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1993       const unsigned Indent = 2;
1994       unsigned Cnt = 0;
1995       for (const OperandDataVec &OpDataVec : OpsVec) {
1996         OS << "Operand " << Cnt++ << "\n";
1997         for (const OperandData &OpData : OpDataVec) {
1998           OS.indent(Indent) << "{";
1999           if (Value *V = OpData.V)
2000             OS << *V;
2001           else
2002             OS << "null";
2003           OS << ", APO:" << OpData.APO << "}\n";
2004         }
2005         OS << "\n";
2006       }
2007       return OS;
2008     }
2009 
2010     /// Debug print.
2011     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2012 #endif
2013   };
2014 
2015   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2016   /// for a pair which have highest score deemed to have best chance to form
2017   /// root of profitable tree to vectorize. Return None if no candidate scored
2018   /// above the LookAheadHeuristics::ScoreFail.
2019   Optional<int>
2020   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2021     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2022                                   RootLookAheadMaxDepth);
2023     int BestScore = LookAheadHeuristics::ScoreFail;
2024     Optional<int> Index = None;
2025     for (int I : seq<int>(0, Candidates.size())) {
2026       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2027                                                Candidates[I].second,
2028                                                /*U1=*/nullptr, /*U2=*/nullptr,
2029                                                /*Level=*/1, None);
2030       if (Score > BestScore) {
2031         BestScore = Score;
2032         Index = I;
2033       }
2034     }
2035     return Index;
2036   }
2037 
2038   /// Checks if the instruction is marked for deletion.
2039   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2040 
2041   /// Removes an instruction from its block and eventually deletes it.
2042   /// It's like Instruction::eraseFromParent() except that the actual deletion
2043   /// is delayed until BoUpSLP is destructed.
2044   void eraseInstruction(Instruction *I) {
2045     DeletedInstructions.insert(I);
2046   }
2047 
2048   /// Checks if the instruction was already analyzed for being possible
2049   /// reduction root.
2050   bool isAnalizedReductionRoot(Instruction *I) const {
2051     return AnalizedReductionsRoots.count(I);
2052   }
2053   /// Register given instruction as already analyzed for being possible
2054   /// reduction root.
2055   void analyzedReductionRoot(Instruction *I) {
2056     AnalizedReductionsRoots.insert(I);
2057   }
2058   /// Checks if the provided list of reduced values was checked already for
2059   /// vectorization.
2060   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2061     return AnalyzedReductionVals.contains(hash_value(VL));
2062   }
2063   /// Adds the list of reduced values to list of already checked values for the
2064   /// vectorization.
2065   void analyzedReductionVals(ArrayRef<Value *> VL) {
2066     AnalyzedReductionVals.insert(hash_value(VL));
2067   }
2068   /// Clear the list of the analyzed reduction root instructions.
2069   void clearReductionData() {
2070     AnalizedReductionsRoots.clear();
2071     AnalyzedReductionVals.clear();
2072   }
2073   /// Checks if the given value is gathered in one of the nodes.
2074   bool isGathered(Value *V) const {
2075     return MustGather.contains(V);
2076   }
2077 
2078   ~BoUpSLP();
2079 
2080 private:
2081   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2082   /// reordering (i.e. the operands can be reordered because they have only one
2083   /// user and reordarable).
2084   /// \param ReorderableGathers List of all gather nodes that require reordering
2085   /// (e.g., gather of extractlements or partially vectorizable loads).
2086   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2087   /// reordering, subset of \p NonVectorized.
2088   bool
2089   canReorderOperands(TreeEntry *UserTE,
2090                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2091                      ArrayRef<TreeEntry *> ReorderableGathers,
2092                      SmallVectorImpl<TreeEntry *> &GatherOps);
2093 
2094   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2095   /// if any. If it is not vectorized (gather node), returns nullptr.
2096   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2097     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2098     TreeEntry *TE = nullptr;
2099     const auto *It = find_if(VL, [this, &TE](Value *V) {
2100       TE = getTreeEntry(V);
2101       return TE;
2102     });
2103     if (It != VL.end() && TE->isSame(VL))
2104       return TE;
2105     return nullptr;
2106   }
2107 
2108   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2109   /// if any. If it is not vectorized (gather node), returns nullptr.
2110   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2111                                         unsigned OpIdx) const {
2112     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2113         const_cast<TreeEntry *>(UserTE), OpIdx);
2114   }
2115 
2116   /// Checks if all users of \p I are the part of the vectorization tree.
2117   bool areAllUsersVectorized(Instruction *I,
2118                              ArrayRef<Value *> VectorizedVals) const;
2119 
2120   /// \returns the cost of the vectorizable entry.
2121   InstructionCost getEntryCost(const TreeEntry *E,
2122                                ArrayRef<Value *> VectorizedVals);
2123 
2124   /// This is the recursive part of buildTree.
2125   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2126                      const EdgeInfo &EI);
2127 
2128   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2129   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2130   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2131   /// returns false, setting \p CurrentOrder to either an empty vector or a
2132   /// non-identity permutation that allows to reuse extract instructions.
2133   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2134                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2135 
2136   /// Vectorize a single entry in the tree.
2137   Value *vectorizeTree(TreeEntry *E);
2138 
2139   /// Vectorize a single entry in the tree, starting in \p VL.
2140   Value *vectorizeTree(ArrayRef<Value *> VL);
2141 
2142   /// Create a new vector from a list of scalar values.  Produces a sequence
2143   /// which exploits values reused across lanes, and arranges the inserts
2144   /// for ease of later optimization.
2145   Value *createBuildVector(ArrayRef<Value *> VL);
2146 
2147   /// \returns the scalarization cost for this type. Scalarization in this
2148   /// context means the creation of vectors from a group of scalars. If \p
2149   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2150   /// vector elements.
2151   InstructionCost getGatherCost(FixedVectorType *Ty,
2152                                 const APInt &ShuffledIndices,
2153                                 bool NeedToShuffle) const;
2154 
2155   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2156   /// tree entries.
2157   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2158   /// previous tree entries. \p Mask is filled with the shuffle mask.
2159   Optional<TargetTransformInfo::ShuffleKind>
2160   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2161                         SmallVectorImpl<const TreeEntry *> &Entries);
2162 
2163   /// \returns the scalarization cost for this list of values. Assuming that
2164   /// this subtree gets vectorized, we may need to extract the values from the
2165   /// roots. This method calculates the cost of extracting the values.
2166   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2167 
2168   /// Set the Builder insert point to one after the last instruction in
2169   /// the bundle
2170   void setInsertPointAfterBundle(const TreeEntry *E);
2171 
2172   /// \returns a vector from a collection of scalars in \p VL.
2173   Value *gather(ArrayRef<Value *> VL);
2174 
2175   /// \returns whether the VectorizableTree is fully vectorizable and will
2176   /// be beneficial even the tree height is tiny.
2177   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2178 
2179   /// Reorder commutative or alt operands to get better probability of
2180   /// generating vectorized code.
2181   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2182                                              SmallVectorImpl<Value *> &Left,
2183                                              SmallVectorImpl<Value *> &Right,
2184                                              const DataLayout &DL,
2185                                              ScalarEvolution &SE,
2186                                              const BoUpSLP &R);
2187 
2188   /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2189   /// users of \p TE and collects the stores. It returns the map from the store
2190   /// pointers to the collected stores.
2191   DenseMap<Value *, SmallVector<StoreInst *, 4>>
2192   collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2193 
2194   /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2195   /// stores in \p StoresVec can for a vector instruction. If so it returns true
2196   /// and populates \p ReorderIndices with the shuffle indices of the the stores
2197   /// when compared to the sorted vector.
2198   bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2199                      OrdersType &ReorderIndices) const;
2200 
2201   /// Iterates through the users of \p TE, looking for scalar stores that can be
2202   /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2203   /// their order and builds an order index vector for each store bundle. It
2204   /// returns all these order vectors found.
2205   /// We run this after the tree has formed, otherwise we may come across user
2206   /// instructions that are not yet in the tree.
2207   SmallVector<OrdersType, 1>
2208   findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2209 
2210   struct TreeEntry {
2211     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2212     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2213 
2214     /// \returns true if the scalars in VL are equal to this entry.
2215     bool isSame(ArrayRef<Value *> VL) const {
2216       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2217         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2218           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2219         return VL.size() == Mask.size() &&
2220                std::equal(VL.begin(), VL.end(), Mask.begin(),
2221                           [Scalars](Value *V, int Idx) {
2222                             return (isa<UndefValue>(V) &&
2223                                     Idx == UndefMaskElem) ||
2224                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2225                           });
2226       };
2227       if (!ReorderIndices.empty()) {
2228         // TODO: implement matching if the nodes are just reordered, still can
2229         // treat the vector as the same if the list of scalars matches VL
2230         // directly, without reordering.
2231         SmallVector<int> Mask;
2232         inversePermutation(ReorderIndices, Mask);
2233         if (VL.size() == Scalars.size())
2234           return IsSame(Scalars, Mask);
2235         if (VL.size() == ReuseShuffleIndices.size()) {
2236           ::addMask(Mask, ReuseShuffleIndices);
2237           return IsSame(Scalars, Mask);
2238         }
2239         return false;
2240       }
2241       return IsSame(Scalars, ReuseShuffleIndices);
2242     }
2243 
2244     /// \returns true if current entry has same operands as \p TE.
2245     bool hasEqualOperands(const TreeEntry &TE) const {
2246       if (TE.getNumOperands() != getNumOperands())
2247         return false;
2248       SmallBitVector Used(getNumOperands());
2249       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2250         unsigned PrevCount = Used.count();
2251         for (unsigned K = 0; K < E; ++K) {
2252           if (Used.test(K))
2253             continue;
2254           if (getOperand(K) == TE.getOperand(I)) {
2255             Used.set(K);
2256             break;
2257           }
2258         }
2259         // Check if we actually found the matching operand.
2260         if (PrevCount == Used.count())
2261           return false;
2262       }
2263       return true;
2264     }
2265 
2266     /// \return Final vectorization factor for the node. Defined by the total
2267     /// number of vectorized scalars, including those, used several times in the
2268     /// entry and counted in the \a ReuseShuffleIndices, if any.
2269     unsigned getVectorFactor() const {
2270       if (!ReuseShuffleIndices.empty())
2271         return ReuseShuffleIndices.size();
2272       return Scalars.size();
2273     };
2274 
2275     /// A vector of scalars.
2276     ValueList Scalars;
2277 
2278     /// The Scalars are vectorized into this value. It is initialized to Null.
2279     Value *VectorizedValue = nullptr;
2280 
2281     /// Do we need to gather this sequence or vectorize it
2282     /// (either with vector instruction or with scatter/gather
2283     /// intrinsics for store/load)?
2284     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2285     EntryState State;
2286 
2287     /// Does this sequence require some shuffling?
2288     SmallVector<int, 4> ReuseShuffleIndices;
2289 
2290     /// Does this entry require reordering?
2291     SmallVector<unsigned, 4> ReorderIndices;
2292 
2293     /// Points back to the VectorizableTree.
2294     ///
2295     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2296     /// to be a pointer and needs to be able to initialize the child iterator.
2297     /// Thus we need a reference back to the container to translate the indices
2298     /// to entries.
2299     VecTreeTy &Container;
2300 
2301     /// The TreeEntry index containing the user of this entry.  We can actually
2302     /// have multiple users so the data structure is not truly a tree.
2303     SmallVector<EdgeInfo, 1> UserTreeIndices;
2304 
2305     /// The index of this treeEntry in VectorizableTree.
2306     int Idx = -1;
2307 
2308   private:
2309     /// The operands of each instruction in each lane Operands[op_index][lane].
2310     /// Note: This helps avoid the replication of the code that performs the
2311     /// reordering of operands during buildTree_rec() and vectorizeTree().
2312     SmallVector<ValueList, 2> Operands;
2313 
2314     /// The main/alternate instruction.
2315     Instruction *MainOp = nullptr;
2316     Instruction *AltOp = nullptr;
2317 
2318   public:
2319     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2320     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2321       if (Operands.size() < OpIdx + 1)
2322         Operands.resize(OpIdx + 1);
2323       assert(Operands[OpIdx].empty() && "Already resized?");
2324       assert(OpVL.size() <= Scalars.size() &&
2325              "Number of operands is greater than the number of scalars.");
2326       Operands[OpIdx].resize(OpVL.size());
2327       copy(OpVL, Operands[OpIdx].begin());
2328     }
2329 
2330     /// Set the operands of this bundle in their original order.
2331     void setOperandsInOrder() {
2332       assert(Operands.empty() && "Already initialized?");
2333       auto *I0 = cast<Instruction>(Scalars[0]);
2334       Operands.resize(I0->getNumOperands());
2335       unsigned NumLanes = Scalars.size();
2336       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2337            OpIdx != NumOperands; ++OpIdx) {
2338         Operands[OpIdx].resize(NumLanes);
2339         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2340           auto *I = cast<Instruction>(Scalars[Lane]);
2341           assert(I->getNumOperands() == NumOperands &&
2342                  "Expected same number of operands");
2343           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2344         }
2345       }
2346     }
2347 
2348     /// Reorders operands of the node to the given mask \p Mask.
2349     void reorderOperands(ArrayRef<int> Mask) {
2350       for (ValueList &Operand : Operands)
2351         reorderScalars(Operand, Mask);
2352     }
2353 
2354     /// \returns the \p OpIdx operand of this TreeEntry.
2355     ValueList &getOperand(unsigned OpIdx) {
2356       assert(OpIdx < Operands.size() && "Off bounds");
2357       return Operands[OpIdx];
2358     }
2359 
2360     /// \returns the \p OpIdx operand of this TreeEntry.
2361     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2362       assert(OpIdx < Operands.size() && "Off bounds");
2363       return Operands[OpIdx];
2364     }
2365 
2366     /// \returns the number of operands.
2367     unsigned getNumOperands() const { return Operands.size(); }
2368 
2369     /// \return the single \p OpIdx operand.
2370     Value *getSingleOperand(unsigned OpIdx) const {
2371       assert(OpIdx < Operands.size() && "Off bounds");
2372       assert(!Operands[OpIdx].empty() && "No operand available");
2373       return Operands[OpIdx][0];
2374     }
2375 
2376     /// Some of the instructions in the list have alternate opcodes.
2377     bool isAltShuffle() const { return MainOp != AltOp; }
2378 
2379     bool isOpcodeOrAlt(Instruction *I) const {
2380       unsigned CheckedOpcode = I->getOpcode();
2381       return (getOpcode() == CheckedOpcode ||
2382               getAltOpcode() == CheckedOpcode);
2383     }
2384 
2385     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2386     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2387     /// \p OpValue.
2388     Value *isOneOf(Value *Op) const {
2389       auto *I = dyn_cast<Instruction>(Op);
2390       if (I && isOpcodeOrAlt(I))
2391         return Op;
2392       return MainOp;
2393     }
2394 
2395     void setOperations(const InstructionsState &S) {
2396       MainOp = S.MainOp;
2397       AltOp = S.AltOp;
2398     }
2399 
2400     Instruction *getMainOp() const {
2401       return MainOp;
2402     }
2403 
2404     Instruction *getAltOp() const {
2405       return AltOp;
2406     }
2407 
2408     /// The main/alternate opcodes for the list of instructions.
2409     unsigned getOpcode() const {
2410       return MainOp ? MainOp->getOpcode() : 0;
2411     }
2412 
2413     unsigned getAltOpcode() const {
2414       return AltOp ? AltOp->getOpcode() : 0;
2415     }
2416 
2417     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2418     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2419     int findLaneForValue(Value *V) const {
2420       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2421       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2422       if (!ReorderIndices.empty())
2423         FoundLane = ReorderIndices[FoundLane];
2424       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2425       if (!ReuseShuffleIndices.empty()) {
2426         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2427                                   find(ReuseShuffleIndices, FoundLane));
2428       }
2429       return FoundLane;
2430     }
2431 
2432 #ifndef NDEBUG
2433     /// Debug printer.
2434     LLVM_DUMP_METHOD void dump() const {
2435       dbgs() << Idx << ".\n";
2436       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2437         dbgs() << "Operand " << OpI << ":\n";
2438         for (const Value *V : Operands[OpI])
2439           dbgs().indent(2) << *V << "\n";
2440       }
2441       dbgs() << "Scalars: \n";
2442       for (Value *V : Scalars)
2443         dbgs().indent(2) << *V << "\n";
2444       dbgs() << "State: ";
2445       switch (State) {
2446       case Vectorize:
2447         dbgs() << "Vectorize\n";
2448         break;
2449       case ScatterVectorize:
2450         dbgs() << "ScatterVectorize\n";
2451         break;
2452       case NeedToGather:
2453         dbgs() << "NeedToGather\n";
2454         break;
2455       }
2456       dbgs() << "MainOp: ";
2457       if (MainOp)
2458         dbgs() << *MainOp << "\n";
2459       else
2460         dbgs() << "NULL\n";
2461       dbgs() << "AltOp: ";
2462       if (AltOp)
2463         dbgs() << *AltOp << "\n";
2464       else
2465         dbgs() << "NULL\n";
2466       dbgs() << "VectorizedValue: ";
2467       if (VectorizedValue)
2468         dbgs() << *VectorizedValue << "\n";
2469       else
2470         dbgs() << "NULL\n";
2471       dbgs() << "ReuseShuffleIndices: ";
2472       if (ReuseShuffleIndices.empty())
2473         dbgs() << "Empty";
2474       else
2475         for (int ReuseIdx : ReuseShuffleIndices)
2476           dbgs() << ReuseIdx << ", ";
2477       dbgs() << "\n";
2478       dbgs() << "ReorderIndices: ";
2479       for (unsigned ReorderIdx : ReorderIndices)
2480         dbgs() << ReorderIdx << ", ";
2481       dbgs() << "\n";
2482       dbgs() << "UserTreeIndices: ";
2483       for (const auto &EInfo : UserTreeIndices)
2484         dbgs() << EInfo << ", ";
2485       dbgs() << "\n";
2486     }
2487 #endif
2488   };
2489 
2490 #ifndef NDEBUG
2491   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2492                      InstructionCost VecCost,
2493                      InstructionCost ScalarCost) const {
2494     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2495     dbgs() << "SLP: Costs:\n";
2496     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2497     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2498     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2499     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2500                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2501   }
2502 #endif
2503 
2504   /// Create a new VectorizableTree entry.
2505   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2506                           const InstructionsState &S,
2507                           const EdgeInfo &UserTreeIdx,
2508                           ArrayRef<int> ReuseShuffleIndices = None,
2509                           ArrayRef<unsigned> ReorderIndices = None) {
2510     TreeEntry::EntryState EntryState =
2511         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2512     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2513                         ReuseShuffleIndices, ReorderIndices);
2514   }
2515 
2516   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2517                           TreeEntry::EntryState EntryState,
2518                           Optional<ScheduleData *> Bundle,
2519                           const InstructionsState &S,
2520                           const EdgeInfo &UserTreeIdx,
2521                           ArrayRef<int> ReuseShuffleIndices = None,
2522                           ArrayRef<unsigned> ReorderIndices = None) {
2523     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2524             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2525            "Need to vectorize gather entry?");
2526     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2527     TreeEntry *Last = VectorizableTree.back().get();
2528     Last->Idx = VectorizableTree.size() - 1;
2529     Last->State = EntryState;
2530     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2531                                      ReuseShuffleIndices.end());
2532     if (ReorderIndices.empty()) {
2533       Last->Scalars.assign(VL.begin(), VL.end());
2534       Last->setOperations(S);
2535     } else {
2536       // Reorder scalars and build final mask.
2537       Last->Scalars.assign(VL.size(), nullptr);
2538       transform(ReorderIndices, Last->Scalars.begin(),
2539                 [VL](unsigned Idx) -> Value * {
2540                   if (Idx >= VL.size())
2541                     return UndefValue::get(VL.front()->getType());
2542                   return VL[Idx];
2543                 });
2544       InstructionsState S = getSameOpcode(Last->Scalars);
2545       Last->setOperations(S);
2546       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2547     }
2548     if (Last->State != TreeEntry::NeedToGather) {
2549       for (Value *V : VL) {
2550         assert(!getTreeEntry(V) && "Scalar already in tree!");
2551         ScalarToTreeEntry[V] = Last;
2552       }
2553       // Update the scheduler bundle to point to this TreeEntry.
2554       ScheduleData *BundleMember = Bundle.getValue();
2555       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2556               isVectorLikeInstWithConstOps(S.MainOp) ||
2557               doesNotNeedToSchedule(VL)) &&
2558              "Bundle and VL out of sync");
2559       if (BundleMember) {
2560         for (Value *V : VL) {
2561           if (doesNotNeedToBeScheduled(V))
2562             continue;
2563           assert(BundleMember && "Unexpected end of bundle.");
2564           BundleMember->TE = Last;
2565           BundleMember = BundleMember->NextInBundle;
2566         }
2567       }
2568       assert(!BundleMember && "Bundle and VL out of sync");
2569     } else {
2570       MustGather.insert(VL.begin(), VL.end());
2571     }
2572 
2573     if (UserTreeIdx.UserTE)
2574       Last->UserTreeIndices.push_back(UserTreeIdx);
2575 
2576     return Last;
2577   }
2578 
2579   /// -- Vectorization State --
2580   /// Holds all of the tree entries.
2581   TreeEntry::VecTreeTy VectorizableTree;
2582 
2583 #ifndef NDEBUG
2584   /// Debug printer.
2585   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2586     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2587       VectorizableTree[Id]->dump();
2588       dbgs() << "\n";
2589     }
2590   }
2591 #endif
2592 
2593   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2594 
2595   const TreeEntry *getTreeEntry(Value *V) const {
2596     return ScalarToTreeEntry.lookup(V);
2597   }
2598 
2599   /// Maps a specific scalar to its tree entry.
2600   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2601 
2602   /// Maps a value to the proposed vectorizable size.
2603   SmallDenseMap<Value *, unsigned> InstrElementSize;
2604 
2605   /// A list of scalars that we found that we need to keep as scalars.
2606   ValueSet MustGather;
2607 
2608   /// This POD struct describes one external user in the vectorized tree.
2609   struct ExternalUser {
2610     ExternalUser(Value *S, llvm::User *U, int L)
2611         : Scalar(S), User(U), Lane(L) {}
2612 
2613     // Which scalar in our function.
2614     Value *Scalar;
2615 
2616     // Which user that uses the scalar.
2617     llvm::User *User;
2618 
2619     // Which lane does the scalar belong to.
2620     int Lane;
2621   };
2622   using UserList = SmallVector<ExternalUser, 16>;
2623 
2624   /// Checks if two instructions may access the same memory.
2625   ///
2626   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2627   /// is invariant in the calling loop.
2628   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2629                  Instruction *Inst2) {
2630     // First check if the result is already in the cache.
2631     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2632     Optional<bool> &result = AliasCache[key];
2633     if (result.hasValue()) {
2634       return result.getValue();
2635     }
2636     bool aliased = true;
2637     if (Loc1.Ptr && isSimple(Inst1))
2638       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2639     // Store the result in the cache.
2640     result = aliased;
2641     return aliased;
2642   }
2643 
2644   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2645 
2646   /// Cache for alias results.
2647   /// TODO: consider moving this to the AliasAnalysis itself.
2648   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2649 
2650   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2651   // globally through SLP because we don't perform any action which
2652   // invalidates capture results.
2653   BatchAAResults BatchAA;
2654 
2655   /// Temporary store for deleted instructions. Instructions will be deleted
2656   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2657   /// ensure that there are no incorrect collisions in the AliasCache, which
2658   /// can happen if a new instruction is allocated at the same address as a
2659   /// previously deleted instruction.
2660   DenseSet<Instruction *> DeletedInstructions;
2661 
2662   /// Set of the instruction, being analyzed already for reductions.
2663   SmallPtrSet<Instruction *, 16> AnalizedReductionsRoots;
2664 
2665   /// Set of hashes for the list of reduction values already being analyzed.
2666   DenseSet<size_t> AnalyzedReductionVals;
2667 
2668   /// A list of values that need to extracted out of the tree.
2669   /// This list holds pairs of (Internal Scalar : External User). External User
2670   /// can be nullptr, it means that this Internal Scalar will be used later,
2671   /// after vectorization.
2672   UserList ExternalUses;
2673 
2674   /// Values used only by @llvm.assume calls.
2675   SmallPtrSet<const Value *, 32> EphValues;
2676 
2677   /// Holds all of the instructions that we gathered.
2678   SetVector<Instruction *> GatherShuffleSeq;
2679 
2680   /// A list of blocks that we are going to CSE.
2681   SetVector<BasicBlock *> CSEBlocks;
2682 
2683   /// Contains all scheduling relevant data for an instruction.
2684   /// A ScheduleData either represents a single instruction or a member of an
2685   /// instruction bundle (= a group of instructions which is combined into a
2686   /// vector instruction).
2687   struct ScheduleData {
2688     // The initial value for the dependency counters. It means that the
2689     // dependencies are not calculated yet.
2690     enum { InvalidDeps = -1 };
2691 
2692     ScheduleData() = default;
2693 
2694     void init(int BlockSchedulingRegionID, Value *OpVal) {
2695       FirstInBundle = this;
2696       NextInBundle = nullptr;
2697       NextLoadStore = nullptr;
2698       IsScheduled = false;
2699       SchedulingRegionID = BlockSchedulingRegionID;
2700       clearDependencies();
2701       OpValue = OpVal;
2702       TE = nullptr;
2703     }
2704 
2705     /// Verify basic self consistency properties
2706     void verify() {
2707       if (hasValidDependencies()) {
2708         assert(UnscheduledDeps <= Dependencies && "invariant");
2709       } else {
2710         assert(UnscheduledDeps == Dependencies && "invariant");
2711       }
2712 
2713       if (IsScheduled) {
2714         assert(isSchedulingEntity() &&
2715                 "unexpected scheduled state");
2716         for (const ScheduleData *BundleMember = this; BundleMember;
2717              BundleMember = BundleMember->NextInBundle) {
2718           assert(BundleMember->hasValidDependencies() &&
2719                  BundleMember->UnscheduledDeps == 0 &&
2720                  "unexpected scheduled state");
2721           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2722                  "only bundle is marked scheduled");
2723         }
2724       }
2725 
2726       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2727              "all bundle members must be in same basic block");
2728     }
2729 
2730     /// Returns true if the dependency information has been calculated.
2731     /// Note that depenendency validity can vary between instructions within
2732     /// a single bundle.
2733     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2734 
2735     /// Returns true for single instructions and for bundle representatives
2736     /// (= the head of a bundle).
2737     bool isSchedulingEntity() const { return FirstInBundle == this; }
2738 
2739     /// Returns true if it represents an instruction bundle and not only a
2740     /// single instruction.
2741     bool isPartOfBundle() const {
2742       return NextInBundle != nullptr || FirstInBundle != this || TE;
2743     }
2744 
2745     /// Returns true if it is ready for scheduling, i.e. it has no more
2746     /// unscheduled depending instructions/bundles.
2747     bool isReady() const {
2748       assert(isSchedulingEntity() &&
2749              "can't consider non-scheduling entity for ready list");
2750       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2751     }
2752 
2753     /// Modifies the number of unscheduled dependencies for this instruction,
2754     /// and returns the number of remaining dependencies for the containing
2755     /// bundle.
2756     int incrementUnscheduledDeps(int Incr) {
2757       assert(hasValidDependencies() &&
2758              "increment of unscheduled deps would be meaningless");
2759       UnscheduledDeps += Incr;
2760       return FirstInBundle->unscheduledDepsInBundle();
2761     }
2762 
2763     /// Sets the number of unscheduled dependencies to the number of
2764     /// dependencies.
2765     void resetUnscheduledDeps() {
2766       UnscheduledDeps = Dependencies;
2767     }
2768 
2769     /// Clears all dependency information.
2770     void clearDependencies() {
2771       Dependencies = InvalidDeps;
2772       resetUnscheduledDeps();
2773       MemoryDependencies.clear();
2774       ControlDependencies.clear();
2775     }
2776 
2777     int unscheduledDepsInBundle() const {
2778       assert(isSchedulingEntity() && "only meaningful on the bundle");
2779       int Sum = 0;
2780       for (const ScheduleData *BundleMember = this; BundleMember;
2781            BundleMember = BundleMember->NextInBundle) {
2782         if (BundleMember->UnscheduledDeps == InvalidDeps)
2783           return InvalidDeps;
2784         Sum += BundleMember->UnscheduledDeps;
2785       }
2786       return Sum;
2787     }
2788 
2789     void dump(raw_ostream &os) const {
2790       if (!isSchedulingEntity()) {
2791         os << "/ " << *Inst;
2792       } else if (NextInBundle) {
2793         os << '[' << *Inst;
2794         ScheduleData *SD = NextInBundle;
2795         while (SD) {
2796           os << ';' << *SD->Inst;
2797           SD = SD->NextInBundle;
2798         }
2799         os << ']';
2800       } else {
2801         os << *Inst;
2802       }
2803     }
2804 
2805     Instruction *Inst = nullptr;
2806 
2807     /// Opcode of the current instruction in the schedule data.
2808     Value *OpValue = nullptr;
2809 
2810     /// The TreeEntry that this instruction corresponds to.
2811     TreeEntry *TE = nullptr;
2812 
2813     /// Points to the head in an instruction bundle (and always to this for
2814     /// single instructions).
2815     ScheduleData *FirstInBundle = nullptr;
2816 
2817     /// Single linked list of all instructions in a bundle. Null if it is a
2818     /// single instruction.
2819     ScheduleData *NextInBundle = nullptr;
2820 
2821     /// Single linked list of all memory instructions (e.g. load, store, call)
2822     /// in the block - until the end of the scheduling region.
2823     ScheduleData *NextLoadStore = nullptr;
2824 
2825     /// The dependent memory instructions.
2826     /// This list is derived on demand in calculateDependencies().
2827     SmallVector<ScheduleData *, 4> MemoryDependencies;
2828 
2829     /// List of instructions which this instruction could be control dependent
2830     /// on.  Allowing such nodes to be scheduled below this one could introduce
2831     /// a runtime fault which didn't exist in the original program.
2832     /// ex: this is a load or udiv following a readonly call which inf loops
2833     SmallVector<ScheduleData *, 4> ControlDependencies;
2834 
2835     /// This ScheduleData is in the current scheduling region if this matches
2836     /// the current SchedulingRegionID of BlockScheduling.
2837     int SchedulingRegionID = 0;
2838 
2839     /// Used for getting a "good" final ordering of instructions.
2840     int SchedulingPriority = 0;
2841 
2842     /// The number of dependencies. Constitutes of the number of users of the
2843     /// instruction plus the number of dependent memory instructions (if any).
2844     /// This value is calculated on demand.
2845     /// If InvalidDeps, the number of dependencies is not calculated yet.
2846     int Dependencies = InvalidDeps;
2847 
2848     /// The number of dependencies minus the number of dependencies of scheduled
2849     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2850     /// for scheduling.
2851     /// Note that this is negative as long as Dependencies is not calculated.
2852     int UnscheduledDeps = InvalidDeps;
2853 
2854     /// True if this instruction is scheduled (or considered as scheduled in the
2855     /// dry-run).
2856     bool IsScheduled = false;
2857   };
2858 
2859 #ifndef NDEBUG
2860   friend inline raw_ostream &operator<<(raw_ostream &os,
2861                                         const BoUpSLP::ScheduleData &SD) {
2862     SD.dump(os);
2863     return os;
2864   }
2865 #endif
2866 
2867   friend struct GraphTraits<BoUpSLP *>;
2868   friend struct DOTGraphTraits<BoUpSLP *>;
2869 
2870   /// Contains all scheduling data for a basic block.
2871   /// It does not schedules instructions, which are not memory read/write
2872   /// instructions and their operands are either constants, or arguments, or
2873   /// phis, or instructions from others blocks, or their users are phis or from
2874   /// the other blocks. The resulting vector instructions can be placed at the
2875   /// beginning of the basic block without scheduling (if operands does not need
2876   /// to be scheduled) or at the end of the block (if users are outside of the
2877   /// block). It allows to save some compile time and memory used by the
2878   /// compiler.
2879   /// ScheduleData is assigned for each instruction in between the boundaries of
2880   /// the tree entry, even for those, which are not part of the graph. It is
2881   /// required to correctly follow the dependencies between the instructions and
2882   /// their correct scheduling. The ScheduleData is not allocated for the
2883   /// instructions, which do not require scheduling, like phis, nodes with
2884   /// extractelements/insertelements only or nodes with instructions, with
2885   /// uses/operands outside of the block.
2886   struct BlockScheduling {
2887     BlockScheduling(BasicBlock *BB)
2888         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2889 
2890     void clear() {
2891       ReadyInsts.clear();
2892       ScheduleStart = nullptr;
2893       ScheduleEnd = nullptr;
2894       FirstLoadStoreInRegion = nullptr;
2895       LastLoadStoreInRegion = nullptr;
2896       RegionHasStackSave = false;
2897 
2898       // Reduce the maximum schedule region size by the size of the
2899       // previous scheduling run.
2900       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2901       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2902         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2903       ScheduleRegionSize = 0;
2904 
2905       // Make a new scheduling region, i.e. all existing ScheduleData is not
2906       // in the new region yet.
2907       ++SchedulingRegionID;
2908     }
2909 
2910     ScheduleData *getScheduleData(Instruction *I) {
2911       if (BB != I->getParent())
2912         // Avoid lookup if can't possibly be in map.
2913         return nullptr;
2914       ScheduleData *SD = ScheduleDataMap.lookup(I);
2915       if (SD && isInSchedulingRegion(SD))
2916         return SD;
2917       return nullptr;
2918     }
2919 
2920     ScheduleData *getScheduleData(Value *V) {
2921       if (auto *I = dyn_cast<Instruction>(V))
2922         return getScheduleData(I);
2923       return nullptr;
2924     }
2925 
2926     ScheduleData *getScheduleData(Value *V, Value *Key) {
2927       if (V == Key)
2928         return getScheduleData(V);
2929       auto I = ExtraScheduleDataMap.find(V);
2930       if (I != ExtraScheduleDataMap.end()) {
2931         ScheduleData *SD = I->second.lookup(Key);
2932         if (SD && isInSchedulingRegion(SD))
2933           return SD;
2934       }
2935       return nullptr;
2936     }
2937 
2938     bool isInSchedulingRegion(ScheduleData *SD) const {
2939       return SD->SchedulingRegionID == SchedulingRegionID;
2940     }
2941 
2942     /// Marks an instruction as scheduled and puts all dependent ready
2943     /// instructions into the ready-list.
2944     template <typename ReadyListType>
2945     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2946       SD->IsScheduled = true;
2947       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2948 
2949       for (ScheduleData *BundleMember = SD; BundleMember;
2950            BundleMember = BundleMember->NextInBundle) {
2951         if (BundleMember->Inst != BundleMember->OpValue)
2952           continue;
2953 
2954         // Handle the def-use chain dependencies.
2955 
2956         // Decrement the unscheduled counter and insert to ready list if ready.
2957         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2958           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2959             if (OpDef && OpDef->hasValidDependencies() &&
2960                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2961               // There are no more unscheduled dependencies after
2962               // decrementing, so we can put the dependent instruction
2963               // into the ready list.
2964               ScheduleData *DepBundle = OpDef->FirstInBundle;
2965               assert(!DepBundle->IsScheduled &&
2966                      "already scheduled bundle gets ready");
2967               ReadyList.insert(DepBundle);
2968               LLVM_DEBUG(dbgs()
2969                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2970             }
2971           });
2972         };
2973 
2974         // If BundleMember is a vector bundle, its operands may have been
2975         // reordered during buildTree(). We therefore need to get its operands
2976         // through the TreeEntry.
2977         if (TreeEntry *TE = BundleMember->TE) {
2978           // Need to search for the lane since the tree entry can be reordered.
2979           int Lane = std::distance(TE->Scalars.begin(),
2980                                    find(TE->Scalars, BundleMember->Inst));
2981           assert(Lane >= 0 && "Lane not set");
2982 
2983           // Since vectorization tree is being built recursively this assertion
2984           // ensures that the tree entry has all operands set before reaching
2985           // this code. Couple of exceptions known at the moment are extracts
2986           // where their second (immediate) operand is not added. Since
2987           // immediates do not affect scheduler behavior this is considered
2988           // okay.
2989           auto *In = BundleMember->Inst;
2990           assert(In &&
2991                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2992                   In->getNumOperands() == TE->getNumOperands()) &&
2993                  "Missed TreeEntry operands?");
2994           (void)In; // fake use to avoid build failure when assertions disabled
2995 
2996           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2997                OpIdx != NumOperands; ++OpIdx)
2998             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2999               DecrUnsched(I);
3000         } else {
3001           // If BundleMember is a stand-alone instruction, no operand reordering
3002           // has taken place, so we directly access its operands.
3003           for (Use &U : BundleMember->Inst->operands())
3004             if (auto *I = dyn_cast<Instruction>(U.get()))
3005               DecrUnsched(I);
3006         }
3007         // Handle the memory dependencies.
3008         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3009           if (MemoryDepSD->hasValidDependencies() &&
3010               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3011             // There are no more unscheduled dependencies after decrementing,
3012             // so we can put the dependent instruction into the ready list.
3013             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3014             assert(!DepBundle->IsScheduled &&
3015                    "already scheduled bundle gets ready");
3016             ReadyList.insert(DepBundle);
3017             LLVM_DEBUG(dbgs()
3018                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
3019           }
3020         }
3021         // Handle the control dependencies.
3022         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3023           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3024             // There are no more unscheduled dependencies after decrementing,
3025             // so we can put the dependent instruction into the ready list.
3026             ScheduleData *DepBundle = DepSD->FirstInBundle;
3027             assert(!DepBundle->IsScheduled &&
3028                    "already scheduled bundle gets ready");
3029             ReadyList.insert(DepBundle);
3030             LLVM_DEBUG(dbgs()
3031                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3032           }
3033         }
3034 
3035       }
3036     }
3037 
3038     /// Verify basic self consistency properties of the data structure.
3039     void verify() {
3040       if (!ScheduleStart)
3041         return;
3042 
3043       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3044              ScheduleStart->comesBefore(ScheduleEnd) &&
3045              "Not a valid scheduling region?");
3046 
3047       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3048         auto *SD = getScheduleData(I);
3049         if (!SD)
3050           continue;
3051         assert(isInSchedulingRegion(SD) &&
3052                "primary schedule data not in window?");
3053         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3054                "entire bundle in window!");
3055         (void)SD;
3056         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3057       }
3058 
3059       for (auto *SD : ReadyInsts) {
3060         assert(SD->isSchedulingEntity() && SD->isReady() &&
3061                "item in ready list not ready?");
3062         (void)SD;
3063       }
3064     }
3065 
3066     void doForAllOpcodes(Value *V,
3067                          function_ref<void(ScheduleData *SD)> Action) {
3068       if (ScheduleData *SD = getScheduleData(V))
3069         Action(SD);
3070       auto I = ExtraScheduleDataMap.find(V);
3071       if (I != ExtraScheduleDataMap.end())
3072         for (auto &P : I->second)
3073           if (isInSchedulingRegion(P.second))
3074             Action(P.second);
3075     }
3076 
3077     /// Put all instructions into the ReadyList which are ready for scheduling.
3078     template <typename ReadyListType>
3079     void initialFillReadyList(ReadyListType &ReadyList) {
3080       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3081         doForAllOpcodes(I, [&](ScheduleData *SD) {
3082           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3083               SD->isReady()) {
3084             ReadyList.insert(SD);
3085             LLVM_DEBUG(dbgs()
3086                        << "SLP:    initially in ready list: " << *SD << "\n");
3087           }
3088         });
3089       }
3090     }
3091 
3092     /// Build a bundle from the ScheduleData nodes corresponding to the
3093     /// scalar instruction for each lane.
3094     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3095 
3096     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3097     /// cyclic dependencies. This is only a dry-run, no instructions are
3098     /// actually moved at this stage.
3099     /// \returns the scheduling bundle. The returned Optional value is non-None
3100     /// if \p VL is allowed to be scheduled.
3101     Optional<ScheduleData *>
3102     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3103                       const InstructionsState &S);
3104 
3105     /// Un-bundles a group of instructions.
3106     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3107 
3108     /// Allocates schedule data chunk.
3109     ScheduleData *allocateScheduleDataChunks();
3110 
3111     /// Extends the scheduling region so that V is inside the region.
3112     /// \returns true if the region size is within the limit.
3113     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3114 
3115     /// Initialize the ScheduleData structures for new instructions in the
3116     /// scheduling region.
3117     void initScheduleData(Instruction *FromI, Instruction *ToI,
3118                           ScheduleData *PrevLoadStore,
3119                           ScheduleData *NextLoadStore);
3120 
3121     /// Updates the dependency information of a bundle and of all instructions/
3122     /// bundles which depend on the original bundle.
3123     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3124                                BoUpSLP *SLP);
3125 
3126     /// Sets all instruction in the scheduling region to un-scheduled.
3127     void resetSchedule();
3128 
3129     BasicBlock *BB;
3130 
3131     /// Simple memory allocation for ScheduleData.
3132     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3133 
3134     /// The size of a ScheduleData array in ScheduleDataChunks.
3135     int ChunkSize;
3136 
3137     /// The allocator position in the current chunk, which is the last entry
3138     /// of ScheduleDataChunks.
3139     int ChunkPos;
3140 
3141     /// Attaches ScheduleData to Instruction.
3142     /// Note that the mapping survives during all vectorization iterations, i.e.
3143     /// ScheduleData structures are recycled.
3144     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3145 
3146     /// Attaches ScheduleData to Instruction with the leading key.
3147     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3148         ExtraScheduleDataMap;
3149 
3150     /// The ready-list for scheduling (only used for the dry-run).
3151     SetVector<ScheduleData *> ReadyInsts;
3152 
3153     /// The first instruction of the scheduling region.
3154     Instruction *ScheduleStart = nullptr;
3155 
3156     /// The first instruction _after_ the scheduling region.
3157     Instruction *ScheduleEnd = nullptr;
3158 
3159     /// The first memory accessing instruction in the scheduling region
3160     /// (can be null).
3161     ScheduleData *FirstLoadStoreInRegion = nullptr;
3162 
3163     /// The last memory accessing instruction in the scheduling region
3164     /// (can be null).
3165     ScheduleData *LastLoadStoreInRegion = nullptr;
3166 
3167     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3168     /// region?  Used to optimize the dependence calculation for the
3169     /// common case where there isn't.
3170     bool RegionHasStackSave = false;
3171 
3172     /// The current size of the scheduling region.
3173     int ScheduleRegionSize = 0;
3174 
3175     /// The maximum size allowed for the scheduling region.
3176     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3177 
3178     /// The ID of the scheduling region. For a new vectorization iteration this
3179     /// is incremented which "removes" all ScheduleData from the region.
3180     /// Make sure that the initial SchedulingRegionID is greater than the
3181     /// initial SchedulingRegionID in ScheduleData (which is 0).
3182     int SchedulingRegionID = 1;
3183   };
3184 
3185   /// Attaches the BlockScheduling structures to basic blocks.
3186   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3187 
3188   /// Performs the "real" scheduling. Done before vectorization is actually
3189   /// performed in a basic block.
3190   void scheduleBlock(BlockScheduling *BS);
3191 
3192   /// List of users to ignore during scheduling and that don't need extracting.
3193   ArrayRef<Value *> UserIgnoreList;
3194 
3195   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3196   /// sorted SmallVectors of unsigned.
3197   struct OrdersTypeDenseMapInfo {
3198     static OrdersType getEmptyKey() {
3199       OrdersType V;
3200       V.push_back(~1U);
3201       return V;
3202     }
3203 
3204     static OrdersType getTombstoneKey() {
3205       OrdersType V;
3206       V.push_back(~2U);
3207       return V;
3208     }
3209 
3210     static unsigned getHashValue(const OrdersType &V) {
3211       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3212     }
3213 
3214     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3215       return LHS == RHS;
3216     }
3217   };
3218 
3219   // Analysis and block reference.
3220   Function *F;
3221   ScalarEvolution *SE;
3222   TargetTransformInfo *TTI;
3223   TargetLibraryInfo *TLI;
3224   LoopInfo *LI;
3225   DominatorTree *DT;
3226   AssumptionCache *AC;
3227   DemandedBits *DB;
3228   const DataLayout *DL;
3229   OptimizationRemarkEmitter *ORE;
3230 
3231   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3232   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3233 
3234   /// Instruction builder to construct the vectorized tree.
3235   IRBuilder<> Builder;
3236 
3237   /// A map of scalar integer values to the smallest bit width with which they
3238   /// can legally be represented. The values map to (width, signed) pairs,
3239   /// where "width" indicates the minimum bit width and "signed" is True if the
3240   /// value must be signed-extended, rather than zero-extended, back to its
3241   /// original width.
3242   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3243 };
3244 
3245 } // end namespace slpvectorizer
3246 
3247 template <> struct GraphTraits<BoUpSLP *> {
3248   using TreeEntry = BoUpSLP::TreeEntry;
3249 
3250   /// NodeRef has to be a pointer per the GraphWriter.
3251   using NodeRef = TreeEntry *;
3252 
3253   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3254 
3255   /// Add the VectorizableTree to the index iterator to be able to return
3256   /// TreeEntry pointers.
3257   struct ChildIteratorType
3258       : public iterator_adaptor_base<
3259             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3260     ContainerTy &VectorizableTree;
3261 
3262     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3263                       ContainerTy &VT)
3264         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3265 
3266     NodeRef operator*() { return I->UserTE; }
3267   };
3268 
3269   static NodeRef getEntryNode(BoUpSLP &R) {
3270     return R.VectorizableTree[0].get();
3271   }
3272 
3273   static ChildIteratorType child_begin(NodeRef N) {
3274     return {N->UserTreeIndices.begin(), N->Container};
3275   }
3276 
3277   static ChildIteratorType child_end(NodeRef N) {
3278     return {N->UserTreeIndices.end(), N->Container};
3279   }
3280 
3281   /// For the node iterator we just need to turn the TreeEntry iterator into a
3282   /// TreeEntry* iterator so that it dereferences to NodeRef.
3283   class nodes_iterator {
3284     using ItTy = ContainerTy::iterator;
3285     ItTy It;
3286 
3287   public:
3288     nodes_iterator(const ItTy &It2) : It(It2) {}
3289     NodeRef operator*() { return It->get(); }
3290     nodes_iterator operator++() {
3291       ++It;
3292       return *this;
3293     }
3294     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3295   };
3296 
3297   static nodes_iterator nodes_begin(BoUpSLP *R) {
3298     return nodes_iterator(R->VectorizableTree.begin());
3299   }
3300 
3301   static nodes_iterator nodes_end(BoUpSLP *R) {
3302     return nodes_iterator(R->VectorizableTree.end());
3303   }
3304 
3305   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3306 };
3307 
3308 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3309   using TreeEntry = BoUpSLP::TreeEntry;
3310 
3311   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3312 
3313   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3314     std::string Str;
3315     raw_string_ostream OS(Str);
3316     if (isSplat(Entry->Scalars))
3317       OS << "<splat> ";
3318     for (auto V : Entry->Scalars) {
3319       OS << *V;
3320       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3321             return EU.Scalar == V;
3322           }))
3323         OS << " <extract>";
3324       OS << "\n";
3325     }
3326     return Str;
3327   }
3328 
3329   static std::string getNodeAttributes(const TreeEntry *Entry,
3330                                        const BoUpSLP *) {
3331     if (Entry->State == TreeEntry::NeedToGather)
3332       return "color=red";
3333     return "";
3334   }
3335 };
3336 
3337 } // end namespace llvm
3338 
3339 BoUpSLP::~BoUpSLP() {
3340   SmallVector<WeakTrackingVH> DeadInsts;
3341   for (auto *I : DeletedInstructions) {
3342     for (Use &U : I->operands()) {
3343       auto *Op = dyn_cast<Instruction>(U.get());
3344       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3345           wouldInstructionBeTriviallyDead(Op, TLI))
3346         DeadInsts.emplace_back(Op);
3347     }
3348     I->dropAllReferences();
3349   }
3350   for (auto *I : DeletedInstructions) {
3351     assert(I->use_empty() &&
3352            "trying to erase instruction with users.");
3353     I->eraseFromParent();
3354   }
3355 
3356   // Cleanup any dead scalar code feeding the vectorized instructions
3357   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3358 
3359 #ifdef EXPENSIVE_CHECKS
3360   // If we could guarantee that this call is not extremely slow, we could
3361   // remove the ifdef limitation (see PR47712).
3362   assert(!verifyFunction(*F, &dbgs()));
3363 #endif
3364 }
3365 
3366 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3367 /// contains original mask for the scalars reused in the node. Procedure
3368 /// transform this mask in accordance with the given \p Mask.
3369 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3370   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3371          "Expected non-empty mask.");
3372   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3373   Prev.swap(Reuses);
3374   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3375     if (Mask[I] != UndefMaskElem)
3376       Reuses[Mask[I]] = Prev[I];
3377 }
3378 
3379 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3380 /// the original order of the scalars. Procedure transforms the provided order
3381 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3382 /// identity order, \p Order is cleared.
3383 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3384   assert(!Mask.empty() && "Expected non-empty mask.");
3385   SmallVector<int> MaskOrder;
3386   if (Order.empty()) {
3387     MaskOrder.resize(Mask.size());
3388     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3389   } else {
3390     inversePermutation(Order, MaskOrder);
3391   }
3392   reorderReuses(MaskOrder, Mask);
3393   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3394     Order.clear();
3395     return;
3396   }
3397   Order.assign(Mask.size(), Mask.size());
3398   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3399     if (MaskOrder[I] != UndefMaskElem)
3400       Order[MaskOrder[I]] = I;
3401   fixupOrderingIndices(Order);
3402 }
3403 
3404 Optional<BoUpSLP::OrdersType>
3405 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3406   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3407   unsigned NumScalars = TE.Scalars.size();
3408   OrdersType CurrentOrder(NumScalars, NumScalars);
3409   SmallVector<int> Positions;
3410   SmallBitVector UsedPositions(NumScalars);
3411   const TreeEntry *STE = nullptr;
3412   // Try to find all gathered scalars that are gets vectorized in other
3413   // vectorize node. Here we can have only one single tree vector node to
3414   // correctly identify order of the gathered scalars.
3415   for (unsigned I = 0; I < NumScalars; ++I) {
3416     Value *V = TE.Scalars[I];
3417     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3418       continue;
3419     if (const auto *LocalSTE = getTreeEntry(V)) {
3420       if (!STE)
3421         STE = LocalSTE;
3422       else if (STE != LocalSTE)
3423         // Take the order only from the single vector node.
3424         return None;
3425       unsigned Lane =
3426           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3427       if (Lane >= NumScalars)
3428         return None;
3429       if (CurrentOrder[Lane] != NumScalars) {
3430         if (Lane != I)
3431           continue;
3432         UsedPositions.reset(CurrentOrder[Lane]);
3433       }
3434       // The partial identity (where only some elements of the gather node are
3435       // in the identity order) is good.
3436       CurrentOrder[Lane] = I;
3437       UsedPositions.set(I);
3438     }
3439   }
3440   // Need to keep the order if we have a vector entry and at least 2 scalars or
3441   // the vectorized entry has just 2 scalars.
3442   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3443     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3444       for (unsigned I = 0; I < NumScalars; ++I)
3445         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3446           return false;
3447       return true;
3448     };
3449     if (IsIdentityOrder(CurrentOrder)) {
3450       CurrentOrder.clear();
3451       return CurrentOrder;
3452     }
3453     auto *It = CurrentOrder.begin();
3454     for (unsigned I = 0; I < NumScalars;) {
3455       if (UsedPositions.test(I)) {
3456         ++I;
3457         continue;
3458       }
3459       if (*It == NumScalars) {
3460         *It = I;
3461         ++I;
3462       }
3463       ++It;
3464     }
3465     return CurrentOrder;
3466   }
3467   return None;
3468 }
3469 
3470 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3471                             const DataLayout &DL, ScalarEvolution &SE,
3472                             SmallVectorImpl<unsigned> &SortedIndices) {
3473   assert(llvm::all_of(
3474              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3475          "Expected list of pointer operands.");
3476   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3477   // Ptr into, sort and return the sorted indices with values next to one
3478   // another.
3479   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3480   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3481 
3482   unsigned Cnt = 1;
3483   for (Value *Ptr : VL.drop_front()) {
3484     bool Found = any_of(Bases, [&](auto &Base) {
3485       Optional<int> Diff =
3486           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3487                           /*StrictCheck=*/true);
3488       if (!Diff)
3489         return false;
3490 
3491       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3492       return true;
3493     });
3494 
3495     if (!Found) {
3496       // If we haven't found enough to usefully cluster, return early.
3497       if (Bases.size() > VL.size() / 2 - 1)
3498         return false;
3499 
3500       // Not found already - add a new Base
3501       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3502     }
3503   }
3504 
3505   // For each of the bases sort the pointers by Offset and check if any of the
3506   // base become consecutively allocated.
3507   bool AnyConsecutive = false;
3508   for (auto &Base : Bases) {
3509     auto &Vec = Base.second;
3510     if (Vec.size() > 1) {
3511       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3512                                 const std::tuple<Value *, int, unsigned> &Y) {
3513         return std::get<1>(X) < std::get<1>(Y);
3514       });
3515       int InitialOffset = std::get<1>(Vec[0]);
3516       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3517         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3518       });
3519     }
3520   }
3521 
3522   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3523   SortedIndices.clear();
3524   if (!AnyConsecutive)
3525     return false;
3526 
3527   for (auto &Base : Bases) {
3528     for (auto &T : Base.second)
3529       SortedIndices.push_back(std::get<2>(T));
3530   }
3531 
3532   assert(SortedIndices.size() == VL.size() &&
3533          "Expected SortedIndices to be the size of VL");
3534   return true;
3535 }
3536 
3537 Optional<BoUpSLP::OrdersType>
3538 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3539   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3540   Type *ScalarTy = TE.Scalars[0]->getType();
3541 
3542   SmallVector<Value *> Ptrs;
3543   Ptrs.reserve(TE.Scalars.size());
3544   for (Value *V : TE.Scalars) {
3545     auto *L = dyn_cast<LoadInst>(V);
3546     if (!L || !L->isSimple())
3547       return None;
3548     Ptrs.push_back(L->getPointerOperand());
3549   }
3550 
3551   BoUpSLP::OrdersType Order;
3552   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3553     return Order;
3554   return None;
3555 }
3556 
3557 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3558                                                          bool TopToBottom) {
3559   // No need to reorder if need to shuffle reuses, still need to shuffle the
3560   // node.
3561   if (!TE.ReuseShuffleIndices.empty())
3562     return None;
3563   if (TE.State == TreeEntry::Vectorize &&
3564       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3565        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3566       !TE.isAltShuffle())
3567     return TE.ReorderIndices;
3568   if (TE.State == TreeEntry::NeedToGather) {
3569     // TODO: add analysis of other gather nodes with extractelement
3570     // instructions and other values/instructions, not only undefs.
3571     if (((TE.getOpcode() == Instruction::ExtractElement &&
3572           !TE.isAltShuffle()) ||
3573          (all_of(TE.Scalars,
3574                  [](Value *V) {
3575                    return isa<UndefValue, ExtractElementInst>(V);
3576                  }) &&
3577           any_of(TE.Scalars,
3578                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3579         all_of(TE.Scalars,
3580                [](Value *V) {
3581                  auto *EE = dyn_cast<ExtractElementInst>(V);
3582                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3583                }) &&
3584         allSameType(TE.Scalars)) {
3585       // Check that gather of extractelements can be represented as
3586       // just a shuffle of a single vector.
3587       OrdersType CurrentOrder;
3588       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3589       if (Reuse || !CurrentOrder.empty()) {
3590         if (!CurrentOrder.empty())
3591           fixupOrderingIndices(CurrentOrder);
3592         return CurrentOrder;
3593       }
3594     }
3595     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3596       return CurrentOrder;
3597     if (TE.Scalars.size() >= 4)
3598       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3599         return Order;
3600   }
3601   return None;
3602 }
3603 
3604 void BoUpSLP::reorderTopToBottom() {
3605   // Maps VF to the graph nodes.
3606   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3607   // ExtractElement gather nodes which can be vectorized and need to handle
3608   // their ordering.
3609   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3610 
3611   // Maps a TreeEntry to the reorder indices of external users.
3612   DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
3613       ExternalUserReorderMap;
3614   // Find all reorderable nodes with the given VF.
3615   // Currently the are vectorized stores,loads,extracts + some gathering of
3616   // extracts.
3617   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders,
3618                               &ExternalUserReorderMap](
3619                                  const std::unique_ptr<TreeEntry> &TE) {
3620     // Look for external users that will probably be vectorized.
3621     SmallVector<OrdersType, 1> ExternalUserReorderIndices =
3622         findExternalStoreUsersReorderIndices(TE.get());
3623     if (!ExternalUserReorderIndices.empty()) {
3624       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3625       ExternalUserReorderMap.try_emplace(TE.get(),
3626                                          std::move(ExternalUserReorderIndices));
3627     }
3628 
3629     if (Optional<OrdersType> CurrentOrder =
3630             getReorderingData(*TE, /*TopToBottom=*/true)) {
3631       // Do not include ordering for nodes used in the alt opcode vectorization,
3632       // better to reorder them during bottom-to-top stage. If follow the order
3633       // here, it causes reordering of the whole graph though actually it is
3634       // profitable just to reorder the subgraph that starts from the alternate
3635       // opcode vectorization node. Such nodes already end-up with the shuffle
3636       // instruction and it is just enough to change this shuffle rather than
3637       // rotate the scalars for the whole graph.
3638       unsigned Cnt = 0;
3639       const TreeEntry *UserTE = TE.get();
3640       while (UserTE && Cnt < RecursionMaxDepth) {
3641         if (UserTE->UserTreeIndices.size() != 1)
3642           break;
3643         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3644               return EI.UserTE->State == TreeEntry::Vectorize &&
3645                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3646             }))
3647           return;
3648         if (UserTE->UserTreeIndices.empty())
3649           UserTE = nullptr;
3650         else
3651           UserTE = UserTE->UserTreeIndices.back().UserTE;
3652         ++Cnt;
3653       }
3654       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3655       if (TE->State != TreeEntry::Vectorize)
3656         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3657     }
3658   });
3659 
3660   // Reorder the graph nodes according to their vectorization factor.
3661   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3662        VF /= 2) {
3663     auto It = VFToOrderedEntries.find(VF);
3664     if (It == VFToOrderedEntries.end())
3665       continue;
3666     // Try to find the most profitable order. We just are looking for the most
3667     // used order and reorder scalar elements in the nodes according to this
3668     // mostly used order.
3669     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3670     // All operands are reordered and used only in this node - propagate the
3671     // most used order to the user node.
3672     MapVector<OrdersType, unsigned,
3673               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3674         OrdersUses;
3675     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3676     for (const TreeEntry *OpTE : OrderedEntries) {
3677       // No need to reorder this nodes, still need to extend and to use shuffle,
3678       // just need to merge reordering shuffle and the reuse shuffle.
3679       if (!OpTE->ReuseShuffleIndices.empty())
3680         continue;
3681       // Count number of orders uses.
3682       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3683         if (OpTE->State == TreeEntry::NeedToGather) {
3684           auto It = GathersToOrders.find(OpTE);
3685           if (It != GathersToOrders.end())
3686             return It->second;
3687         }
3688         return OpTE->ReorderIndices;
3689       }();
3690       // First consider the order of the external scalar users.
3691       auto It = ExternalUserReorderMap.find(OpTE);
3692       if (It != ExternalUserReorderMap.end()) {
3693         const auto &ExternalUserReorderIndices = It->second;
3694         for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
3695           ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
3696         // No other useful reorder data in this entry.
3697         if (Order.empty())
3698           continue;
3699       }
3700       // Stores actually store the mask, not the order, need to invert.
3701       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3702           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3703         SmallVector<int> Mask;
3704         inversePermutation(Order, Mask);
3705         unsigned E = Order.size();
3706         OrdersType CurrentOrder(E, E);
3707         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3708           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3709         });
3710         fixupOrderingIndices(CurrentOrder);
3711         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3712       } else {
3713         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3714       }
3715     }
3716     // Set order of the user node.
3717     if (OrdersUses.empty())
3718       continue;
3719     // Choose the most used order.
3720     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3721     unsigned Cnt = OrdersUses.front().second;
3722     for (const auto &Pair : drop_begin(OrdersUses)) {
3723       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3724         BestOrder = Pair.first;
3725         Cnt = Pair.second;
3726       }
3727     }
3728     // Set order of the user node.
3729     if (BestOrder.empty())
3730       continue;
3731     SmallVector<int> Mask;
3732     inversePermutation(BestOrder, Mask);
3733     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3734     unsigned E = BestOrder.size();
3735     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3736       return I < E ? static_cast<int>(I) : UndefMaskElem;
3737     });
3738     // Do an actual reordering, if profitable.
3739     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3740       // Just do the reordering for the nodes with the given VF.
3741       if (TE->Scalars.size() != VF) {
3742         if (TE->ReuseShuffleIndices.size() == VF) {
3743           // Need to reorder the reuses masks of the operands with smaller VF to
3744           // be able to find the match between the graph nodes and scalar
3745           // operands of the given node during vectorization/cost estimation.
3746           assert(all_of(TE->UserTreeIndices,
3747                         [VF, &TE](const EdgeInfo &EI) {
3748                           return EI.UserTE->Scalars.size() == VF ||
3749                                  EI.UserTE->Scalars.size() ==
3750                                      TE->Scalars.size();
3751                         }) &&
3752                  "All users must be of VF size.");
3753           // Update ordering of the operands with the smaller VF than the given
3754           // one.
3755           reorderReuses(TE->ReuseShuffleIndices, Mask);
3756         }
3757         continue;
3758       }
3759       if (TE->State == TreeEntry::Vectorize &&
3760           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3761               InsertElementInst>(TE->getMainOp()) &&
3762           !TE->isAltShuffle()) {
3763         // Build correct orders for extract{element,value}, loads and
3764         // stores.
3765         reorderOrder(TE->ReorderIndices, Mask);
3766         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3767           TE->reorderOperands(Mask);
3768       } else {
3769         // Reorder the node and its operands.
3770         TE->reorderOperands(Mask);
3771         assert(TE->ReorderIndices.empty() &&
3772                "Expected empty reorder sequence.");
3773         reorderScalars(TE->Scalars, Mask);
3774       }
3775       if (!TE->ReuseShuffleIndices.empty()) {
3776         // Apply reversed order to keep the original ordering of the reused
3777         // elements to avoid extra reorder indices shuffling.
3778         OrdersType CurrentOrder;
3779         reorderOrder(CurrentOrder, MaskOrder);
3780         SmallVector<int> NewReuses;
3781         inversePermutation(CurrentOrder, NewReuses);
3782         addMask(NewReuses, TE->ReuseShuffleIndices);
3783         TE->ReuseShuffleIndices.swap(NewReuses);
3784       }
3785     }
3786   }
3787 }
3788 
3789 bool BoUpSLP::canReorderOperands(
3790     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3791     ArrayRef<TreeEntry *> ReorderableGathers,
3792     SmallVectorImpl<TreeEntry *> &GatherOps) {
3793   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3794     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3795           return OpData.first == I &&
3796                  OpData.second->State == TreeEntry::Vectorize;
3797         }))
3798       continue;
3799     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3800       // Do not reorder if operand node is used by many user nodes.
3801       if (any_of(TE->UserTreeIndices,
3802                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3803         return false;
3804       // Add the node to the list of the ordered nodes with the identity
3805       // order.
3806       Edges.emplace_back(I, TE);
3807       continue;
3808     }
3809     ArrayRef<Value *> VL = UserTE->getOperand(I);
3810     TreeEntry *Gather = nullptr;
3811     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3812           assert(TE->State != TreeEntry::Vectorize &&
3813                  "Only non-vectorized nodes are expected.");
3814           if (TE->isSame(VL)) {
3815             Gather = TE;
3816             return true;
3817           }
3818           return false;
3819         }) > 1)
3820       return false;
3821     if (Gather)
3822       GatherOps.push_back(Gather);
3823   }
3824   return true;
3825 }
3826 
3827 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3828   SetVector<TreeEntry *> OrderedEntries;
3829   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3830   // Find all reorderable leaf nodes with the given VF.
3831   // Currently the are vectorized loads,extracts without alternate operands +
3832   // some gathering of extracts.
3833   SmallVector<TreeEntry *> NonVectorized;
3834   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3835                               &NonVectorized](
3836                                  const std::unique_ptr<TreeEntry> &TE) {
3837     if (TE->State != TreeEntry::Vectorize)
3838       NonVectorized.push_back(TE.get());
3839     if (Optional<OrdersType> CurrentOrder =
3840             getReorderingData(*TE, /*TopToBottom=*/false)) {
3841       OrderedEntries.insert(TE.get());
3842       if (TE->State != TreeEntry::Vectorize)
3843         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3844     }
3845   });
3846 
3847   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3848   // I.e., if the node has operands, that are reordered, try to make at least
3849   // one operand order in the natural order and reorder others + reorder the
3850   // user node itself.
3851   SmallPtrSet<const TreeEntry *, 4> Visited;
3852   while (!OrderedEntries.empty()) {
3853     // 1. Filter out only reordered nodes.
3854     // 2. If the entry has multiple uses - skip it and jump to the next node.
3855     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3856     SmallVector<TreeEntry *> Filtered;
3857     for (TreeEntry *TE : OrderedEntries) {
3858       if (!(TE->State == TreeEntry::Vectorize ||
3859             (TE->State == TreeEntry::NeedToGather &&
3860              GathersToOrders.count(TE))) ||
3861           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3862           !all_of(drop_begin(TE->UserTreeIndices),
3863                   [TE](const EdgeInfo &EI) {
3864                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3865                   }) ||
3866           !Visited.insert(TE).second) {
3867         Filtered.push_back(TE);
3868         continue;
3869       }
3870       // Build a map between user nodes and their operands order to speedup
3871       // search. The graph currently does not provide this dependency directly.
3872       for (EdgeInfo &EI : TE->UserTreeIndices) {
3873         TreeEntry *UserTE = EI.UserTE;
3874         auto It = Users.find(UserTE);
3875         if (It == Users.end())
3876           It = Users.insert({UserTE, {}}).first;
3877         It->second.emplace_back(EI.EdgeIdx, TE);
3878       }
3879     }
3880     // Erase filtered entries.
3881     for_each(Filtered,
3882              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3883     for (auto &Data : Users) {
3884       // Check that operands are used only in the User node.
3885       SmallVector<TreeEntry *> GatherOps;
3886       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3887                               GatherOps)) {
3888         for_each(Data.second,
3889                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3890                    OrderedEntries.remove(Op.second);
3891                  });
3892         continue;
3893       }
3894       // All operands are reordered and used only in this node - propagate the
3895       // most used order to the user node.
3896       MapVector<OrdersType, unsigned,
3897                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3898           OrdersUses;
3899       // Do the analysis for each tree entry only once, otherwise the order of
3900       // the same node my be considered several times, though might be not
3901       // profitable.
3902       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3903       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3904       for (const auto &Op : Data.second) {
3905         TreeEntry *OpTE = Op.second;
3906         if (!VisitedOps.insert(OpTE).second)
3907           continue;
3908         if (!OpTE->ReuseShuffleIndices.empty() ||
3909             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3910           continue;
3911         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3912           if (OpTE->State == TreeEntry::NeedToGather)
3913             return GathersToOrders.find(OpTE)->second;
3914           return OpTE->ReorderIndices;
3915         }();
3916         unsigned NumOps = count_if(
3917             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3918               return P.second == OpTE;
3919             });
3920         // Stores actually store the mask, not the order, need to invert.
3921         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3922             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3923           SmallVector<int> Mask;
3924           inversePermutation(Order, Mask);
3925           unsigned E = Order.size();
3926           OrdersType CurrentOrder(E, E);
3927           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3928             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3929           });
3930           fixupOrderingIndices(CurrentOrder);
3931           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3932               NumOps;
3933         } else {
3934           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3935         }
3936         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3937         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3938                                             const TreeEntry *TE) {
3939           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3940               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3941               (IgnoreReorder && TE->Idx == 0))
3942             return true;
3943           if (TE->State == TreeEntry::NeedToGather) {
3944             auto It = GathersToOrders.find(TE);
3945             if (It != GathersToOrders.end())
3946               return !It->second.empty();
3947             return true;
3948           }
3949           return false;
3950         };
3951         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3952           TreeEntry *UserTE = EI.UserTE;
3953           if (!VisitedUsers.insert(UserTE).second)
3954             continue;
3955           // May reorder user node if it requires reordering, has reused
3956           // scalars, is an alternate op vectorize node or its op nodes require
3957           // reordering.
3958           if (AllowsReordering(UserTE))
3959             continue;
3960           // Check if users allow reordering.
3961           // Currently look up just 1 level of operands to avoid increase of
3962           // the compile time.
3963           // Profitable to reorder if definitely more operands allow
3964           // reordering rather than those with natural order.
3965           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3966           if (static_cast<unsigned>(count_if(
3967                   Ops, [UserTE, &AllowsReordering](
3968                            const std::pair<unsigned, TreeEntry *> &Op) {
3969                     return AllowsReordering(Op.second) &&
3970                            all_of(Op.second->UserTreeIndices,
3971                                   [UserTE](const EdgeInfo &EI) {
3972                                     return EI.UserTE == UserTE;
3973                                   });
3974                   })) <= Ops.size() / 2)
3975             ++Res.first->second;
3976         }
3977       }
3978       // If no orders - skip current nodes and jump to the next one, if any.
3979       if (OrdersUses.empty()) {
3980         for_each(Data.second,
3981                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3982                    OrderedEntries.remove(Op.second);
3983                  });
3984         continue;
3985       }
3986       // Choose the best order.
3987       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3988       unsigned Cnt = OrdersUses.front().second;
3989       for (const auto &Pair : drop_begin(OrdersUses)) {
3990         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3991           BestOrder = Pair.first;
3992           Cnt = Pair.second;
3993         }
3994       }
3995       // Set order of the user node (reordering of operands and user nodes).
3996       if (BestOrder.empty()) {
3997         for_each(Data.second,
3998                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3999                    OrderedEntries.remove(Op.second);
4000                  });
4001         continue;
4002       }
4003       // Erase operands from OrderedEntries list and adjust their orders.
4004       VisitedOps.clear();
4005       SmallVector<int> Mask;
4006       inversePermutation(BestOrder, Mask);
4007       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4008       unsigned E = BestOrder.size();
4009       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4010         return I < E ? static_cast<int>(I) : UndefMaskElem;
4011       });
4012       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4013         TreeEntry *TE = Op.second;
4014         OrderedEntries.remove(TE);
4015         if (!VisitedOps.insert(TE).second)
4016           continue;
4017         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4018           // Just reorder reuses indices.
4019           reorderReuses(TE->ReuseShuffleIndices, Mask);
4020           continue;
4021         }
4022         // Gathers are processed separately.
4023         if (TE->State != TreeEntry::Vectorize)
4024           continue;
4025         assert((BestOrder.size() == TE->ReorderIndices.size() ||
4026                 TE->ReorderIndices.empty()) &&
4027                "Non-matching sizes of user/operand entries.");
4028         reorderOrder(TE->ReorderIndices, Mask);
4029       }
4030       // For gathers just need to reorder its scalars.
4031       for (TreeEntry *Gather : GatherOps) {
4032         assert(Gather->ReorderIndices.empty() &&
4033                "Unexpected reordering of gathers.");
4034         if (!Gather->ReuseShuffleIndices.empty()) {
4035           // Just reorder reuses indices.
4036           reorderReuses(Gather->ReuseShuffleIndices, Mask);
4037           continue;
4038         }
4039         reorderScalars(Gather->Scalars, Mask);
4040         OrderedEntries.remove(Gather);
4041       }
4042       // Reorder operands of the user node and set the ordering for the user
4043       // node itself.
4044       if (Data.first->State != TreeEntry::Vectorize ||
4045           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4046               Data.first->getMainOp()) ||
4047           Data.first->isAltShuffle())
4048         Data.first->reorderOperands(Mask);
4049       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4050           Data.first->isAltShuffle()) {
4051         reorderScalars(Data.first->Scalars, Mask);
4052         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4053         if (Data.first->ReuseShuffleIndices.empty() &&
4054             !Data.first->ReorderIndices.empty() &&
4055             !Data.first->isAltShuffle()) {
4056           // Insert user node to the list to try to sink reordering deeper in
4057           // the graph.
4058           OrderedEntries.insert(Data.first);
4059         }
4060       } else {
4061         reorderOrder(Data.first->ReorderIndices, Mask);
4062       }
4063     }
4064   }
4065   // If the reordering is unnecessary, just remove the reorder.
4066   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4067       VectorizableTree.front()->ReuseShuffleIndices.empty())
4068     VectorizableTree.front()->ReorderIndices.clear();
4069 }
4070 
4071 void BoUpSLP::buildExternalUses(
4072     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4073   // Collect the values that we need to extract from the tree.
4074   for (auto &TEPtr : VectorizableTree) {
4075     TreeEntry *Entry = TEPtr.get();
4076 
4077     // No need to handle users of gathered values.
4078     if (Entry->State == TreeEntry::NeedToGather)
4079       continue;
4080 
4081     // For each lane:
4082     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4083       Value *Scalar = Entry->Scalars[Lane];
4084       int FoundLane = Entry->findLaneForValue(Scalar);
4085 
4086       // Check if the scalar is externally used as an extra arg.
4087       auto ExtI = ExternallyUsedValues.find(Scalar);
4088       if (ExtI != ExternallyUsedValues.end()) {
4089         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4090                           << Lane << " from " << *Scalar << ".\n");
4091         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4092       }
4093       for (User *U : Scalar->users()) {
4094         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4095 
4096         Instruction *UserInst = dyn_cast<Instruction>(U);
4097         if (!UserInst)
4098           continue;
4099 
4100         if (isDeleted(UserInst))
4101           continue;
4102 
4103         // Skip in-tree scalars that become vectors
4104         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4105           Value *UseScalar = UseEntry->Scalars[0];
4106           // Some in-tree scalars will remain as scalar in vectorized
4107           // instructions. If that is the case, the one in Lane 0 will
4108           // be used.
4109           if (UseScalar != U ||
4110               UseEntry->State == TreeEntry::ScatterVectorize ||
4111               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4112             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4113                               << ".\n");
4114             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4115             continue;
4116           }
4117         }
4118 
4119         // Ignore users in the user ignore list.
4120         if (is_contained(UserIgnoreList, UserInst))
4121           continue;
4122 
4123         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4124                           << Lane << " from " << *Scalar << ".\n");
4125         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4126       }
4127     }
4128   }
4129 }
4130 
4131 DenseMap<Value *, SmallVector<StoreInst *, 4>>
4132 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4133   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4134   for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4135     Value *V = TE->Scalars[Lane];
4136     // To save compilation time we don't visit if we have too many users.
4137     static constexpr unsigned UsersLimit = 4;
4138     if (V->hasNUsesOrMore(UsersLimit))
4139       break;
4140 
4141     // Collect stores per pointer object.
4142     for (User *U : V->users()) {
4143       auto *SI = dyn_cast<StoreInst>(U);
4144       if (SI == nullptr || !SI->isSimple() ||
4145           !isValidElementType(SI->getValueOperand()->getType()))
4146         continue;
4147       // Skip entry if already
4148       if (getTreeEntry(U))
4149         continue;
4150 
4151       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4152       auto &StoresVec = PtrToStoresMap[Ptr];
4153       // For now just keep one store per pointer object per lane.
4154       // TODO: Extend this to support multiple stores per pointer per lane
4155       if (StoresVec.size() > Lane)
4156         continue;
4157       // Skip if in different BBs.
4158       if (!StoresVec.empty() &&
4159           SI->getParent() != StoresVec.back()->getParent())
4160         continue;
4161       // Make sure that the stores are of the same type.
4162       if (!StoresVec.empty() &&
4163           SI->getValueOperand()->getType() !=
4164               StoresVec.back()->getValueOperand()->getType())
4165         continue;
4166       StoresVec.push_back(SI);
4167     }
4168   }
4169   return PtrToStoresMap;
4170 }
4171 
4172 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4173                             OrdersType &ReorderIndices) const {
4174   // We check whether the stores in StoreVec can form a vector by sorting them
4175   // and checking whether they are consecutive.
4176 
4177   // To avoid calling getPointersDiff() while sorting we create a vector of
4178   // pairs {store, offset from first} and sort this instead.
4179   SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4180   StoreInst *S0 = StoresVec[0];
4181   StoreOffsetVec[0] = {S0, 0};
4182   Type *S0Ty = S0->getValueOperand()->getType();
4183   Value *S0Ptr = S0->getPointerOperand();
4184   for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4185     StoreInst *SI = StoresVec[Idx];
4186     Optional<int> Diff =
4187         getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4188                         SI->getPointerOperand(), *DL, *SE,
4189                         /*StrictCheck=*/true);
4190     // We failed to compare the pointers so just abandon this StoresVec.
4191     if (!Diff)
4192       return false;
4193     StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4194   }
4195 
4196   // Sort the vector based on the pointers. We create a copy because we may
4197   // need the original later for calculating the reorder (shuffle) indices.
4198   stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4199                                  const std::pair<StoreInst *, int> &Pair2) {
4200     int Offset1 = Pair1.second;
4201     int Offset2 = Pair2.second;
4202     return Offset1 < Offset2;
4203   });
4204 
4205   // Check if the stores are consecutive by checking if last-first == size-1.
4206   int LastOffset = StoreOffsetVec.back().second;
4207   int FirstOffset = StoreOffsetVec.front().second;
4208   if (LastOffset - FirstOffset != (int)StoreOffsetVec.size() - 1)
4209     return false;
4210 
4211   // Calculate the shuffle indices according to their offset against the sorted
4212   // StoreOffsetVec.
4213   ReorderIndices.reserve(StoresVec.size());
4214   for (StoreInst *SI : StoresVec) {
4215     unsigned Idx = find_if(StoreOffsetVec,
4216                            [SI](const std::pair<StoreInst *, int> &Pair) {
4217                              return Pair.first == SI;
4218                            }) -
4219                    StoreOffsetVec.begin();
4220     ReorderIndices.push_back(Idx);
4221   }
4222   // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4223   // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4224   // same convention here.
4225   auto IsIdentityOrder = [](const OrdersType &Order) {
4226     for (unsigned Idx : seq<unsigned>(0, Order.size()))
4227       if (Idx != Order[Idx])
4228         return false;
4229     return true;
4230   };
4231   if (IsIdentityOrder(ReorderIndices))
4232     ReorderIndices.clear();
4233 
4234   return true;
4235 }
4236 
4237 #ifndef NDEBUG
4238 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4239   for (unsigned Idx : Order)
4240     dbgs() << Idx << ", ";
4241   dbgs() << "\n";
4242 }
4243 #endif
4244 
4245 SmallVector<BoUpSLP::OrdersType, 1>
4246 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4247   unsigned NumLanes = TE->Scalars.size();
4248 
4249   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
4250       collectUserStores(TE);
4251 
4252   // Holds the reorder indices for each candidate store vector that is a user of
4253   // the current TreeEntry.
4254   SmallVector<OrdersType, 1> ExternalReorderIndices;
4255 
4256   // Now inspect the stores collected per pointer and look for vectorization
4257   // candidates. For each candidate calculate the reorder index vector and push
4258   // it into `ExternalReorderIndices`
4259   for (const auto &Pair : PtrToStoresMap) {
4260     auto &StoresVec = Pair.second;
4261     // If we have fewer than NumLanes stores, then we can't form a vector.
4262     if (StoresVec.size() != NumLanes)
4263       continue;
4264 
4265     // If the stores are not consecutive then abandon this StoresVec.
4266     OrdersType ReorderIndices;
4267     if (!CanFormVector(StoresVec, ReorderIndices))
4268       continue;
4269 
4270     // We now know that the scalars in StoresVec can form a vector instruction,
4271     // so set the reorder indices.
4272     ExternalReorderIndices.push_back(ReorderIndices);
4273   }
4274   return ExternalReorderIndices;
4275 }
4276 
4277 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4278                         ArrayRef<Value *> UserIgnoreLst) {
4279   deleteTree();
4280   UserIgnoreList = UserIgnoreLst;
4281   if (!allSameType(Roots))
4282     return;
4283   buildTree_rec(Roots, 0, EdgeInfo());
4284 }
4285 
4286 namespace {
4287 /// Tracks the state we can represent the loads in the given sequence.
4288 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4289 } // anonymous namespace
4290 
4291 /// Checks if the given array of loads can be represented as a vectorized,
4292 /// scatter or just simple gather.
4293 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4294                                     const TargetTransformInfo &TTI,
4295                                     const DataLayout &DL, ScalarEvolution &SE,
4296                                     SmallVectorImpl<unsigned> &Order,
4297                                     SmallVectorImpl<Value *> &PointerOps) {
4298   // Check that a vectorized load would load the same memory as a scalar
4299   // load. For example, we don't want to vectorize loads that are smaller
4300   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4301   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4302   // from such a struct, we read/write packed bits disagreeing with the
4303   // unvectorized version.
4304   Type *ScalarTy = VL0->getType();
4305 
4306   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4307     return LoadsState::Gather;
4308 
4309   // Make sure all loads in the bundle are simple - we can't vectorize
4310   // atomic or volatile loads.
4311   PointerOps.clear();
4312   PointerOps.resize(VL.size());
4313   auto *POIter = PointerOps.begin();
4314   for (Value *V : VL) {
4315     auto *L = cast<LoadInst>(V);
4316     if (!L->isSimple())
4317       return LoadsState::Gather;
4318     *POIter = L->getPointerOperand();
4319     ++POIter;
4320   }
4321 
4322   Order.clear();
4323   // Check the order of pointer operands.
4324   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4325     Value *Ptr0;
4326     Value *PtrN;
4327     if (Order.empty()) {
4328       Ptr0 = PointerOps.front();
4329       PtrN = PointerOps.back();
4330     } else {
4331       Ptr0 = PointerOps[Order.front()];
4332       PtrN = PointerOps[Order.back()];
4333     }
4334     Optional<int> Diff =
4335         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4336     // Check that the sorted loads are consecutive.
4337     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4338       return LoadsState::Vectorize;
4339     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4340     for (Value *V : VL)
4341       CommonAlignment =
4342           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4343     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4344                                 CommonAlignment))
4345       return LoadsState::ScatterVectorize;
4346   }
4347 
4348   return LoadsState::Gather;
4349 }
4350 
4351 /// \return true if the specified list of values has only one instruction that
4352 /// requires scheduling, false otherwise.
4353 #ifndef NDEBUG
4354 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4355   Value *NeedsScheduling = nullptr;
4356   for (Value *V : VL) {
4357     if (doesNotNeedToBeScheduled(V))
4358       continue;
4359     if (!NeedsScheduling) {
4360       NeedsScheduling = V;
4361       continue;
4362     }
4363     return false;
4364   }
4365   return NeedsScheduling;
4366 }
4367 #endif
4368 
4369 /// Generates key/subkey pair for the given value to provide effective sorting
4370 /// of the values and better detection of the vectorizable values sequences. The
4371 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4372 /// and in values subgroups (subkeys).
4373 static std::pair<size_t, size_t> generateKeySubkey(
4374     Value *V, const TargetLibraryInfo *TLI,
4375     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4376     bool AllowAlternate) {
4377   hash_code Key = hash_value(V->getValueID() + 2);
4378   hash_code SubKey = hash_value(0);
4379   // Sort the loads by the distance between the pointers.
4380   if (auto *LI = dyn_cast<LoadInst>(V)) {
4381     Key = hash_combine(hash_value(Instruction::Load), Key);
4382     if (LI->isSimple())
4383       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4384     else
4385       SubKey = hash_value(LI);
4386   } else if (isVectorLikeInstWithConstOps(V)) {
4387     // Sort extracts by the vector operands.
4388     if (isa<ExtractElementInst, UndefValue>(V))
4389       Key = hash_value(Value::UndefValueVal + 1);
4390     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4391       if (!isUndefVector(EI->getVectorOperand()) &&
4392           !isa<UndefValue>(EI->getIndexOperand()))
4393         SubKey = hash_value(EI->getVectorOperand());
4394     }
4395   } else if (auto *I = dyn_cast<Instruction>(V)) {
4396     // Sort other instructions just by the opcodes except for CMPInst.
4397     // For CMP also sort by the predicate kind.
4398     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4399         isValidForAlternation(I->getOpcode())) {
4400       if (AllowAlternate)
4401         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4402       else
4403         Key = hash_combine(hash_value(I->getOpcode()), Key);
4404       SubKey = hash_combine(
4405           hash_value(I->getOpcode()), hash_value(I->getType()),
4406           hash_value(isa<BinaryOperator>(I)
4407                          ? I->getType()
4408                          : cast<CastInst>(I)->getOperand(0)->getType()));
4409     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4410       CmpInst::Predicate Pred = CI->getPredicate();
4411       if (CI->isCommutative())
4412         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4413       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4414       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4415                             hash_value(SwapPred),
4416                             hash_value(CI->getOperand(0)->getType()));
4417     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4418       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4419       if (isTriviallyVectorizable(ID))
4420         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4421       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4422         SubKey = hash_combine(hash_value(I->getOpcode()),
4423                               hash_value(Call->getCalledFunction()));
4424       else
4425         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4426       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4427         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4428                               hash_value(Op.Tag), SubKey);
4429     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4430       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4431         SubKey = hash_value(Gep->getPointerOperand());
4432       else
4433         SubKey = hash_value(Gep);
4434     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4435                !isa<ConstantInt>(I->getOperand(1))) {
4436       // Do not try to vectorize instructions with potentially high cost.
4437       SubKey = hash_value(I);
4438     } else {
4439       SubKey = hash_value(I->getOpcode());
4440     }
4441     Key = hash_combine(hash_value(I->getParent()), Key);
4442   }
4443   return std::make_pair(Key, SubKey);
4444 }
4445 
4446 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4447                             const EdgeInfo &UserTreeIdx) {
4448   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4449 
4450   SmallVector<int> ReuseShuffleIndicies;
4451   SmallVector<Value *> UniqueValues;
4452   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4453                                 &UserTreeIdx,
4454                                 this](const InstructionsState &S) {
4455     // Check that every instruction appears once in this bundle.
4456     DenseMap<Value *, unsigned> UniquePositions;
4457     for (Value *V : VL) {
4458       if (isConstant(V)) {
4459         ReuseShuffleIndicies.emplace_back(
4460             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4461         UniqueValues.emplace_back(V);
4462         continue;
4463       }
4464       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4465       ReuseShuffleIndicies.emplace_back(Res.first->second);
4466       if (Res.second)
4467         UniqueValues.emplace_back(V);
4468     }
4469     size_t NumUniqueScalarValues = UniqueValues.size();
4470     if (NumUniqueScalarValues == VL.size()) {
4471       ReuseShuffleIndicies.clear();
4472     } else {
4473       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4474       if (NumUniqueScalarValues <= 1 ||
4475           (UniquePositions.size() == 1 && all_of(UniqueValues,
4476                                                  [](Value *V) {
4477                                                    return isa<UndefValue>(V) ||
4478                                                           !isConstant(V);
4479                                                  })) ||
4480           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4481         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4482         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4483         return false;
4484       }
4485       VL = UniqueValues;
4486     }
4487     return true;
4488   };
4489 
4490   InstructionsState S = getSameOpcode(VL);
4491   if (Depth == RecursionMaxDepth) {
4492     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4493     if (TryToFindDuplicates(S))
4494       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4495                    ReuseShuffleIndicies);
4496     return;
4497   }
4498 
4499   // Don't handle scalable vectors
4500   if (S.getOpcode() == Instruction::ExtractElement &&
4501       isa<ScalableVectorType>(
4502           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4503     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4504     if (TryToFindDuplicates(S))
4505       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4506                    ReuseShuffleIndicies);
4507     return;
4508   }
4509 
4510   // Don't handle vectors.
4511   if (S.OpValue->getType()->isVectorTy() &&
4512       !isa<InsertElementInst>(S.OpValue)) {
4513     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4514     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4515     return;
4516   }
4517 
4518   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4519     if (SI->getValueOperand()->getType()->isVectorTy()) {
4520       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4521       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4522       return;
4523     }
4524 
4525   // If all of the operands are identical or constant we have a simple solution.
4526   // If we deal with insert/extract instructions, they all must have constant
4527   // indices, otherwise we should gather them, not try to vectorize.
4528   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4529       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4530        !all_of(VL, isVectorLikeInstWithConstOps))) {
4531     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4532     if (TryToFindDuplicates(S))
4533       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4534                    ReuseShuffleIndicies);
4535     return;
4536   }
4537 
4538   // We now know that this is a vector of instructions of the same type from
4539   // the same block.
4540 
4541   // Don't vectorize ephemeral values.
4542   for (Value *V : VL) {
4543     if (EphValues.count(V)) {
4544       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4545                         << ") is ephemeral.\n");
4546       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4547       return;
4548     }
4549   }
4550 
4551   // Check if this is a duplicate of another entry.
4552   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4553     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4554     if (!E->isSame(VL)) {
4555       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4556       if (TryToFindDuplicates(S))
4557         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4558                      ReuseShuffleIndicies);
4559       return;
4560     }
4561     // Record the reuse of the tree node.  FIXME, currently this is only used to
4562     // properly draw the graph rather than for the actual vectorization.
4563     E->UserTreeIndices.push_back(UserTreeIdx);
4564     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4565                       << ".\n");
4566     return;
4567   }
4568 
4569   // Check that none of the instructions in the bundle are already in the tree.
4570   for (Value *V : VL) {
4571     auto *I = dyn_cast<Instruction>(V);
4572     if (!I)
4573       continue;
4574     if (getTreeEntry(I)) {
4575       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4576                         << ") is already in tree.\n");
4577       if (TryToFindDuplicates(S))
4578         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4579                      ReuseShuffleIndicies);
4580       return;
4581     }
4582   }
4583 
4584   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4585   for (Value *V : VL) {
4586     if (is_contained(UserIgnoreList, V)) {
4587       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4588       if (TryToFindDuplicates(S))
4589         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4590                      ReuseShuffleIndicies);
4591       return;
4592     }
4593   }
4594 
4595   // Check that all of the users of the scalars that we want to vectorize are
4596   // schedulable.
4597   auto *VL0 = cast<Instruction>(S.OpValue);
4598   BasicBlock *BB = VL0->getParent();
4599 
4600   if (!DT->isReachableFromEntry(BB)) {
4601     // Don't go into unreachable blocks. They may contain instructions with
4602     // dependency cycles which confuse the final scheduling.
4603     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4604     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4605     return;
4606   }
4607 
4608   // Check that every instruction appears once in this bundle.
4609   if (!TryToFindDuplicates(S))
4610     return;
4611 
4612   auto &BSRef = BlocksSchedules[BB];
4613   if (!BSRef)
4614     BSRef = std::make_unique<BlockScheduling>(BB);
4615 
4616   BlockScheduling &BS = *BSRef;
4617 
4618   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4619 #ifdef EXPENSIVE_CHECKS
4620   // Make sure we didn't break any internal invariants
4621   BS.verify();
4622 #endif
4623   if (!Bundle) {
4624     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4625     assert((!BS.getScheduleData(VL0) ||
4626             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4627            "tryScheduleBundle should cancelScheduling on failure");
4628     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4629                  ReuseShuffleIndicies);
4630     return;
4631   }
4632   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4633 
4634   unsigned ShuffleOrOp = S.isAltShuffle() ?
4635                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4636   switch (ShuffleOrOp) {
4637     case Instruction::PHI: {
4638       auto *PH = cast<PHINode>(VL0);
4639 
4640       // Check for terminator values (e.g. invoke).
4641       for (Value *V : VL)
4642         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4643           Instruction *Term = dyn_cast<Instruction>(Incoming);
4644           if (Term && Term->isTerminator()) {
4645             LLVM_DEBUG(dbgs()
4646                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4647             BS.cancelScheduling(VL, VL0);
4648             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4649                          ReuseShuffleIndicies);
4650             return;
4651           }
4652         }
4653 
4654       TreeEntry *TE =
4655           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4656       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4657 
4658       // Keeps the reordered operands to avoid code duplication.
4659       SmallVector<ValueList, 2> OperandsVec;
4660       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4661         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4662           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4663           TE->setOperand(I, Operands);
4664           OperandsVec.push_back(Operands);
4665           continue;
4666         }
4667         ValueList Operands;
4668         // Prepare the operand vector.
4669         for (Value *V : VL)
4670           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4671               PH->getIncomingBlock(I)));
4672         TE->setOperand(I, Operands);
4673         OperandsVec.push_back(Operands);
4674       }
4675       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4676         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4677       return;
4678     }
4679     case Instruction::ExtractValue:
4680     case Instruction::ExtractElement: {
4681       OrdersType CurrentOrder;
4682       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4683       if (Reuse) {
4684         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4685         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4686                      ReuseShuffleIndicies);
4687         // This is a special case, as it does not gather, but at the same time
4688         // we are not extending buildTree_rec() towards the operands.
4689         ValueList Op0;
4690         Op0.assign(VL.size(), VL0->getOperand(0));
4691         VectorizableTree.back()->setOperand(0, Op0);
4692         return;
4693       }
4694       if (!CurrentOrder.empty()) {
4695         LLVM_DEBUG({
4696           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4697                     "with order";
4698           for (unsigned Idx : CurrentOrder)
4699             dbgs() << " " << Idx;
4700           dbgs() << "\n";
4701         });
4702         fixupOrderingIndices(CurrentOrder);
4703         // Insert new order with initial value 0, if it does not exist,
4704         // otherwise return the iterator to the existing one.
4705         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4706                      ReuseShuffleIndicies, CurrentOrder);
4707         // This is a special case, as it does not gather, but at the same time
4708         // we are not extending buildTree_rec() towards the operands.
4709         ValueList Op0;
4710         Op0.assign(VL.size(), VL0->getOperand(0));
4711         VectorizableTree.back()->setOperand(0, Op0);
4712         return;
4713       }
4714       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4715       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4716                    ReuseShuffleIndicies);
4717       BS.cancelScheduling(VL, VL0);
4718       return;
4719     }
4720     case Instruction::InsertElement: {
4721       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4722 
4723       // Check that we have a buildvector and not a shuffle of 2 or more
4724       // different vectors.
4725       ValueSet SourceVectors;
4726       for (Value *V : VL) {
4727         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4728         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4729       }
4730 
4731       if (count_if(VL, [&SourceVectors](Value *V) {
4732             return !SourceVectors.contains(V);
4733           }) >= 2) {
4734         // Found 2nd source vector - cancel.
4735         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4736                              "different source vectors.\n");
4737         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4738         BS.cancelScheduling(VL, VL0);
4739         return;
4740       }
4741 
4742       auto OrdCompare = [](const std::pair<int, int> &P1,
4743                            const std::pair<int, int> &P2) {
4744         return P1.first > P2.first;
4745       };
4746       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4747                     decltype(OrdCompare)>
4748           Indices(OrdCompare);
4749       for (int I = 0, E = VL.size(); I < E; ++I) {
4750         unsigned Idx = *getInsertIndex(VL[I]);
4751         Indices.emplace(Idx, I);
4752       }
4753       OrdersType CurrentOrder(VL.size(), VL.size());
4754       bool IsIdentity = true;
4755       for (int I = 0, E = VL.size(); I < E; ++I) {
4756         CurrentOrder[Indices.top().second] = I;
4757         IsIdentity &= Indices.top().second == I;
4758         Indices.pop();
4759       }
4760       if (IsIdentity)
4761         CurrentOrder.clear();
4762       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4763                                    None, CurrentOrder);
4764       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4765 
4766       constexpr int NumOps = 2;
4767       ValueList VectorOperands[NumOps];
4768       for (int I = 0; I < NumOps; ++I) {
4769         for (Value *V : VL)
4770           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4771 
4772         TE->setOperand(I, VectorOperands[I]);
4773       }
4774       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4775       return;
4776     }
4777     case Instruction::Load: {
4778       // Check that a vectorized load would load the same memory as a scalar
4779       // load. For example, we don't want to vectorize loads that are smaller
4780       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4781       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4782       // from such a struct, we read/write packed bits disagreeing with the
4783       // unvectorized version.
4784       SmallVector<Value *> PointerOps;
4785       OrdersType CurrentOrder;
4786       TreeEntry *TE = nullptr;
4787       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4788                                 PointerOps)) {
4789       case LoadsState::Vectorize:
4790         if (CurrentOrder.empty()) {
4791           // Original loads are consecutive and does not require reordering.
4792           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4793                             ReuseShuffleIndicies);
4794           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4795         } else {
4796           fixupOrderingIndices(CurrentOrder);
4797           // Need to reorder.
4798           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4799                             ReuseShuffleIndicies, CurrentOrder);
4800           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4801         }
4802         TE->setOperandsInOrder();
4803         break;
4804       case LoadsState::ScatterVectorize:
4805         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4806         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4807                           UserTreeIdx, ReuseShuffleIndicies);
4808         TE->setOperandsInOrder();
4809         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4810         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4811         break;
4812       case LoadsState::Gather:
4813         BS.cancelScheduling(VL, VL0);
4814         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4815                      ReuseShuffleIndicies);
4816 #ifndef NDEBUG
4817         Type *ScalarTy = VL0->getType();
4818         if (DL->getTypeSizeInBits(ScalarTy) !=
4819             DL->getTypeAllocSizeInBits(ScalarTy))
4820           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4821         else if (any_of(VL, [](Value *V) {
4822                    return !cast<LoadInst>(V)->isSimple();
4823                  }))
4824           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4825         else
4826           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4827 #endif // NDEBUG
4828         break;
4829       }
4830       return;
4831     }
4832     case Instruction::ZExt:
4833     case Instruction::SExt:
4834     case Instruction::FPToUI:
4835     case Instruction::FPToSI:
4836     case Instruction::FPExt:
4837     case Instruction::PtrToInt:
4838     case Instruction::IntToPtr:
4839     case Instruction::SIToFP:
4840     case Instruction::UIToFP:
4841     case Instruction::Trunc:
4842     case Instruction::FPTrunc:
4843     case Instruction::BitCast: {
4844       Type *SrcTy = VL0->getOperand(0)->getType();
4845       for (Value *V : VL) {
4846         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4847         if (Ty != SrcTy || !isValidElementType(Ty)) {
4848           BS.cancelScheduling(VL, VL0);
4849           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4850                        ReuseShuffleIndicies);
4851           LLVM_DEBUG(dbgs()
4852                      << "SLP: Gathering casts with different src types.\n");
4853           return;
4854         }
4855       }
4856       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4857                                    ReuseShuffleIndicies);
4858       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4859 
4860       TE->setOperandsInOrder();
4861       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4862         ValueList Operands;
4863         // Prepare the operand vector.
4864         for (Value *V : VL)
4865           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4866 
4867         buildTree_rec(Operands, Depth + 1, {TE, i});
4868       }
4869       return;
4870     }
4871     case Instruction::ICmp:
4872     case Instruction::FCmp: {
4873       // Check that all of the compares have the same predicate.
4874       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4875       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4876       Type *ComparedTy = VL0->getOperand(0)->getType();
4877       for (Value *V : VL) {
4878         CmpInst *Cmp = cast<CmpInst>(V);
4879         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4880             Cmp->getOperand(0)->getType() != ComparedTy) {
4881           BS.cancelScheduling(VL, VL0);
4882           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4883                        ReuseShuffleIndicies);
4884           LLVM_DEBUG(dbgs()
4885                      << "SLP: Gathering cmp with different predicate.\n");
4886           return;
4887         }
4888       }
4889 
4890       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4891                                    ReuseShuffleIndicies);
4892       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4893 
4894       ValueList Left, Right;
4895       if (cast<CmpInst>(VL0)->isCommutative()) {
4896         // Commutative predicate - collect + sort operands of the instructions
4897         // so that each side is more likely to have the same opcode.
4898         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4899         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4900       } else {
4901         // Collect operands - commute if it uses the swapped predicate.
4902         for (Value *V : VL) {
4903           auto *Cmp = cast<CmpInst>(V);
4904           Value *LHS = Cmp->getOperand(0);
4905           Value *RHS = Cmp->getOperand(1);
4906           if (Cmp->getPredicate() != P0)
4907             std::swap(LHS, RHS);
4908           Left.push_back(LHS);
4909           Right.push_back(RHS);
4910         }
4911       }
4912       TE->setOperand(0, Left);
4913       TE->setOperand(1, Right);
4914       buildTree_rec(Left, Depth + 1, {TE, 0});
4915       buildTree_rec(Right, Depth + 1, {TE, 1});
4916       return;
4917     }
4918     case Instruction::Select:
4919     case Instruction::FNeg:
4920     case Instruction::Add:
4921     case Instruction::FAdd:
4922     case Instruction::Sub:
4923     case Instruction::FSub:
4924     case Instruction::Mul:
4925     case Instruction::FMul:
4926     case Instruction::UDiv:
4927     case Instruction::SDiv:
4928     case Instruction::FDiv:
4929     case Instruction::URem:
4930     case Instruction::SRem:
4931     case Instruction::FRem:
4932     case Instruction::Shl:
4933     case Instruction::LShr:
4934     case Instruction::AShr:
4935     case Instruction::And:
4936     case Instruction::Or:
4937     case Instruction::Xor: {
4938       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4939                                    ReuseShuffleIndicies);
4940       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4941 
4942       // Sort operands of the instructions so that each side is more likely to
4943       // have the same opcode.
4944       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4945         ValueList Left, Right;
4946         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4947         TE->setOperand(0, Left);
4948         TE->setOperand(1, Right);
4949         buildTree_rec(Left, Depth + 1, {TE, 0});
4950         buildTree_rec(Right, Depth + 1, {TE, 1});
4951         return;
4952       }
4953 
4954       TE->setOperandsInOrder();
4955       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4956         ValueList Operands;
4957         // Prepare the operand vector.
4958         for (Value *V : VL)
4959           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4960 
4961         buildTree_rec(Operands, Depth + 1, {TE, i});
4962       }
4963       return;
4964     }
4965     case Instruction::GetElementPtr: {
4966       // We don't combine GEPs with complicated (nested) indexing.
4967       for (Value *V : VL) {
4968         if (cast<Instruction>(V)->getNumOperands() != 2) {
4969           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4970           BS.cancelScheduling(VL, VL0);
4971           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4972                        ReuseShuffleIndicies);
4973           return;
4974         }
4975       }
4976 
4977       // We can't combine several GEPs into one vector if they operate on
4978       // different types.
4979       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4980       for (Value *V : VL) {
4981         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4982         if (Ty0 != CurTy) {
4983           LLVM_DEBUG(dbgs()
4984                      << "SLP: not-vectorizable GEP (different types).\n");
4985           BS.cancelScheduling(VL, VL0);
4986           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4987                        ReuseShuffleIndicies);
4988           return;
4989         }
4990       }
4991 
4992       // We don't combine GEPs with non-constant indexes.
4993       Type *Ty1 = VL0->getOperand(1)->getType();
4994       for (Value *V : VL) {
4995         auto Op = cast<Instruction>(V)->getOperand(1);
4996         if (!isa<ConstantInt>(Op) ||
4997             (Op->getType() != Ty1 &&
4998              Op->getType()->getScalarSizeInBits() >
4999                  DL->getIndexSizeInBits(
5000                      V->getType()->getPointerAddressSpace()))) {
5001           LLVM_DEBUG(dbgs()
5002                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
5003           BS.cancelScheduling(VL, VL0);
5004           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5005                        ReuseShuffleIndicies);
5006           return;
5007         }
5008       }
5009 
5010       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5011                                    ReuseShuffleIndicies);
5012       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
5013       SmallVector<ValueList, 2> Operands(2);
5014       // Prepare the operand vector for pointer operands.
5015       for (Value *V : VL)
5016         Operands.front().push_back(
5017             cast<GetElementPtrInst>(V)->getPointerOperand());
5018       TE->setOperand(0, Operands.front());
5019       // Need to cast all indices to the same type before vectorization to
5020       // avoid crash.
5021       // Required to be able to find correct matches between different gather
5022       // nodes and reuse the vectorized values rather than trying to gather them
5023       // again.
5024       int IndexIdx = 1;
5025       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5026       Type *Ty = all_of(VL,
5027                         [VL0Ty, IndexIdx](Value *V) {
5028                           return VL0Ty == cast<GetElementPtrInst>(V)
5029                                               ->getOperand(IndexIdx)
5030                                               ->getType();
5031                         })
5032                      ? VL0Ty
5033                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5034                                             ->getPointerOperandType()
5035                                             ->getScalarType());
5036       // Prepare the operand vector.
5037       for (Value *V : VL) {
5038         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
5039         auto *CI = cast<ConstantInt>(Op);
5040         Operands.back().push_back(ConstantExpr::getIntegerCast(
5041             CI, Ty, CI->getValue().isSignBitSet()));
5042       }
5043       TE->setOperand(IndexIdx, Operands.back());
5044 
5045       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5046         buildTree_rec(Operands[I], Depth + 1, {TE, I});
5047       return;
5048     }
5049     case Instruction::Store: {
5050       // Check if the stores are consecutive or if we need to swizzle them.
5051       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5052       // Avoid types that are padded when being allocated as scalars, while
5053       // being packed together in a vector (such as i1).
5054       if (DL->getTypeSizeInBits(ScalarTy) !=
5055           DL->getTypeAllocSizeInBits(ScalarTy)) {
5056         BS.cancelScheduling(VL, VL0);
5057         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5058                      ReuseShuffleIndicies);
5059         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
5060         return;
5061       }
5062       // Make sure all stores in the bundle are simple - we can't vectorize
5063       // atomic or volatile stores.
5064       SmallVector<Value *, 4> PointerOps(VL.size());
5065       ValueList Operands(VL.size());
5066       auto POIter = PointerOps.begin();
5067       auto OIter = Operands.begin();
5068       for (Value *V : VL) {
5069         auto *SI = cast<StoreInst>(V);
5070         if (!SI->isSimple()) {
5071           BS.cancelScheduling(VL, VL0);
5072           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5073                        ReuseShuffleIndicies);
5074           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
5075           return;
5076         }
5077         *POIter = SI->getPointerOperand();
5078         *OIter = SI->getValueOperand();
5079         ++POIter;
5080         ++OIter;
5081       }
5082 
5083       OrdersType CurrentOrder;
5084       // Check the order of pointer operands.
5085       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5086         Value *Ptr0;
5087         Value *PtrN;
5088         if (CurrentOrder.empty()) {
5089           Ptr0 = PointerOps.front();
5090           PtrN = PointerOps.back();
5091         } else {
5092           Ptr0 = PointerOps[CurrentOrder.front()];
5093           PtrN = PointerOps[CurrentOrder.back()];
5094         }
5095         Optional<int> Dist =
5096             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5097         // Check that the sorted pointer operands are consecutive.
5098         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5099           if (CurrentOrder.empty()) {
5100             // Original stores are consecutive and does not require reordering.
5101             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5102                                          UserTreeIdx, ReuseShuffleIndicies);
5103             TE->setOperandsInOrder();
5104             buildTree_rec(Operands, Depth + 1, {TE, 0});
5105             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
5106           } else {
5107             fixupOrderingIndices(CurrentOrder);
5108             TreeEntry *TE =
5109                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5110                              ReuseShuffleIndicies, CurrentOrder);
5111             TE->setOperandsInOrder();
5112             buildTree_rec(Operands, Depth + 1, {TE, 0});
5113             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
5114           }
5115           return;
5116         }
5117       }
5118 
5119       BS.cancelScheduling(VL, VL0);
5120       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5121                    ReuseShuffleIndicies);
5122       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
5123       return;
5124     }
5125     case Instruction::Call: {
5126       // Check if the calls are all to the same vectorizable intrinsic or
5127       // library function.
5128       CallInst *CI = cast<CallInst>(VL0);
5129       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5130 
5131       VFShape Shape = VFShape::get(
5132           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5133           false /*HasGlobalPred*/);
5134       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5135 
5136       if (!VecFunc && !isTriviallyVectorizable(ID)) {
5137         BS.cancelScheduling(VL, VL0);
5138         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5139                      ReuseShuffleIndicies);
5140         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
5141         return;
5142       }
5143       Function *F = CI->getCalledFunction();
5144       unsigned NumArgs = CI->arg_size();
5145       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
5146       for (unsigned j = 0; j != NumArgs; ++j)
5147         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
5148           ScalarArgs[j] = CI->getArgOperand(j);
5149       for (Value *V : VL) {
5150         CallInst *CI2 = dyn_cast<CallInst>(V);
5151         if (!CI2 || CI2->getCalledFunction() != F ||
5152             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
5153             (VecFunc &&
5154              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
5155             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
5156           BS.cancelScheduling(VL, VL0);
5157           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5158                        ReuseShuffleIndicies);
5159           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
5160                             << "\n");
5161           return;
5162         }
5163         // Some intrinsics have scalar arguments and should be same in order for
5164         // them to be vectorized.
5165         for (unsigned j = 0; j != NumArgs; ++j) {
5166           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
5167             Value *A1J = CI2->getArgOperand(j);
5168             if (ScalarArgs[j] != A1J) {
5169               BS.cancelScheduling(VL, VL0);
5170               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5171                            ReuseShuffleIndicies);
5172               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
5173                                 << " argument " << ScalarArgs[j] << "!=" << A1J
5174                                 << "\n");
5175               return;
5176             }
5177           }
5178         }
5179         // Verify that the bundle operands are identical between the two calls.
5180         if (CI->hasOperandBundles() &&
5181             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
5182                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
5183                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
5184           BS.cancelScheduling(VL, VL0);
5185           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5186                        ReuseShuffleIndicies);
5187           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
5188                             << *CI << "!=" << *V << '\n');
5189           return;
5190         }
5191       }
5192 
5193       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5194                                    ReuseShuffleIndicies);
5195       TE->setOperandsInOrder();
5196       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5197         // For scalar operands no need to to create an entry since no need to
5198         // vectorize it.
5199         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5200           continue;
5201         ValueList Operands;
5202         // Prepare the operand vector.
5203         for (Value *V : VL) {
5204           auto *CI2 = cast<CallInst>(V);
5205           Operands.push_back(CI2->getArgOperand(i));
5206         }
5207         buildTree_rec(Operands, Depth + 1, {TE, i});
5208       }
5209       return;
5210     }
5211     case Instruction::ShuffleVector: {
5212       // If this is not an alternate sequence of opcode like add-sub
5213       // then do not vectorize this instruction.
5214       if (!S.isAltShuffle()) {
5215         BS.cancelScheduling(VL, VL0);
5216         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5217                      ReuseShuffleIndicies);
5218         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5219         return;
5220       }
5221       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5222                                    ReuseShuffleIndicies);
5223       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5224 
5225       // Reorder operands if reordering would enable vectorization.
5226       auto *CI = dyn_cast<CmpInst>(VL0);
5227       if (isa<BinaryOperator>(VL0) || CI) {
5228         ValueList Left, Right;
5229         if (!CI || all_of(VL, [](Value *V) {
5230               return cast<CmpInst>(V)->isCommutative();
5231             })) {
5232           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5233         } else {
5234           CmpInst::Predicate P0 = CI->getPredicate();
5235           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5236           assert(P0 != AltP0 &&
5237                  "Expected different main/alternate predicates.");
5238           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5239           Value *BaseOp0 = VL0->getOperand(0);
5240           Value *BaseOp1 = VL0->getOperand(1);
5241           // Collect operands - commute if it uses the swapped predicate or
5242           // alternate operation.
5243           for (Value *V : VL) {
5244             auto *Cmp = cast<CmpInst>(V);
5245             Value *LHS = Cmp->getOperand(0);
5246             Value *RHS = Cmp->getOperand(1);
5247             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5248             if (P0 == AltP0Swapped) {
5249               if (CI != Cmp && S.AltOp != Cmp &&
5250                   ((P0 == CurrentPred &&
5251                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5252                    (AltP0 == CurrentPred &&
5253                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5254                 std::swap(LHS, RHS);
5255             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5256               std::swap(LHS, RHS);
5257             }
5258             Left.push_back(LHS);
5259             Right.push_back(RHS);
5260           }
5261         }
5262         TE->setOperand(0, Left);
5263         TE->setOperand(1, Right);
5264         buildTree_rec(Left, Depth + 1, {TE, 0});
5265         buildTree_rec(Right, Depth + 1, {TE, 1});
5266         return;
5267       }
5268 
5269       TE->setOperandsInOrder();
5270       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5271         ValueList Operands;
5272         // Prepare the operand vector.
5273         for (Value *V : VL)
5274           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5275 
5276         buildTree_rec(Operands, Depth + 1, {TE, i});
5277       }
5278       return;
5279     }
5280     default:
5281       BS.cancelScheduling(VL, VL0);
5282       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5283                    ReuseShuffleIndicies);
5284       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5285       return;
5286   }
5287 }
5288 
5289 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5290   unsigned N = 1;
5291   Type *EltTy = T;
5292 
5293   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5294          isa<VectorType>(EltTy)) {
5295     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5296       // Check that struct is homogeneous.
5297       for (const auto *Ty : ST->elements())
5298         if (Ty != *ST->element_begin())
5299           return 0;
5300       N *= ST->getNumElements();
5301       EltTy = *ST->element_begin();
5302     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5303       N *= AT->getNumElements();
5304       EltTy = AT->getElementType();
5305     } else {
5306       auto *VT = cast<FixedVectorType>(EltTy);
5307       N *= VT->getNumElements();
5308       EltTy = VT->getElementType();
5309     }
5310   }
5311 
5312   if (!isValidElementType(EltTy))
5313     return 0;
5314   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5315   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5316     return 0;
5317   return N;
5318 }
5319 
5320 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5321                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5322   const auto *It = find_if(VL, [](Value *V) {
5323     return isa<ExtractElementInst, ExtractValueInst>(V);
5324   });
5325   assert(It != VL.end() && "Expected at least one extract instruction.");
5326   auto *E0 = cast<Instruction>(*It);
5327   assert(all_of(VL,
5328                 [](Value *V) {
5329                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5330                       V);
5331                 }) &&
5332          "Invalid opcode");
5333   // Check if all of the extracts come from the same vector and from the
5334   // correct offset.
5335   Value *Vec = E0->getOperand(0);
5336 
5337   CurrentOrder.clear();
5338 
5339   // We have to extract from a vector/aggregate with the same number of elements.
5340   unsigned NElts;
5341   if (E0->getOpcode() == Instruction::ExtractValue) {
5342     const DataLayout &DL = E0->getModule()->getDataLayout();
5343     NElts = canMapToVector(Vec->getType(), DL);
5344     if (!NElts)
5345       return false;
5346     // Check if load can be rewritten as load of vector.
5347     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5348     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5349       return false;
5350   } else {
5351     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5352   }
5353 
5354   if (NElts != VL.size())
5355     return false;
5356 
5357   // Check that all of the indices extract from the correct offset.
5358   bool ShouldKeepOrder = true;
5359   unsigned E = VL.size();
5360   // Assign to all items the initial value E + 1 so we can check if the extract
5361   // instruction index was used already.
5362   // Also, later we can check that all the indices are used and we have a
5363   // consecutive access in the extract instructions, by checking that no
5364   // element of CurrentOrder still has value E + 1.
5365   CurrentOrder.assign(E, E);
5366   unsigned I = 0;
5367   for (; I < E; ++I) {
5368     auto *Inst = dyn_cast<Instruction>(VL[I]);
5369     if (!Inst)
5370       continue;
5371     if (Inst->getOperand(0) != Vec)
5372       break;
5373     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5374       if (isa<UndefValue>(EE->getIndexOperand()))
5375         continue;
5376     Optional<unsigned> Idx = getExtractIndex(Inst);
5377     if (!Idx)
5378       break;
5379     const unsigned ExtIdx = *Idx;
5380     if (ExtIdx != I) {
5381       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5382         break;
5383       ShouldKeepOrder = false;
5384       CurrentOrder[ExtIdx] = I;
5385     } else {
5386       if (CurrentOrder[I] != E)
5387         break;
5388       CurrentOrder[I] = I;
5389     }
5390   }
5391   if (I < E) {
5392     CurrentOrder.clear();
5393     return false;
5394   }
5395   if (ShouldKeepOrder)
5396     CurrentOrder.clear();
5397 
5398   return ShouldKeepOrder;
5399 }
5400 
5401 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5402                                     ArrayRef<Value *> VectorizedVals) const {
5403   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5404          all_of(I->users(), [this](User *U) {
5405            return ScalarToTreeEntry.count(U) > 0 ||
5406                   isVectorLikeInstWithConstOps(U) ||
5407                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5408          });
5409 }
5410 
5411 static std::pair<InstructionCost, InstructionCost>
5412 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5413                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5414   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5415 
5416   // Calculate the cost of the scalar and vector calls.
5417   SmallVector<Type *, 4> VecTys;
5418   for (Use &Arg : CI->args())
5419     VecTys.push_back(
5420         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5421   FastMathFlags FMF;
5422   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5423     FMF = FPCI->getFastMathFlags();
5424   SmallVector<const Value *> Arguments(CI->args());
5425   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5426                                     dyn_cast<IntrinsicInst>(CI));
5427   auto IntrinsicCost =
5428     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5429 
5430   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5431                                      VecTy->getNumElements())),
5432                             false /*HasGlobalPred*/);
5433   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5434   auto LibCost = IntrinsicCost;
5435   if (!CI->isNoBuiltin() && VecFunc) {
5436     // Calculate the cost of the vector library call.
5437     // If the corresponding vector call is cheaper, return its cost.
5438     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5439                                     TTI::TCK_RecipThroughput);
5440   }
5441   return {IntrinsicCost, LibCost};
5442 }
5443 
5444 /// Compute the cost of creating a vector of type \p VecTy containing the
5445 /// extracted values from \p VL.
5446 static InstructionCost
5447 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5448                    TargetTransformInfo::ShuffleKind ShuffleKind,
5449                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5450   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5451 
5452   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5453       VecTy->getNumElements() < NumOfParts)
5454     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5455 
5456   bool AllConsecutive = true;
5457   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5458   unsigned Idx = -1;
5459   InstructionCost Cost = 0;
5460 
5461   // Process extracts in blocks of EltsPerVector to check if the source vector
5462   // operand can be re-used directly. If not, add the cost of creating a shuffle
5463   // to extract the values into a vector register.
5464   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5465   for (auto *V : VL) {
5466     ++Idx;
5467 
5468     // Need to exclude undefs from analysis.
5469     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5470       continue;
5471 
5472     // Reached the start of a new vector registers.
5473     if (Idx % EltsPerVector == 0) {
5474       RegMask.assign(EltsPerVector, UndefMaskElem);
5475       AllConsecutive = true;
5476       continue;
5477     }
5478 
5479     // Check all extracts for a vector register on the target directly
5480     // extract values in order.
5481     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5482     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5483       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5484       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5485                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5486       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5487     }
5488 
5489     if (AllConsecutive)
5490       continue;
5491 
5492     // Skip all indices, except for the last index per vector block.
5493     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5494       continue;
5495 
5496     // If we have a series of extracts which are not consecutive and hence
5497     // cannot re-use the source vector register directly, compute the shuffle
5498     // cost to extract the vector with EltsPerVector elements.
5499     Cost += TTI.getShuffleCost(
5500         TargetTransformInfo::SK_PermuteSingleSrc,
5501         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5502   }
5503   return Cost;
5504 }
5505 
5506 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5507 /// operations operands.
5508 static void
5509 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5510                       ArrayRef<int> ReusesIndices,
5511                       const function_ref<bool(Instruction *)> IsAltOp,
5512                       SmallVectorImpl<int> &Mask,
5513                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5514                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5515   unsigned Sz = VL.size();
5516   Mask.assign(Sz, UndefMaskElem);
5517   SmallVector<int> OrderMask;
5518   if (!ReorderIndices.empty())
5519     inversePermutation(ReorderIndices, OrderMask);
5520   for (unsigned I = 0; I < Sz; ++I) {
5521     unsigned Idx = I;
5522     if (!ReorderIndices.empty())
5523       Idx = OrderMask[I];
5524     auto *OpInst = cast<Instruction>(VL[Idx]);
5525     if (IsAltOp(OpInst)) {
5526       Mask[I] = Sz + Idx;
5527       if (AltScalars)
5528         AltScalars->push_back(OpInst);
5529     } else {
5530       Mask[I] = Idx;
5531       if (OpScalars)
5532         OpScalars->push_back(OpInst);
5533     }
5534   }
5535   if (!ReusesIndices.empty()) {
5536     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5537     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5538       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5539     });
5540     Mask.swap(NewMask);
5541   }
5542 }
5543 
5544 /// Checks if the specified instruction \p I is an alternate operation for the
5545 /// given \p MainOp and \p AltOp instructions.
5546 static bool isAlternateInstruction(const Instruction *I,
5547                                    const Instruction *MainOp,
5548                                    const Instruction *AltOp) {
5549   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5550     auto *AltCI0 = cast<CmpInst>(AltOp);
5551     auto *CI = cast<CmpInst>(I);
5552     CmpInst::Predicate P0 = CI0->getPredicate();
5553     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5554     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5555     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5556     CmpInst::Predicate CurrentPred = CI->getPredicate();
5557     if (P0 == AltP0Swapped)
5558       return I == AltCI0 ||
5559              (I != MainOp &&
5560               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5561                                    CI->getOperand(0), CI->getOperand(1)));
5562     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5563   }
5564   return I->getOpcode() == AltOp->getOpcode();
5565 }
5566 
5567 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5568                                       ArrayRef<Value *> VectorizedVals) {
5569   ArrayRef<Value*> VL = E->Scalars;
5570 
5571   Type *ScalarTy = VL[0]->getType();
5572   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5573     ScalarTy = SI->getValueOperand()->getType();
5574   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5575     ScalarTy = CI->getOperand(0)->getType();
5576   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5577     ScalarTy = IE->getOperand(1)->getType();
5578   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5579   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5580 
5581   // If we have computed a smaller type for the expression, update VecTy so
5582   // that the costs will be accurate.
5583   if (MinBWs.count(VL[0]))
5584     VecTy = FixedVectorType::get(
5585         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5586   unsigned EntryVF = E->getVectorFactor();
5587   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5588 
5589   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5590   // FIXME: it tries to fix a problem with MSVC buildbots.
5591   TargetTransformInfo &TTIRef = *TTI;
5592   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5593                                VectorizedVals, E](InstructionCost &Cost) {
5594     DenseMap<Value *, int> ExtractVectorsTys;
5595     SmallPtrSet<Value *, 4> CheckedExtracts;
5596     for (auto *V : VL) {
5597       if (isa<UndefValue>(V))
5598         continue;
5599       // If all users of instruction are going to be vectorized and this
5600       // instruction itself is not going to be vectorized, consider this
5601       // instruction as dead and remove its cost from the final cost of the
5602       // vectorized tree.
5603       // Also, avoid adjusting the cost for extractelements with multiple uses
5604       // in different graph entries.
5605       const TreeEntry *VE = getTreeEntry(V);
5606       if (!CheckedExtracts.insert(V).second ||
5607           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5608           (VE && VE != E))
5609         continue;
5610       auto *EE = cast<ExtractElementInst>(V);
5611       Optional<unsigned> EEIdx = getExtractIndex(EE);
5612       if (!EEIdx)
5613         continue;
5614       unsigned Idx = *EEIdx;
5615       if (TTIRef.getNumberOfParts(VecTy) !=
5616           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5617         auto It =
5618             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5619         It->getSecond() = std::min<int>(It->second, Idx);
5620       }
5621       // Take credit for instruction that will become dead.
5622       if (EE->hasOneUse()) {
5623         Instruction *Ext = EE->user_back();
5624         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5625             all_of(Ext->users(),
5626                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5627           // Use getExtractWithExtendCost() to calculate the cost of
5628           // extractelement/ext pair.
5629           Cost -=
5630               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5631                                               EE->getVectorOperandType(), Idx);
5632           // Add back the cost of s|zext which is subtracted separately.
5633           Cost += TTIRef.getCastInstrCost(
5634               Ext->getOpcode(), Ext->getType(), EE->getType(),
5635               TTI::getCastContextHint(Ext), CostKind, Ext);
5636           continue;
5637         }
5638       }
5639       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5640                                         EE->getVectorOperandType(), Idx);
5641     }
5642     // Add a cost for subvector extracts/inserts if required.
5643     for (const auto &Data : ExtractVectorsTys) {
5644       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5645       unsigned NumElts = VecTy->getNumElements();
5646       if (Data.second % NumElts == 0)
5647         continue;
5648       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5649         unsigned Idx = (Data.second / NumElts) * NumElts;
5650         unsigned EENumElts = EEVTy->getNumElements();
5651         if (Idx + NumElts <= EENumElts) {
5652           Cost +=
5653               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5654                                     EEVTy, None, Idx, VecTy);
5655         } else {
5656           // Need to round up the subvector type vectorization factor to avoid a
5657           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5658           // <= EENumElts.
5659           auto *SubVT =
5660               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5661           Cost +=
5662               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5663                                     EEVTy, None, Idx, SubVT);
5664         }
5665       } else {
5666         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5667                                       VecTy, None, 0, EEVTy);
5668       }
5669     }
5670   };
5671   if (E->State == TreeEntry::NeedToGather) {
5672     if (allConstant(VL))
5673       return 0;
5674     if (isa<InsertElementInst>(VL[0]))
5675       return InstructionCost::getInvalid();
5676     SmallVector<int> Mask;
5677     SmallVector<const TreeEntry *> Entries;
5678     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5679         isGatherShuffledEntry(E, Mask, Entries);
5680     if (Shuffle.hasValue()) {
5681       InstructionCost GatherCost = 0;
5682       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5683         // Perfect match in the graph, will reuse the previously vectorized
5684         // node. Cost is 0.
5685         LLVM_DEBUG(
5686             dbgs()
5687             << "SLP: perfect diamond match for gather bundle that starts with "
5688             << *VL.front() << ".\n");
5689         if (NeedToShuffleReuses)
5690           GatherCost =
5691               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5692                                   FinalVecTy, E->ReuseShuffleIndices);
5693       } else {
5694         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5695                           << " entries for bundle that starts with "
5696                           << *VL.front() << ".\n");
5697         // Detected that instead of gather we can emit a shuffle of single/two
5698         // previously vectorized nodes. Add the cost of the permutation rather
5699         // than gather.
5700         ::addMask(Mask, E->ReuseShuffleIndices);
5701         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5702       }
5703       return GatherCost;
5704     }
5705     if ((E->getOpcode() == Instruction::ExtractElement ||
5706          all_of(E->Scalars,
5707                 [](Value *V) {
5708                   return isa<ExtractElementInst, UndefValue>(V);
5709                 })) &&
5710         allSameType(VL)) {
5711       // Check that gather of extractelements can be represented as just a
5712       // shuffle of a single/two vectors the scalars are extracted from.
5713       SmallVector<int> Mask;
5714       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5715           isFixedVectorShuffle(VL, Mask);
5716       if (ShuffleKind.hasValue()) {
5717         // Found the bunch of extractelement instructions that must be gathered
5718         // into a vector and can be represented as a permutation elements in a
5719         // single input vector or of 2 input vectors.
5720         InstructionCost Cost =
5721             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5722         AdjustExtractsCost(Cost);
5723         if (NeedToShuffleReuses)
5724           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5725                                       FinalVecTy, E->ReuseShuffleIndices);
5726         return Cost;
5727       }
5728     }
5729     if (isSplat(VL)) {
5730       // Found the broadcasting of the single scalar, calculate the cost as the
5731       // broadcast.
5732       assert(VecTy == FinalVecTy &&
5733              "No reused scalars expected for broadcast.");
5734       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5735                                  /*Mask=*/None, /*Index=*/0,
5736                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5737     }
5738     InstructionCost ReuseShuffleCost = 0;
5739     if (NeedToShuffleReuses)
5740       ReuseShuffleCost = TTI->getShuffleCost(
5741           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5742     // Improve gather cost for gather of loads, if we can group some of the
5743     // loads into vector loads.
5744     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5745         !E->isAltShuffle()) {
5746       BoUpSLP::ValueSet VectorizedLoads;
5747       unsigned StartIdx = 0;
5748       unsigned VF = VL.size() / 2;
5749       unsigned VectorizedCnt = 0;
5750       unsigned ScatterVectorizeCnt = 0;
5751       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5752       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5753         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5754              Cnt += VF) {
5755           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5756           if (!VectorizedLoads.count(Slice.front()) &&
5757               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5758             SmallVector<Value *> PointerOps;
5759             OrdersType CurrentOrder;
5760             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5761                                               *SE, CurrentOrder, PointerOps);
5762             switch (LS) {
5763             case LoadsState::Vectorize:
5764             case LoadsState::ScatterVectorize:
5765               // Mark the vectorized loads so that we don't vectorize them
5766               // again.
5767               if (LS == LoadsState::Vectorize)
5768                 ++VectorizedCnt;
5769               else
5770                 ++ScatterVectorizeCnt;
5771               VectorizedLoads.insert(Slice.begin(), Slice.end());
5772               // If we vectorized initial block, no need to try to vectorize it
5773               // again.
5774               if (Cnt == StartIdx)
5775                 StartIdx += VF;
5776               break;
5777             case LoadsState::Gather:
5778               break;
5779             }
5780           }
5781         }
5782         // Check if the whole array was vectorized already - exit.
5783         if (StartIdx >= VL.size())
5784           break;
5785         // Found vectorizable parts - exit.
5786         if (!VectorizedLoads.empty())
5787           break;
5788       }
5789       if (!VectorizedLoads.empty()) {
5790         InstructionCost GatherCost = 0;
5791         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5792         bool NeedInsertSubvectorAnalysis =
5793             !NumParts || (VL.size() / VF) > NumParts;
5794         // Get the cost for gathered loads.
5795         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5796           if (VectorizedLoads.contains(VL[I]))
5797             continue;
5798           GatherCost += getGatherCost(VL.slice(I, VF));
5799         }
5800         // The cost for vectorized loads.
5801         InstructionCost ScalarsCost = 0;
5802         for (Value *V : VectorizedLoads) {
5803           auto *LI = cast<LoadInst>(V);
5804           ScalarsCost += TTI->getMemoryOpCost(
5805               Instruction::Load, LI->getType(), LI->getAlign(),
5806               LI->getPointerAddressSpace(), CostKind, LI);
5807         }
5808         auto *LI = cast<LoadInst>(E->getMainOp());
5809         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5810         Align Alignment = LI->getAlign();
5811         GatherCost +=
5812             VectorizedCnt *
5813             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5814                                  LI->getPointerAddressSpace(), CostKind, LI);
5815         GatherCost += ScatterVectorizeCnt *
5816                       TTI->getGatherScatterOpCost(
5817                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5818                           /*VariableMask=*/false, Alignment, CostKind, LI);
5819         if (NeedInsertSubvectorAnalysis) {
5820           // Add the cost for the subvectors insert.
5821           for (int I = VF, E = VL.size(); I < E; I += VF)
5822             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5823                                               None, I, LoadTy);
5824         }
5825         return ReuseShuffleCost + GatherCost - ScalarsCost;
5826       }
5827     }
5828     return ReuseShuffleCost + getGatherCost(VL);
5829   }
5830   InstructionCost CommonCost = 0;
5831   SmallVector<int> Mask;
5832   if (!E->ReorderIndices.empty()) {
5833     SmallVector<int> NewMask;
5834     if (E->getOpcode() == Instruction::Store) {
5835       // For stores the order is actually a mask.
5836       NewMask.resize(E->ReorderIndices.size());
5837       copy(E->ReorderIndices, NewMask.begin());
5838     } else {
5839       inversePermutation(E->ReorderIndices, NewMask);
5840     }
5841     ::addMask(Mask, NewMask);
5842   }
5843   if (NeedToShuffleReuses)
5844     ::addMask(Mask, E->ReuseShuffleIndices);
5845   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5846     CommonCost =
5847         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5848   assert((E->State == TreeEntry::Vectorize ||
5849           E->State == TreeEntry::ScatterVectorize) &&
5850          "Unhandled state");
5851   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5852   Instruction *VL0 = E->getMainOp();
5853   unsigned ShuffleOrOp =
5854       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5855   switch (ShuffleOrOp) {
5856     case Instruction::PHI:
5857       return 0;
5858 
5859     case Instruction::ExtractValue:
5860     case Instruction::ExtractElement: {
5861       // The common cost of removal ExtractElement/ExtractValue instructions +
5862       // the cost of shuffles, if required to resuffle the original vector.
5863       if (NeedToShuffleReuses) {
5864         unsigned Idx = 0;
5865         for (unsigned I : E->ReuseShuffleIndices) {
5866           if (ShuffleOrOp == Instruction::ExtractElement) {
5867             auto *EE = cast<ExtractElementInst>(VL[I]);
5868             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5869                                                   EE->getVectorOperandType(),
5870                                                   *getExtractIndex(EE));
5871           } else {
5872             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5873                                                   VecTy, Idx);
5874             ++Idx;
5875           }
5876         }
5877         Idx = EntryVF;
5878         for (Value *V : VL) {
5879           if (ShuffleOrOp == Instruction::ExtractElement) {
5880             auto *EE = cast<ExtractElementInst>(V);
5881             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5882                                                   EE->getVectorOperandType(),
5883                                                   *getExtractIndex(EE));
5884           } else {
5885             --Idx;
5886             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5887                                                   VecTy, Idx);
5888           }
5889         }
5890       }
5891       if (ShuffleOrOp == Instruction::ExtractValue) {
5892         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5893           auto *EI = cast<Instruction>(VL[I]);
5894           // Take credit for instruction that will become dead.
5895           if (EI->hasOneUse()) {
5896             Instruction *Ext = EI->user_back();
5897             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5898                 all_of(Ext->users(),
5899                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5900               // Use getExtractWithExtendCost() to calculate the cost of
5901               // extractelement/ext pair.
5902               CommonCost -= TTI->getExtractWithExtendCost(
5903                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5904               // Add back the cost of s|zext which is subtracted separately.
5905               CommonCost += TTI->getCastInstrCost(
5906                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5907                   TTI::getCastContextHint(Ext), CostKind, Ext);
5908               continue;
5909             }
5910           }
5911           CommonCost -=
5912               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5913         }
5914       } else {
5915         AdjustExtractsCost(CommonCost);
5916       }
5917       return CommonCost;
5918     }
5919     case Instruction::InsertElement: {
5920       assert(E->ReuseShuffleIndices.empty() &&
5921              "Unique insertelements only are expected.");
5922       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5923 
5924       unsigned const NumElts = SrcVecTy->getNumElements();
5925       unsigned const NumScalars = VL.size();
5926       APInt DemandedElts = APInt::getZero(NumElts);
5927       // TODO: Add support for Instruction::InsertValue.
5928       SmallVector<int> Mask;
5929       if (!E->ReorderIndices.empty()) {
5930         inversePermutation(E->ReorderIndices, Mask);
5931         Mask.append(NumElts - NumScalars, UndefMaskElem);
5932       } else {
5933         Mask.assign(NumElts, UndefMaskElem);
5934         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5935       }
5936       unsigned Offset = *getInsertIndex(VL0);
5937       bool IsIdentity = true;
5938       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5939       Mask.swap(PrevMask);
5940       for (unsigned I = 0; I < NumScalars; ++I) {
5941         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5942         DemandedElts.setBit(InsertIdx);
5943         IsIdentity &= InsertIdx - Offset == I;
5944         Mask[InsertIdx - Offset] = I;
5945       }
5946       assert(Offset < NumElts && "Failed to find vector index offset");
5947 
5948       InstructionCost Cost = 0;
5949       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5950                                             /*Insert*/ true, /*Extract*/ false);
5951 
5952       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5953         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5954         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5955         Cost += TTI->getShuffleCost(
5956             TargetTransformInfo::SK_PermuteSingleSrc,
5957             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5958       } else if (!IsIdentity) {
5959         auto *FirstInsert =
5960             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5961               return !is_contained(E->Scalars,
5962                                    cast<Instruction>(V)->getOperand(0));
5963             }));
5964         if (isUndefVector(FirstInsert->getOperand(0))) {
5965           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5966         } else {
5967           SmallVector<int> InsertMask(NumElts);
5968           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5969           for (unsigned I = 0; I < NumElts; I++) {
5970             if (Mask[I] != UndefMaskElem)
5971               InsertMask[Offset + I] = NumElts + I;
5972           }
5973           Cost +=
5974               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5975         }
5976       }
5977 
5978       return Cost;
5979     }
5980     case Instruction::ZExt:
5981     case Instruction::SExt:
5982     case Instruction::FPToUI:
5983     case Instruction::FPToSI:
5984     case Instruction::FPExt:
5985     case Instruction::PtrToInt:
5986     case Instruction::IntToPtr:
5987     case Instruction::SIToFP:
5988     case Instruction::UIToFP:
5989     case Instruction::Trunc:
5990     case Instruction::FPTrunc:
5991     case Instruction::BitCast: {
5992       Type *SrcTy = VL0->getOperand(0)->getType();
5993       InstructionCost ScalarEltCost =
5994           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5995                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5996       if (NeedToShuffleReuses) {
5997         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5998       }
5999 
6000       // Calculate the cost of this instruction.
6001       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
6002 
6003       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
6004       InstructionCost VecCost = 0;
6005       // Check if the values are candidates to demote.
6006       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
6007         VecCost = CommonCost + TTI->getCastInstrCost(
6008                                    E->getOpcode(), VecTy, SrcVecTy,
6009                                    TTI::getCastContextHint(VL0), CostKind, VL0);
6010       }
6011       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6012       return VecCost - ScalarCost;
6013     }
6014     case Instruction::FCmp:
6015     case Instruction::ICmp:
6016     case Instruction::Select: {
6017       // Calculate the cost of this instruction.
6018       InstructionCost ScalarEltCost =
6019           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6020                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
6021       if (NeedToShuffleReuses) {
6022         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6023       }
6024       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
6025       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6026 
6027       // Check if all entries in VL are either compares or selects with compares
6028       // as condition that have the same predicates.
6029       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
6030       bool First = true;
6031       for (auto *V : VL) {
6032         CmpInst::Predicate CurrentPred;
6033         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
6034         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
6035              !match(V, MatchCmp)) ||
6036             (!First && VecPred != CurrentPred)) {
6037           VecPred = CmpInst::BAD_ICMP_PREDICATE;
6038           break;
6039         }
6040         First = false;
6041         VecPred = CurrentPred;
6042       }
6043 
6044       InstructionCost VecCost = TTI->getCmpSelInstrCost(
6045           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
6046       // Check if it is possible and profitable to use min/max for selects in
6047       // VL.
6048       //
6049       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
6050       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
6051         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
6052                                           {VecTy, VecTy});
6053         InstructionCost IntrinsicCost =
6054             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6055         // If the selects are the only uses of the compares, they will be dead
6056         // and we can adjust the cost by removing their cost.
6057         if (IntrinsicAndUse.second)
6058           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
6059                                                    MaskTy, VecPred, CostKind);
6060         VecCost = std::min(VecCost, IntrinsicCost);
6061       }
6062       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6063       return CommonCost + VecCost - ScalarCost;
6064     }
6065     case Instruction::FNeg:
6066     case Instruction::Add:
6067     case Instruction::FAdd:
6068     case Instruction::Sub:
6069     case Instruction::FSub:
6070     case Instruction::Mul:
6071     case Instruction::FMul:
6072     case Instruction::UDiv:
6073     case Instruction::SDiv:
6074     case Instruction::FDiv:
6075     case Instruction::URem:
6076     case Instruction::SRem:
6077     case Instruction::FRem:
6078     case Instruction::Shl:
6079     case Instruction::LShr:
6080     case Instruction::AShr:
6081     case Instruction::And:
6082     case Instruction::Or:
6083     case Instruction::Xor: {
6084       // Certain instructions can be cheaper to vectorize if they have a
6085       // constant second vector operand.
6086       TargetTransformInfo::OperandValueKind Op1VK =
6087           TargetTransformInfo::OK_AnyValue;
6088       TargetTransformInfo::OperandValueKind Op2VK =
6089           TargetTransformInfo::OK_UniformConstantValue;
6090       TargetTransformInfo::OperandValueProperties Op1VP =
6091           TargetTransformInfo::OP_None;
6092       TargetTransformInfo::OperandValueProperties Op2VP =
6093           TargetTransformInfo::OP_PowerOf2;
6094 
6095       // If all operands are exactly the same ConstantInt then set the
6096       // operand kind to OK_UniformConstantValue.
6097       // If instead not all operands are constants, then set the operand kind
6098       // to OK_AnyValue. If all operands are constants but not the same,
6099       // then set the operand kind to OK_NonUniformConstantValue.
6100       ConstantInt *CInt0 = nullptr;
6101       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
6102         const Instruction *I = cast<Instruction>(VL[i]);
6103         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
6104         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
6105         if (!CInt) {
6106           Op2VK = TargetTransformInfo::OK_AnyValue;
6107           Op2VP = TargetTransformInfo::OP_None;
6108           break;
6109         }
6110         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
6111             !CInt->getValue().isPowerOf2())
6112           Op2VP = TargetTransformInfo::OP_None;
6113         if (i == 0) {
6114           CInt0 = CInt;
6115           continue;
6116         }
6117         if (CInt0 != CInt)
6118           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6119       }
6120 
6121       SmallVector<const Value *, 4> Operands(VL0->operand_values());
6122       InstructionCost ScalarEltCost =
6123           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
6124                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6125       if (NeedToShuffleReuses) {
6126         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6127       }
6128       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6129       InstructionCost VecCost =
6130           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
6131                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6132       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6133       return CommonCost + VecCost - ScalarCost;
6134     }
6135     case Instruction::GetElementPtr: {
6136       TargetTransformInfo::OperandValueKind Op1VK =
6137           TargetTransformInfo::OK_AnyValue;
6138       TargetTransformInfo::OperandValueKind Op2VK =
6139           TargetTransformInfo::OK_UniformConstantValue;
6140 
6141       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
6142           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
6143       if (NeedToShuffleReuses) {
6144         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6145       }
6146       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6147       InstructionCost VecCost = TTI->getArithmeticInstrCost(
6148           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
6149       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6150       return CommonCost + VecCost - ScalarCost;
6151     }
6152     case Instruction::Load: {
6153       // Cost of wide load - cost of scalar loads.
6154       Align Alignment = cast<LoadInst>(VL0)->getAlign();
6155       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6156           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
6157       if (NeedToShuffleReuses) {
6158         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6159       }
6160       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
6161       InstructionCost VecLdCost;
6162       if (E->State == TreeEntry::Vectorize) {
6163         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
6164                                          CostKind, VL0);
6165       } else {
6166         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
6167         Align CommonAlignment = Alignment;
6168         for (Value *V : VL)
6169           CommonAlignment =
6170               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6171         VecLdCost = TTI->getGatherScatterOpCost(
6172             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
6173             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
6174       }
6175       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
6176       return CommonCost + VecLdCost - ScalarLdCost;
6177     }
6178     case Instruction::Store: {
6179       // We know that we can merge the stores. Calculate the cost.
6180       bool IsReorder = !E->ReorderIndices.empty();
6181       auto *SI =
6182           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
6183       Align Alignment = SI->getAlign();
6184       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6185           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
6186       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
6187       InstructionCost VecStCost = TTI->getMemoryOpCost(
6188           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
6189       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
6190       return CommonCost + VecStCost - ScalarStCost;
6191     }
6192     case Instruction::Call: {
6193       CallInst *CI = cast<CallInst>(VL0);
6194       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6195 
6196       // Calculate the cost of the scalar and vector calls.
6197       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6198       InstructionCost ScalarEltCost =
6199           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6200       if (NeedToShuffleReuses) {
6201         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6202       }
6203       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6204 
6205       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6206       InstructionCost VecCallCost =
6207           std::min(VecCallCosts.first, VecCallCosts.second);
6208 
6209       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6210                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6211                         << " for " << *CI << "\n");
6212 
6213       return CommonCost + VecCallCost - ScalarCallCost;
6214     }
6215     case Instruction::ShuffleVector: {
6216       assert(E->isAltShuffle() &&
6217              ((Instruction::isBinaryOp(E->getOpcode()) &&
6218                Instruction::isBinaryOp(E->getAltOpcode())) ||
6219               (Instruction::isCast(E->getOpcode()) &&
6220                Instruction::isCast(E->getAltOpcode())) ||
6221               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6222              "Invalid Shuffle Vector Operand");
6223       InstructionCost ScalarCost = 0;
6224       if (NeedToShuffleReuses) {
6225         for (unsigned Idx : E->ReuseShuffleIndices) {
6226           Instruction *I = cast<Instruction>(VL[Idx]);
6227           CommonCost -= TTI->getInstructionCost(I, CostKind);
6228         }
6229         for (Value *V : VL) {
6230           Instruction *I = cast<Instruction>(V);
6231           CommonCost += TTI->getInstructionCost(I, CostKind);
6232         }
6233       }
6234       for (Value *V : VL) {
6235         Instruction *I = cast<Instruction>(V);
6236         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6237         ScalarCost += TTI->getInstructionCost(I, CostKind);
6238       }
6239       // VecCost is equal to sum of the cost of creating 2 vectors
6240       // and the cost of creating shuffle.
6241       InstructionCost VecCost = 0;
6242       // Try to find the previous shuffle node with the same operands and same
6243       // main/alternate ops.
6244       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6245         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6246           if (TE.get() == E)
6247             break;
6248           if (TE->isAltShuffle() &&
6249               ((TE->getOpcode() == E->getOpcode() &&
6250                 TE->getAltOpcode() == E->getAltOpcode()) ||
6251                (TE->getOpcode() == E->getAltOpcode() &&
6252                 TE->getAltOpcode() == E->getOpcode())) &&
6253               TE->hasEqualOperands(*E))
6254             return true;
6255         }
6256         return false;
6257       };
6258       if (TryFindNodeWithEqualOperands()) {
6259         LLVM_DEBUG({
6260           dbgs() << "SLP: diamond match for alternate node found.\n";
6261           E->dump();
6262         });
6263         // No need to add new vector costs here since we're going to reuse
6264         // same main/alternate vector ops, just do different shuffling.
6265       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6266         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6267         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6268                                                CostKind);
6269       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6270         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6271                                           Builder.getInt1Ty(),
6272                                           CI0->getPredicate(), CostKind, VL0);
6273         VecCost += TTI->getCmpSelInstrCost(
6274             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6275             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6276             E->getAltOp());
6277       } else {
6278         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6279         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6280         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6281         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6282         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6283                                         TTI::CastContextHint::None, CostKind);
6284         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6285                                          TTI::CastContextHint::None, CostKind);
6286       }
6287 
6288       if (E->ReuseShuffleIndices.empty()) {
6289         CommonCost =
6290             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6291       } else {
6292         SmallVector<int> Mask;
6293         buildShuffleEntryMask(
6294             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6295             [E](Instruction *I) {
6296               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6297               return I->getOpcode() == E->getAltOpcode();
6298             },
6299             Mask);
6300         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6301                                          FinalVecTy, Mask);
6302       }
6303       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6304       return CommonCost + VecCost - ScalarCost;
6305     }
6306     default:
6307       llvm_unreachable("Unknown instruction");
6308   }
6309 }
6310 
6311 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6312   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6313                     << VectorizableTree.size() << " is fully vectorizable .\n");
6314 
6315   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6316     SmallVector<int> Mask;
6317     return TE->State == TreeEntry::NeedToGather &&
6318            !any_of(TE->Scalars,
6319                    [this](Value *V) { return EphValues.contains(V); }) &&
6320            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6321             TE->Scalars.size() < Limit ||
6322             ((TE->getOpcode() == Instruction::ExtractElement ||
6323               all_of(TE->Scalars,
6324                      [](Value *V) {
6325                        return isa<ExtractElementInst, UndefValue>(V);
6326                      })) &&
6327              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6328             (TE->State == TreeEntry::NeedToGather &&
6329              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6330   };
6331 
6332   // We only handle trees of heights 1 and 2.
6333   if (VectorizableTree.size() == 1 &&
6334       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6335        (ForReduction &&
6336         AreVectorizableGathers(VectorizableTree[0].get(),
6337                                VectorizableTree[0]->Scalars.size()) &&
6338         VectorizableTree[0]->getVectorFactor() > 2)))
6339     return true;
6340 
6341   if (VectorizableTree.size() != 2)
6342     return false;
6343 
6344   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6345   // with the second gather nodes if they have less scalar operands rather than
6346   // the initial tree element (may be profitable to shuffle the second gather)
6347   // or they are extractelements, which form shuffle.
6348   SmallVector<int> Mask;
6349   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6350       AreVectorizableGathers(VectorizableTree[1].get(),
6351                              VectorizableTree[0]->Scalars.size()))
6352     return true;
6353 
6354   // Gathering cost would be too much for tiny trees.
6355   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6356       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6357        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6358     return false;
6359 
6360   return true;
6361 }
6362 
6363 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6364                                        TargetTransformInfo *TTI,
6365                                        bool MustMatchOrInst) {
6366   // Look past the root to find a source value. Arbitrarily follow the
6367   // path through operand 0 of any 'or'. Also, peek through optional
6368   // shift-left-by-multiple-of-8-bits.
6369   Value *ZextLoad = Root;
6370   const APInt *ShAmtC;
6371   bool FoundOr = false;
6372   while (!isa<ConstantExpr>(ZextLoad) &&
6373          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6374           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6375            ShAmtC->urem(8) == 0))) {
6376     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6377     ZextLoad = BinOp->getOperand(0);
6378     if (BinOp->getOpcode() == Instruction::Or)
6379       FoundOr = true;
6380   }
6381   // Check if the input is an extended load of the required or/shift expression.
6382   Value *Load;
6383   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6384       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6385     return false;
6386 
6387   // Require that the total load bit width is a legal integer type.
6388   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6389   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6390   Type *SrcTy = Load->getType();
6391   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6392   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6393     return false;
6394 
6395   // Everything matched - assume that we can fold the whole sequence using
6396   // load combining.
6397   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6398              << *(cast<Instruction>(Root)) << "\n");
6399 
6400   return true;
6401 }
6402 
6403 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6404   if (RdxKind != RecurKind::Or)
6405     return false;
6406 
6407   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6408   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6409   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6410                                     /* MatchOr */ false);
6411 }
6412 
6413 bool BoUpSLP::isLoadCombineCandidate() const {
6414   // Peek through a final sequence of stores and check if all operations are
6415   // likely to be load-combined.
6416   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6417   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6418     Value *X;
6419     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6420         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6421       return false;
6422   }
6423   return true;
6424 }
6425 
6426 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6427   // No need to vectorize inserts of gathered values.
6428   if (VectorizableTree.size() == 2 &&
6429       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6430       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6431     return true;
6432 
6433   // We can vectorize the tree if its size is greater than or equal to the
6434   // minimum size specified by the MinTreeSize command line option.
6435   if (VectorizableTree.size() >= MinTreeSize)
6436     return false;
6437 
6438   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6439   // can vectorize it if we can prove it fully vectorizable.
6440   if (isFullyVectorizableTinyTree(ForReduction))
6441     return false;
6442 
6443   assert(VectorizableTree.empty()
6444              ? ExternalUses.empty()
6445              : true && "We shouldn't have any external users");
6446 
6447   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6448   // vectorizable.
6449   return true;
6450 }
6451 
6452 InstructionCost BoUpSLP::getSpillCost() const {
6453   // Walk from the bottom of the tree to the top, tracking which values are
6454   // live. When we see a call instruction that is not part of our tree,
6455   // query TTI to see if there is a cost to keeping values live over it
6456   // (for example, if spills and fills are required).
6457   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6458   InstructionCost Cost = 0;
6459 
6460   SmallPtrSet<Instruction*, 4> LiveValues;
6461   Instruction *PrevInst = nullptr;
6462 
6463   // The entries in VectorizableTree are not necessarily ordered by their
6464   // position in basic blocks. Collect them and order them by dominance so later
6465   // instructions are guaranteed to be visited first. For instructions in
6466   // different basic blocks, we only scan to the beginning of the block, so
6467   // their order does not matter, as long as all instructions in a basic block
6468   // are grouped together. Using dominance ensures a deterministic order.
6469   SmallVector<Instruction *, 16> OrderedScalars;
6470   for (const auto &TEPtr : VectorizableTree) {
6471     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6472     if (!Inst)
6473       continue;
6474     OrderedScalars.push_back(Inst);
6475   }
6476   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6477     auto *NodeA = DT->getNode(A->getParent());
6478     auto *NodeB = DT->getNode(B->getParent());
6479     assert(NodeA && "Should only process reachable instructions");
6480     assert(NodeB && "Should only process reachable instructions");
6481     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6482            "Different nodes should have different DFS numbers");
6483     if (NodeA != NodeB)
6484       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6485     return B->comesBefore(A);
6486   });
6487 
6488   for (Instruction *Inst : OrderedScalars) {
6489     if (!PrevInst) {
6490       PrevInst = Inst;
6491       continue;
6492     }
6493 
6494     // Update LiveValues.
6495     LiveValues.erase(PrevInst);
6496     for (auto &J : PrevInst->operands()) {
6497       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6498         LiveValues.insert(cast<Instruction>(&*J));
6499     }
6500 
6501     LLVM_DEBUG({
6502       dbgs() << "SLP: #LV: " << LiveValues.size();
6503       for (auto *X : LiveValues)
6504         dbgs() << " " << X->getName();
6505       dbgs() << ", Looking at ";
6506       Inst->dump();
6507     });
6508 
6509     // Now find the sequence of instructions between PrevInst and Inst.
6510     unsigned NumCalls = 0;
6511     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6512                                  PrevInstIt =
6513                                      PrevInst->getIterator().getReverse();
6514     while (InstIt != PrevInstIt) {
6515       if (PrevInstIt == PrevInst->getParent()->rend()) {
6516         PrevInstIt = Inst->getParent()->rbegin();
6517         continue;
6518       }
6519 
6520       // Debug information does not impact spill cost.
6521       if ((isa<CallInst>(&*PrevInstIt) &&
6522            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6523           &*PrevInstIt != PrevInst)
6524         NumCalls++;
6525 
6526       ++PrevInstIt;
6527     }
6528 
6529     if (NumCalls) {
6530       SmallVector<Type*, 4> V;
6531       for (auto *II : LiveValues) {
6532         auto *ScalarTy = II->getType();
6533         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6534           ScalarTy = VectorTy->getElementType();
6535         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6536       }
6537       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6538     }
6539 
6540     PrevInst = Inst;
6541   }
6542 
6543   return Cost;
6544 }
6545 
6546 /// Check if two insertelement instructions are from the same buildvector.
6547 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6548                                             InsertElementInst *V) {
6549   // Instructions must be from the same basic blocks.
6550   if (VU->getParent() != V->getParent())
6551     return false;
6552   // Checks if 2 insertelements are from the same buildvector.
6553   if (VU->getType() != V->getType())
6554     return false;
6555   // Multiple used inserts are separate nodes.
6556   if (!VU->hasOneUse() && !V->hasOneUse())
6557     return false;
6558   auto *IE1 = VU;
6559   auto *IE2 = V;
6560   // Go through the vector operand of insertelement instructions trying to find
6561   // either VU as the original vector for IE2 or V as the original vector for
6562   // IE1.
6563   do {
6564     if (IE2 == VU || IE1 == V)
6565       return true;
6566     if (IE1) {
6567       if (IE1 != VU && !IE1->hasOneUse())
6568         IE1 = nullptr;
6569       else
6570         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6571     }
6572     if (IE2) {
6573       if (IE2 != V && !IE2->hasOneUse())
6574         IE2 = nullptr;
6575       else
6576         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6577     }
6578   } while (IE1 || IE2);
6579   return false;
6580 }
6581 
6582 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6583 /// buildvector sequence.
6584 static bool isFirstInsertElement(const InsertElementInst *IE1,
6585                                  const InsertElementInst *IE2) {
6586   const auto *I1 = IE1;
6587   const auto *I2 = IE2;
6588   const InsertElementInst *PrevI1;
6589   const InsertElementInst *PrevI2;
6590   do {
6591     if (I2 == IE1)
6592       return true;
6593     if (I1 == IE2)
6594       return false;
6595     PrevI1 = I1;
6596     PrevI2 = I2;
6597     if (I1 && (I1 == IE1 || I1->hasOneUse()))
6598       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6599     if (I2 && (I2 == IE2 || I2->hasOneUse()))
6600       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6601   } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
6602   llvm_unreachable("Two different buildvectors not expected.");
6603 }
6604 
6605 /// Does the analysis of the provided shuffle masks and performs the requested
6606 /// actions on the vectors with the given shuffle masks. It tries to do it in
6607 /// several steps.
6608 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6609 /// have common VF and perform action for 2 input vectors (including non-undef
6610 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6611 /// and processed as a shuffle of 2 elements.
6612 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6613 /// action only for 1 vector with the given mask, if it is not the identity
6614 /// mask.
6615 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6616 /// vectors, combing the masks properly between the steps.
6617 template <typename T>
6618 static T *performExtractsShuffleAction(
6619     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6620     function_ref<unsigned(T *)> GetVF,
6621     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6622     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6623   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6624   SmallVector<int> Mask(ShuffleMask.begin()->second);
6625   auto VMIt = std::next(ShuffleMask.begin());
6626   T *Prev = nullptr;
6627   bool IsBaseNotUndef = !isUndefVector(Base);
6628   if (IsBaseNotUndef) {
6629     // Base is not undef, need to combine it with the next subvectors.
6630     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6631     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6632       if (Mask[Idx] == UndefMaskElem)
6633         Mask[Idx] = Idx;
6634       else
6635         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6636     }
6637     Prev = Action(Mask, {nullptr, Res.first});
6638   } else if (ShuffleMask.size() == 1) {
6639     // Base is undef and only 1 vector is shuffled - perform the action only for
6640     // single vector, if the mask is not the identity mask.
6641     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6642     if (Res.second)
6643       // Identity mask is found.
6644       Prev = Res.first;
6645     else
6646       Prev = Action(Mask, {ShuffleMask.begin()->first});
6647   } else {
6648     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6649     // shuffles step by step, combining shuffle between the steps.
6650     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6651     unsigned Vec2VF = GetVF(VMIt->first);
6652     if (Vec1VF == Vec2VF) {
6653       // No need to resize the input vectors since they are of the same size, we
6654       // can shuffle them directly.
6655       ArrayRef<int> SecMask = VMIt->second;
6656       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6657         if (SecMask[I] != UndefMaskElem) {
6658           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6659           Mask[I] = SecMask[I] + Vec1VF;
6660         }
6661       }
6662       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6663     } else {
6664       // Vectors of different sizes - resize and reshuffle.
6665       std::pair<T *, bool> Res1 =
6666           ResizeAction(ShuffleMask.begin()->first, Mask);
6667       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6668       ArrayRef<int> SecMask = VMIt->second;
6669       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6670         if (Mask[I] != UndefMaskElem) {
6671           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6672           if (Res1.second)
6673             Mask[I] = I;
6674         } else if (SecMask[I] != UndefMaskElem) {
6675           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6676           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6677         }
6678       }
6679       Prev = Action(Mask, {Res1.first, Res2.first});
6680     }
6681     VMIt = std::next(VMIt);
6682   }
6683   // Perform requested actions for the remaining masks/vectors.
6684   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6685     // Shuffle other input vectors, if any.
6686     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6687     ArrayRef<int> SecMask = VMIt->second;
6688     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6689       if (SecMask[I] != UndefMaskElem) {
6690         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6691                "Multiple uses of scalars.");
6692         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6693       } else if (Mask[I] != UndefMaskElem) {
6694         Mask[I] = I;
6695       }
6696     }
6697     Prev = Action(Mask, {Prev, Res.first});
6698   }
6699   return Prev;
6700 }
6701 
6702 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6703   InstructionCost Cost = 0;
6704   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6705                     << VectorizableTree.size() << ".\n");
6706 
6707   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6708 
6709   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6710     TreeEntry &TE = *VectorizableTree[I];
6711 
6712     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6713     Cost += C;
6714     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6715                       << " for bundle that starts with " << *TE.Scalars[0]
6716                       << ".\n"
6717                       << "SLP: Current total cost = " << Cost << "\n");
6718   }
6719 
6720   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6721   InstructionCost ExtractCost = 0;
6722   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6723   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6724   SmallVector<APInt> DemandedElts;
6725   for (ExternalUser &EU : ExternalUses) {
6726     // We only add extract cost once for the same scalar.
6727     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6728         !ExtractCostCalculated.insert(EU.Scalar).second)
6729       continue;
6730 
6731     // Uses by ephemeral values are free (because the ephemeral value will be
6732     // removed prior to code generation, and so the extraction will be
6733     // removed as well).
6734     if (EphValues.count(EU.User))
6735       continue;
6736 
6737     // No extract cost for vector "scalar"
6738     if (isa<FixedVectorType>(EU.Scalar->getType()))
6739       continue;
6740 
6741     // Already counted the cost for external uses when tried to adjust the cost
6742     // for extractelements, no need to add it again.
6743     if (isa<ExtractElementInst>(EU.Scalar))
6744       continue;
6745 
6746     // If found user is an insertelement, do not calculate extract cost but try
6747     // to detect it as a final shuffled/identity match.
6748     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6749       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6750         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6751         if (InsertIdx) {
6752           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6753           auto *It =
6754               find_if(FirstUsers,
6755                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6756                         return areTwoInsertFromSameBuildVector(
6757                             VU, cast<InsertElementInst>(Pair.first));
6758                       });
6759           int VecId = -1;
6760           if (It == FirstUsers.end()) {
6761             (void)ShuffleMasks.emplace_back();
6762             SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6763             if (Mask.empty())
6764               Mask.assign(FTy->getNumElements(), UndefMaskElem);
6765             // Find the insertvector, vectorized in tree, if any.
6766             Value *Base = VU;
6767             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6768               if (IEBase != EU.User && !IEBase->hasOneUse())
6769                 break;
6770               // Build the mask for the vectorized insertelement instructions.
6771               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6772                 VU = IEBase;
6773                 do {
6774                   IEBase = cast<InsertElementInst>(Base);
6775                   int Idx = *getInsertIndex(IEBase);
6776                   assert(Mask[Idx] == UndefMaskElem &&
6777                          "InsertElementInstruction used already.");
6778                   Mask[Idx] = Idx;
6779                   Base = IEBase->getOperand(0);
6780                 } while (E == getTreeEntry(Base));
6781                 break;
6782               }
6783               Base = cast<InsertElementInst>(Base)->getOperand(0);
6784             }
6785             FirstUsers.emplace_back(VU, ScalarTE);
6786             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6787             VecId = FirstUsers.size() - 1;
6788           } else {
6789             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6790               It->first = VU;
6791             VecId = std::distance(FirstUsers.begin(), It);
6792           }
6793           int InIdx = *InsertIdx;
6794           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6795           if (Mask.empty())
6796             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6797           Mask[InIdx] = EU.Lane;
6798           DemandedElts[VecId].setBit(InIdx);
6799           continue;
6800         }
6801       }
6802     }
6803 
6804     // If we plan to rewrite the tree in a smaller type, we will need to sign
6805     // extend the extracted value back to the original type. Here, we account
6806     // for the extract and the added cost of the sign extend if needed.
6807     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6808     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6809     if (MinBWs.count(ScalarRoot)) {
6810       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6811       auto Extend =
6812           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6813       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6814       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6815                                                    VecTy, EU.Lane);
6816     } else {
6817       ExtractCost +=
6818           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6819     }
6820   }
6821 
6822   InstructionCost SpillCost = getSpillCost();
6823   Cost += SpillCost + ExtractCost;
6824   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6825     InstructionCost C = 0;
6826     unsigned VF = Mask.size();
6827     unsigned VecVF = TE->getVectorFactor();
6828     if (VF != VecVF &&
6829         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6830          (all_of(Mask,
6831                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6832           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6833       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6834       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6835                 OrigMask.begin());
6836       C = TTI->getShuffleCost(
6837           TTI::SK_PermuteSingleSrc,
6838           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6839       LLVM_DEBUG(
6840           dbgs() << "SLP: Adding cost " << C
6841                  << " for final shuffle of insertelement external users.\n";
6842           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6843       Cost += C;
6844       return std::make_pair(TE, true);
6845     }
6846     return std::make_pair(TE, false);
6847   };
6848   // Calculate the cost of the reshuffled vectors, if any.
6849   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6850     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6851     unsigned VF = ShuffleMasks[I].begin()->second.size();
6852     auto *FTy = FixedVectorType::get(
6853         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6854     auto Vector = ShuffleMasks[I].takeVector();
6855     auto &&EstimateShufflesCost = [this, FTy,
6856                                    &Cost](ArrayRef<int> Mask,
6857                                           ArrayRef<const TreeEntry *> TEs) {
6858       assert((TEs.size() == 1 || TEs.size() == 2) &&
6859              "Expected exactly 1 or 2 tree entries.");
6860       if (TEs.size() == 1) {
6861         int Limit = 2 * Mask.size();
6862         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6863             !ShuffleVectorInst::isIdentityMask(Mask)) {
6864           InstructionCost C =
6865               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6866           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6867                             << " for final shuffle of insertelement "
6868                                "external users.\n";
6869                      TEs.front()->dump();
6870                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6871           Cost += C;
6872         }
6873       } else {
6874         InstructionCost C =
6875             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
6876         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6877                           << " for final shuffle of vector node and external "
6878                              "insertelement users.\n";
6879                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
6880                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
6881         Cost += C;
6882       }
6883       return TEs.back();
6884     };
6885     (void)performExtractsShuffleAction<const TreeEntry>(
6886         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
6887         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
6888         EstimateShufflesCost);
6889     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6890         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
6891         /*Insert*/ true, /*Extract*/ false);
6892     Cost -= InsertCost;
6893   }
6894 
6895 #ifndef NDEBUG
6896   SmallString<256> Str;
6897   {
6898     raw_svector_ostream OS(Str);
6899     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6900        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6901        << "SLP: Total Cost = " << Cost << ".\n";
6902   }
6903   LLVM_DEBUG(dbgs() << Str);
6904   if (ViewSLPTree)
6905     ViewGraph(this, "SLP" + F->getName(), false, Str);
6906 #endif
6907 
6908   return Cost;
6909 }
6910 
6911 Optional<TargetTransformInfo::ShuffleKind>
6912 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6913                                SmallVectorImpl<const TreeEntry *> &Entries) {
6914   // TODO: currently checking only for Scalars in the tree entry, need to count
6915   // reused elements too for better cost estimation.
6916   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6917   Entries.clear();
6918   // Build a lists of values to tree entries.
6919   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6920   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6921     if (EntryPtr.get() == TE)
6922       break;
6923     if (EntryPtr->State != TreeEntry::NeedToGather)
6924       continue;
6925     for (Value *V : EntryPtr->Scalars)
6926       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6927   }
6928   // Find all tree entries used by the gathered values. If no common entries
6929   // found - not a shuffle.
6930   // Here we build a set of tree nodes for each gathered value and trying to
6931   // find the intersection between these sets. If we have at least one common
6932   // tree node for each gathered value - we have just a permutation of the
6933   // single vector. If we have 2 different sets, we're in situation where we
6934   // have a permutation of 2 input vectors.
6935   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6936   DenseMap<Value *, int> UsedValuesEntry;
6937   for (Value *V : TE->Scalars) {
6938     if (isa<UndefValue>(V))
6939       continue;
6940     // Build a list of tree entries where V is used.
6941     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6942     auto It = ValueToTEs.find(V);
6943     if (It != ValueToTEs.end())
6944       VToTEs = It->second;
6945     if (const TreeEntry *VTE = getTreeEntry(V))
6946       VToTEs.insert(VTE);
6947     if (VToTEs.empty())
6948       return None;
6949     if (UsedTEs.empty()) {
6950       // The first iteration, just insert the list of nodes to vector.
6951       UsedTEs.push_back(VToTEs);
6952     } else {
6953       // Need to check if there are any previously used tree nodes which use V.
6954       // If there are no such nodes, consider that we have another one input
6955       // vector.
6956       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6957       unsigned Idx = 0;
6958       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6959         // Do we have a non-empty intersection of previously listed tree entries
6960         // and tree entries using current V?
6961         set_intersect(VToTEs, Set);
6962         if (!VToTEs.empty()) {
6963           // Yes, write the new subset and continue analysis for the next
6964           // scalar.
6965           Set.swap(VToTEs);
6966           break;
6967         }
6968         VToTEs = SavedVToTEs;
6969         ++Idx;
6970       }
6971       // No non-empty intersection found - need to add a second set of possible
6972       // source vectors.
6973       if (Idx == UsedTEs.size()) {
6974         // If the number of input vectors is greater than 2 - not a permutation,
6975         // fallback to the regular gather.
6976         if (UsedTEs.size() == 2)
6977           return None;
6978         UsedTEs.push_back(SavedVToTEs);
6979         Idx = UsedTEs.size() - 1;
6980       }
6981       UsedValuesEntry.try_emplace(V, Idx);
6982     }
6983   }
6984 
6985   if (UsedTEs.empty()) {
6986     assert(all_of(TE->Scalars, UndefValue::classof) &&
6987            "Expected vector of undefs only.");
6988     return None;
6989   }
6990 
6991   unsigned VF = 0;
6992   if (UsedTEs.size() == 1) {
6993     // Try to find the perfect match in another gather node at first.
6994     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6995       return EntryPtr->isSame(TE->Scalars);
6996     });
6997     if (It != UsedTEs.front().end()) {
6998       Entries.push_back(*It);
6999       std::iota(Mask.begin(), Mask.end(), 0);
7000       return TargetTransformInfo::SK_PermuteSingleSrc;
7001     }
7002     // No perfect match, just shuffle, so choose the first tree node.
7003     Entries.push_back(*UsedTEs.front().begin());
7004   } else {
7005     // Try to find nodes with the same vector factor.
7006     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
7007     DenseMap<int, const TreeEntry *> VFToTE;
7008     for (const TreeEntry *TE : UsedTEs.front())
7009       VFToTE.try_emplace(TE->getVectorFactor(), TE);
7010     for (const TreeEntry *TE : UsedTEs.back()) {
7011       auto It = VFToTE.find(TE->getVectorFactor());
7012       if (It != VFToTE.end()) {
7013         VF = It->first;
7014         Entries.push_back(It->second);
7015         Entries.push_back(TE);
7016         break;
7017       }
7018     }
7019     // No 2 source vectors with the same vector factor - give up and do regular
7020     // gather.
7021     if (Entries.empty())
7022       return None;
7023   }
7024 
7025   // Build a shuffle mask for better cost estimation and vector emission.
7026   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
7027     Value *V = TE->Scalars[I];
7028     if (isa<UndefValue>(V))
7029       continue;
7030     unsigned Idx = UsedValuesEntry.lookup(V);
7031     const TreeEntry *VTE = Entries[Idx];
7032     int FoundLane = VTE->findLaneForValue(V);
7033     Mask[I] = Idx * VF + FoundLane;
7034     // Extra check required by isSingleSourceMaskImpl function (called by
7035     // ShuffleVectorInst::isSingleSourceMask).
7036     if (Mask[I] >= 2 * E)
7037       return None;
7038   }
7039   switch (Entries.size()) {
7040   case 1:
7041     return TargetTransformInfo::SK_PermuteSingleSrc;
7042   case 2:
7043     return TargetTransformInfo::SK_PermuteTwoSrc;
7044   default:
7045     break;
7046   }
7047   return None;
7048 }
7049 
7050 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
7051                                        const APInt &ShuffledIndices,
7052                                        bool NeedToShuffle) const {
7053   InstructionCost Cost =
7054       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
7055                                     /*Extract*/ false);
7056   if (NeedToShuffle)
7057     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
7058   return Cost;
7059 }
7060 
7061 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
7062   // Find the type of the operands in VL.
7063   Type *ScalarTy = VL[0]->getType();
7064   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
7065     ScalarTy = SI->getValueOperand()->getType();
7066   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7067   bool DuplicateNonConst = false;
7068   // Find the cost of inserting/extracting values from the vector.
7069   // Check if the same elements are inserted several times and count them as
7070   // shuffle candidates.
7071   APInt ShuffledElements = APInt::getZero(VL.size());
7072   DenseSet<Value *> UniqueElements;
7073   // Iterate in reverse order to consider insert elements with the high cost.
7074   for (unsigned I = VL.size(); I > 0; --I) {
7075     unsigned Idx = I - 1;
7076     // No need to shuffle duplicates for constants.
7077     if (isConstant(VL[Idx])) {
7078       ShuffledElements.setBit(Idx);
7079       continue;
7080     }
7081     if (!UniqueElements.insert(VL[Idx]).second) {
7082       DuplicateNonConst = true;
7083       ShuffledElements.setBit(Idx);
7084     }
7085   }
7086   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
7087 }
7088 
7089 // Perform operand reordering on the instructions in VL and return the reordered
7090 // operands in Left and Right.
7091 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
7092                                              SmallVectorImpl<Value *> &Left,
7093                                              SmallVectorImpl<Value *> &Right,
7094                                              const DataLayout &DL,
7095                                              ScalarEvolution &SE,
7096                                              const BoUpSLP &R) {
7097   if (VL.empty())
7098     return;
7099   VLOperands Ops(VL, DL, SE, R);
7100   // Reorder the operands in place.
7101   Ops.reorder();
7102   Left = Ops.getVL(0);
7103   Right = Ops.getVL(1);
7104 }
7105 
7106 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
7107   // Get the basic block this bundle is in. All instructions in the bundle
7108   // should be in this block.
7109   auto *Front = E->getMainOp();
7110   auto *BB = Front->getParent();
7111   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
7112     auto *I = cast<Instruction>(V);
7113     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
7114   }));
7115 
7116   auto &&FindLastInst = [E, Front]() {
7117     Instruction *LastInst = Front;
7118     for (Value *V : E->Scalars) {
7119       auto *I = dyn_cast<Instruction>(V);
7120       if (!I)
7121         continue;
7122       if (LastInst->comesBefore(I))
7123         LastInst = I;
7124     }
7125     return LastInst;
7126   };
7127 
7128   auto &&FindFirstInst = [E, Front]() {
7129     Instruction *FirstInst = Front;
7130     for (Value *V : E->Scalars) {
7131       auto *I = dyn_cast<Instruction>(V);
7132       if (!I)
7133         continue;
7134       if (I->comesBefore(FirstInst))
7135         FirstInst = I;
7136     }
7137     return FirstInst;
7138   };
7139 
7140   // Set the insert point to the beginning of the basic block if the entry
7141   // should not be scheduled.
7142   if (E->State != TreeEntry::NeedToGather &&
7143       doesNotNeedToSchedule(E->Scalars)) {
7144     Instruction *InsertInst;
7145     if (all_of(E->Scalars, isUsedOutsideBlock))
7146       InsertInst = FindLastInst();
7147     else
7148       InsertInst = FindFirstInst();
7149     // If the instruction is PHI, set the insert point after all the PHIs.
7150     if (isa<PHINode>(InsertInst))
7151       InsertInst = BB->getFirstNonPHI();
7152     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7153     Builder.SetInsertPoint(BB, InsertPt);
7154     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7155     return;
7156   }
7157 
7158   // The last instruction in the bundle in program order.
7159   Instruction *LastInst = nullptr;
7160 
7161   // Find the last instruction. The common case should be that BB has been
7162   // scheduled, and the last instruction is VL.back(). So we start with
7163   // VL.back() and iterate over schedule data until we reach the end of the
7164   // bundle. The end of the bundle is marked by null ScheduleData.
7165   if (BlocksSchedules.count(BB)) {
7166     Value *V = E->isOneOf(E->Scalars.back());
7167     if (doesNotNeedToBeScheduled(V))
7168       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7169     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7170     if (Bundle && Bundle->isPartOfBundle())
7171       for (; Bundle; Bundle = Bundle->NextInBundle)
7172         if (Bundle->OpValue == Bundle->Inst)
7173           LastInst = Bundle->Inst;
7174   }
7175 
7176   // LastInst can still be null at this point if there's either not an entry
7177   // for BB in BlocksSchedules or there's no ScheduleData available for
7178   // VL.back(). This can be the case if buildTree_rec aborts for various
7179   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7180   // size is reached, etc.). ScheduleData is initialized in the scheduling
7181   // "dry-run".
7182   //
7183   // If this happens, we can still find the last instruction by brute force. We
7184   // iterate forwards from Front (inclusive) until we either see all
7185   // instructions in the bundle or reach the end of the block. If Front is the
7186   // last instruction in program order, LastInst will be set to Front, and we
7187   // will visit all the remaining instructions in the block.
7188   //
7189   // One of the reasons we exit early from buildTree_rec is to place an upper
7190   // bound on compile-time. Thus, taking an additional compile-time hit here is
7191   // not ideal. However, this should be exceedingly rare since it requires that
7192   // we both exit early from buildTree_rec and that the bundle be out-of-order
7193   // (causing us to iterate all the way to the end of the block).
7194   if (!LastInst) {
7195     LastInst = FindLastInst();
7196     // If the instruction is PHI, set the insert point after all the PHIs.
7197     if (isa<PHINode>(LastInst))
7198       LastInst = BB->getFirstNonPHI()->getPrevNode();
7199   }
7200   assert(LastInst && "Failed to find last instruction in bundle");
7201 
7202   // Set the insertion point after the last instruction in the bundle. Set the
7203   // debug location to Front.
7204   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7205   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7206 }
7207 
7208 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7209   // List of instructions/lanes from current block and/or the blocks which are
7210   // part of the current loop. These instructions will be inserted at the end to
7211   // make it possible to optimize loops and hoist invariant instructions out of
7212   // the loops body with better chances for success.
7213   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7214   SmallSet<int, 4> PostponedIndices;
7215   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7216   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7217     SmallPtrSet<BasicBlock *, 4> Visited;
7218     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7219       InsertBB = InsertBB->getSinglePredecessor();
7220     return InsertBB && InsertBB == InstBB;
7221   };
7222   for (int I = 0, E = VL.size(); I < E; ++I) {
7223     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7224       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7225            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7226           PostponedIndices.insert(I).second)
7227         PostponedInsts.emplace_back(Inst, I);
7228   }
7229 
7230   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7231     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7232     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7233     if (!InsElt)
7234       return Vec;
7235     GatherShuffleSeq.insert(InsElt);
7236     CSEBlocks.insert(InsElt->getParent());
7237     // Add to our 'need-to-extract' list.
7238     if (TreeEntry *Entry = getTreeEntry(V)) {
7239       // Find which lane we need to extract.
7240       unsigned FoundLane = Entry->findLaneForValue(V);
7241       ExternalUses.emplace_back(V, InsElt, FoundLane);
7242     }
7243     return Vec;
7244   };
7245   Value *Val0 =
7246       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7247   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7248   Value *Vec = PoisonValue::get(VecTy);
7249   SmallVector<int> NonConsts;
7250   // Insert constant values at first.
7251   for (int I = 0, E = VL.size(); I < E; ++I) {
7252     if (PostponedIndices.contains(I))
7253       continue;
7254     if (!isConstant(VL[I])) {
7255       NonConsts.push_back(I);
7256       continue;
7257     }
7258     Vec = CreateInsertElement(Vec, VL[I], I);
7259   }
7260   // Insert non-constant values.
7261   for (int I : NonConsts)
7262     Vec = CreateInsertElement(Vec, VL[I], I);
7263   // Append instructions, which are/may be part of the loop, in the end to make
7264   // it possible to hoist non-loop-based instructions.
7265   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7266     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7267 
7268   return Vec;
7269 }
7270 
7271 namespace {
7272 /// Merges shuffle masks and emits final shuffle instruction, if required.
7273 class ShuffleInstructionBuilder {
7274   IRBuilderBase &Builder;
7275   const unsigned VF = 0;
7276   bool IsFinalized = false;
7277   SmallVector<int, 4> Mask;
7278   /// Holds all of the instructions that we gathered.
7279   SetVector<Instruction *> &GatherShuffleSeq;
7280   /// A list of blocks that we are going to CSE.
7281   SetVector<BasicBlock *> &CSEBlocks;
7282 
7283 public:
7284   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7285                             SetVector<Instruction *> &GatherShuffleSeq,
7286                             SetVector<BasicBlock *> &CSEBlocks)
7287       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7288         CSEBlocks(CSEBlocks) {}
7289 
7290   /// Adds a mask, inverting it before applying.
7291   void addInversedMask(ArrayRef<unsigned> SubMask) {
7292     if (SubMask.empty())
7293       return;
7294     SmallVector<int, 4> NewMask;
7295     inversePermutation(SubMask, NewMask);
7296     addMask(NewMask);
7297   }
7298 
7299   /// Functions adds masks, merging them into  single one.
7300   void addMask(ArrayRef<unsigned> SubMask) {
7301     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7302     addMask(NewMask);
7303   }
7304 
7305   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7306 
7307   Value *finalize(Value *V) {
7308     IsFinalized = true;
7309     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7310     if (VF == ValueVF && Mask.empty())
7311       return V;
7312     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7313     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7314     addMask(NormalizedMask);
7315 
7316     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7317       return V;
7318     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7319     if (auto *I = dyn_cast<Instruction>(Vec)) {
7320       GatherShuffleSeq.insert(I);
7321       CSEBlocks.insert(I->getParent());
7322     }
7323     return Vec;
7324   }
7325 
7326   ~ShuffleInstructionBuilder() {
7327     assert((IsFinalized || Mask.empty()) &&
7328            "Shuffle construction must be finalized.");
7329   }
7330 };
7331 } // namespace
7332 
7333 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7334   const unsigned VF = VL.size();
7335   InstructionsState S = getSameOpcode(VL);
7336   if (S.getOpcode()) {
7337     if (TreeEntry *E = getTreeEntry(S.OpValue))
7338       if (E->isSame(VL)) {
7339         Value *V = vectorizeTree(E);
7340         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7341           if (!E->ReuseShuffleIndices.empty()) {
7342             // Reshuffle to get only unique values.
7343             // If some of the scalars are duplicated in the vectorization tree
7344             // entry, we do not vectorize them but instead generate a mask for
7345             // the reuses. But if there are several users of the same entry,
7346             // they may have different vectorization factors. This is especially
7347             // important for PHI nodes. In this case, we need to adapt the
7348             // resulting instruction for the user vectorization factor and have
7349             // to reshuffle it again to take only unique elements of the vector.
7350             // Without this code the function incorrectly returns reduced vector
7351             // instruction with the same elements, not with the unique ones.
7352 
7353             // block:
7354             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7355             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7356             // ... (use %2)
7357             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7358             // br %block
7359             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7360             SmallSet<int, 4> UsedIdxs;
7361             int Pos = 0;
7362             int Sz = VL.size();
7363             for (int Idx : E->ReuseShuffleIndices) {
7364               if (Idx != Sz && Idx != UndefMaskElem &&
7365                   UsedIdxs.insert(Idx).second)
7366                 UniqueIdxs[Idx] = Pos;
7367               ++Pos;
7368             }
7369             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7370                                             "less than original vector size.");
7371             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7372             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7373           } else {
7374             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7375                    "Expected vectorization factor less "
7376                    "than original vector size.");
7377             SmallVector<int> UniformMask(VF, 0);
7378             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7379             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7380           }
7381           if (auto *I = dyn_cast<Instruction>(V)) {
7382             GatherShuffleSeq.insert(I);
7383             CSEBlocks.insert(I->getParent());
7384           }
7385         }
7386         return V;
7387       }
7388   }
7389 
7390   // Can't vectorize this, so simply build a new vector with each lane
7391   // corresponding to the requested value.
7392   return createBuildVector(VL);
7393 }
7394 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7395   unsigned VF = VL.size();
7396   // Exploit possible reuse of values across lanes.
7397   SmallVector<int> ReuseShuffleIndicies;
7398   SmallVector<Value *> UniqueValues;
7399   if (VL.size() > 2) {
7400     DenseMap<Value *, unsigned> UniquePositions;
7401     unsigned NumValues =
7402         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7403                                     return !isa<UndefValue>(V);
7404                                   }).base());
7405     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7406     int UniqueVals = 0;
7407     for (Value *V : VL.drop_back(VL.size() - VF)) {
7408       if (isa<UndefValue>(V)) {
7409         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7410         continue;
7411       }
7412       if (isConstant(V)) {
7413         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7414         UniqueValues.emplace_back(V);
7415         continue;
7416       }
7417       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7418       ReuseShuffleIndicies.emplace_back(Res.first->second);
7419       if (Res.second) {
7420         UniqueValues.emplace_back(V);
7421         ++UniqueVals;
7422       }
7423     }
7424     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7425       // Emit pure splat vector.
7426       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7427                                   UndefMaskElem);
7428     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7429       ReuseShuffleIndicies.clear();
7430       UniqueValues.clear();
7431       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7432     }
7433     UniqueValues.append(VF - UniqueValues.size(),
7434                         PoisonValue::get(VL[0]->getType()));
7435     VL = UniqueValues;
7436   }
7437 
7438   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7439                                            CSEBlocks);
7440   Value *Vec = gather(VL);
7441   if (!ReuseShuffleIndicies.empty()) {
7442     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7443     Vec = ShuffleBuilder.finalize(Vec);
7444   }
7445   return Vec;
7446 }
7447 
7448 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7449   IRBuilder<>::InsertPointGuard Guard(Builder);
7450 
7451   if (E->VectorizedValue) {
7452     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7453     return E->VectorizedValue;
7454   }
7455 
7456   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7457   unsigned VF = E->getVectorFactor();
7458   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7459                                            CSEBlocks);
7460   if (E->State == TreeEntry::NeedToGather) {
7461     if (E->getMainOp())
7462       setInsertPointAfterBundle(E);
7463     Value *Vec;
7464     SmallVector<int> Mask;
7465     SmallVector<const TreeEntry *> Entries;
7466     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7467         isGatherShuffledEntry(E, Mask, Entries);
7468     if (Shuffle.hasValue()) {
7469       assert((Entries.size() == 1 || Entries.size() == 2) &&
7470              "Expected shuffle of 1 or 2 entries.");
7471       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7472                                         Entries.back()->VectorizedValue, Mask);
7473       if (auto *I = dyn_cast<Instruction>(Vec)) {
7474         GatherShuffleSeq.insert(I);
7475         CSEBlocks.insert(I->getParent());
7476       }
7477     } else {
7478       Vec = gather(E->Scalars);
7479     }
7480     if (NeedToShuffleReuses) {
7481       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7482       Vec = ShuffleBuilder.finalize(Vec);
7483     }
7484     E->VectorizedValue = Vec;
7485     return Vec;
7486   }
7487 
7488   assert((E->State == TreeEntry::Vectorize ||
7489           E->State == TreeEntry::ScatterVectorize) &&
7490          "Unhandled state");
7491   unsigned ShuffleOrOp =
7492       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7493   Instruction *VL0 = E->getMainOp();
7494   Type *ScalarTy = VL0->getType();
7495   if (auto *Store = dyn_cast<StoreInst>(VL0))
7496     ScalarTy = Store->getValueOperand()->getType();
7497   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7498     ScalarTy = IE->getOperand(1)->getType();
7499   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7500   switch (ShuffleOrOp) {
7501     case Instruction::PHI: {
7502       assert(
7503           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7504           "PHI reordering is free.");
7505       auto *PH = cast<PHINode>(VL0);
7506       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7507       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7508       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7509       Value *V = NewPhi;
7510 
7511       // Adjust insertion point once all PHI's have been generated.
7512       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7513       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7514 
7515       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7516       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7517       V = ShuffleBuilder.finalize(V);
7518 
7519       E->VectorizedValue = V;
7520 
7521       // PHINodes may have multiple entries from the same block. We want to
7522       // visit every block once.
7523       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7524 
7525       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7526         ValueList Operands;
7527         BasicBlock *IBB = PH->getIncomingBlock(i);
7528 
7529         if (!VisitedBBs.insert(IBB).second) {
7530           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7531           continue;
7532         }
7533 
7534         Builder.SetInsertPoint(IBB->getTerminator());
7535         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7536         Value *Vec = vectorizeTree(E->getOperand(i));
7537         NewPhi->addIncoming(Vec, IBB);
7538       }
7539 
7540       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7541              "Invalid number of incoming values");
7542       return V;
7543     }
7544 
7545     case Instruction::ExtractElement: {
7546       Value *V = E->getSingleOperand(0);
7547       Builder.SetInsertPoint(VL0);
7548       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7549       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7550       V = ShuffleBuilder.finalize(V);
7551       E->VectorizedValue = V;
7552       return V;
7553     }
7554     case Instruction::ExtractValue: {
7555       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7556       Builder.SetInsertPoint(LI);
7557       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7558       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7559       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7560       Value *NewV = propagateMetadata(V, E->Scalars);
7561       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7562       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7563       NewV = ShuffleBuilder.finalize(NewV);
7564       E->VectorizedValue = NewV;
7565       return NewV;
7566     }
7567     case Instruction::InsertElement: {
7568       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7569       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7570       Value *V = vectorizeTree(E->getOperand(1));
7571 
7572       // Create InsertVector shuffle if necessary
7573       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7574         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7575       }));
7576       const unsigned NumElts =
7577           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7578       const unsigned NumScalars = E->Scalars.size();
7579 
7580       unsigned Offset = *getInsertIndex(VL0);
7581       assert(Offset < NumElts && "Failed to find vector index offset");
7582 
7583       // Create shuffle to resize vector
7584       SmallVector<int> Mask;
7585       if (!E->ReorderIndices.empty()) {
7586         inversePermutation(E->ReorderIndices, Mask);
7587         Mask.append(NumElts - NumScalars, UndefMaskElem);
7588       } else {
7589         Mask.assign(NumElts, UndefMaskElem);
7590         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7591       }
7592       // Create InsertVector shuffle if necessary
7593       bool IsIdentity = true;
7594       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7595       Mask.swap(PrevMask);
7596       for (unsigned I = 0; I < NumScalars; ++I) {
7597         Value *Scalar = E->Scalars[PrevMask[I]];
7598         unsigned InsertIdx = *getInsertIndex(Scalar);
7599         IsIdentity &= InsertIdx - Offset == I;
7600         Mask[InsertIdx - Offset] = I;
7601       }
7602       if (!IsIdentity || NumElts != NumScalars) {
7603         V = Builder.CreateShuffleVector(V, Mask);
7604         if (auto *I = dyn_cast<Instruction>(V)) {
7605           GatherShuffleSeq.insert(I);
7606           CSEBlocks.insert(I->getParent());
7607         }
7608       }
7609 
7610       if ((!IsIdentity || Offset != 0 ||
7611            !isUndefVector(FirstInsert->getOperand(0))) &&
7612           NumElts != NumScalars) {
7613         SmallVector<int> InsertMask(NumElts);
7614         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7615         for (unsigned I = 0; I < NumElts; I++) {
7616           if (Mask[I] != UndefMaskElem)
7617             InsertMask[Offset + I] = NumElts + I;
7618         }
7619 
7620         V = Builder.CreateShuffleVector(
7621             FirstInsert->getOperand(0), V, InsertMask,
7622             cast<Instruction>(E->Scalars.back())->getName());
7623         if (auto *I = dyn_cast<Instruction>(V)) {
7624           GatherShuffleSeq.insert(I);
7625           CSEBlocks.insert(I->getParent());
7626         }
7627       }
7628 
7629       ++NumVectorInstructions;
7630       E->VectorizedValue = V;
7631       return V;
7632     }
7633     case Instruction::ZExt:
7634     case Instruction::SExt:
7635     case Instruction::FPToUI:
7636     case Instruction::FPToSI:
7637     case Instruction::FPExt:
7638     case Instruction::PtrToInt:
7639     case Instruction::IntToPtr:
7640     case Instruction::SIToFP:
7641     case Instruction::UIToFP:
7642     case Instruction::Trunc:
7643     case Instruction::FPTrunc:
7644     case Instruction::BitCast: {
7645       setInsertPointAfterBundle(E);
7646 
7647       Value *InVec = vectorizeTree(E->getOperand(0));
7648 
7649       if (E->VectorizedValue) {
7650         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7651         return E->VectorizedValue;
7652       }
7653 
7654       auto *CI = cast<CastInst>(VL0);
7655       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7656       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7657       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7658       V = ShuffleBuilder.finalize(V);
7659 
7660       E->VectorizedValue = V;
7661       ++NumVectorInstructions;
7662       return V;
7663     }
7664     case Instruction::FCmp:
7665     case Instruction::ICmp: {
7666       setInsertPointAfterBundle(E);
7667 
7668       Value *L = vectorizeTree(E->getOperand(0));
7669       Value *R = vectorizeTree(E->getOperand(1));
7670 
7671       if (E->VectorizedValue) {
7672         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7673         return E->VectorizedValue;
7674       }
7675 
7676       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7677       Value *V = Builder.CreateCmp(P0, L, R);
7678       propagateIRFlags(V, E->Scalars, VL0);
7679       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7680       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7681       V = ShuffleBuilder.finalize(V);
7682 
7683       E->VectorizedValue = V;
7684       ++NumVectorInstructions;
7685       return V;
7686     }
7687     case Instruction::Select: {
7688       setInsertPointAfterBundle(E);
7689 
7690       Value *Cond = vectorizeTree(E->getOperand(0));
7691       Value *True = vectorizeTree(E->getOperand(1));
7692       Value *False = vectorizeTree(E->getOperand(2));
7693 
7694       if (E->VectorizedValue) {
7695         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7696         return E->VectorizedValue;
7697       }
7698 
7699       Value *V = Builder.CreateSelect(Cond, True, False);
7700       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7701       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7702       V = ShuffleBuilder.finalize(V);
7703 
7704       E->VectorizedValue = V;
7705       ++NumVectorInstructions;
7706       return V;
7707     }
7708     case Instruction::FNeg: {
7709       setInsertPointAfterBundle(E);
7710 
7711       Value *Op = vectorizeTree(E->getOperand(0));
7712 
7713       if (E->VectorizedValue) {
7714         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7715         return E->VectorizedValue;
7716       }
7717 
7718       Value *V = Builder.CreateUnOp(
7719           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7720       propagateIRFlags(V, E->Scalars, VL0);
7721       if (auto *I = dyn_cast<Instruction>(V))
7722         V = propagateMetadata(I, E->Scalars);
7723 
7724       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7725       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7726       V = ShuffleBuilder.finalize(V);
7727 
7728       E->VectorizedValue = V;
7729       ++NumVectorInstructions;
7730 
7731       return V;
7732     }
7733     case Instruction::Add:
7734     case Instruction::FAdd:
7735     case Instruction::Sub:
7736     case Instruction::FSub:
7737     case Instruction::Mul:
7738     case Instruction::FMul:
7739     case Instruction::UDiv:
7740     case Instruction::SDiv:
7741     case Instruction::FDiv:
7742     case Instruction::URem:
7743     case Instruction::SRem:
7744     case Instruction::FRem:
7745     case Instruction::Shl:
7746     case Instruction::LShr:
7747     case Instruction::AShr:
7748     case Instruction::And:
7749     case Instruction::Or:
7750     case Instruction::Xor: {
7751       setInsertPointAfterBundle(E);
7752 
7753       Value *LHS = vectorizeTree(E->getOperand(0));
7754       Value *RHS = vectorizeTree(E->getOperand(1));
7755 
7756       if (E->VectorizedValue) {
7757         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7758         return E->VectorizedValue;
7759       }
7760 
7761       Value *V = Builder.CreateBinOp(
7762           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7763           RHS);
7764       propagateIRFlags(V, E->Scalars, VL0);
7765       if (auto *I = dyn_cast<Instruction>(V))
7766         V = propagateMetadata(I, E->Scalars);
7767 
7768       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7769       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7770       V = ShuffleBuilder.finalize(V);
7771 
7772       E->VectorizedValue = V;
7773       ++NumVectorInstructions;
7774 
7775       return V;
7776     }
7777     case Instruction::Load: {
7778       // Loads are inserted at the head of the tree because we don't want to
7779       // sink them all the way down past store instructions.
7780       setInsertPointAfterBundle(E);
7781 
7782       LoadInst *LI = cast<LoadInst>(VL0);
7783       Instruction *NewLI;
7784       unsigned AS = LI->getPointerAddressSpace();
7785       Value *PO = LI->getPointerOperand();
7786       if (E->State == TreeEntry::Vectorize) {
7787         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7788         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7789 
7790         // The pointer operand uses an in-tree scalar so we add the new BitCast
7791         // or LoadInst to ExternalUses list to make sure that an extract will
7792         // be generated in the future.
7793         if (TreeEntry *Entry = getTreeEntry(PO)) {
7794           // Find which lane we need to extract.
7795           unsigned FoundLane = Entry->findLaneForValue(PO);
7796           ExternalUses.emplace_back(
7797               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7798         }
7799       } else {
7800         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7801         Value *VecPtr = vectorizeTree(E->getOperand(0));
7802         // Use the minimum alignment of the gathered loads.
7803         Align CommonAlignment = LI->getAlign();
7804         for (Value *V : E->Scalars)
7805           CommonAlignment =
7806               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7807         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7808       }
7809       Value *V = propagateMetadata(NewLI, E->Scalars);
7810 
7811       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7812       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7813       V = ShuffleBuilder.finalize(V);
7814       E->VectorizedValue = V;
7815       ++NumVectorInstructions;
7816       return V;
7817     }
7818     case Instruction::Store: {
7819       auto *SI = cast<StoreInst>(VL0);
7820       unsigned AS = SI->getPointerAddressSpace();
7821 
7822       setInsertPointAfterBundle(E);
7823 
7824       Value *VecValue = vectorizeTree(E->getOperand(0));
7825       ShuffleBuilder.addMask(E->ReorderIndices);
7826       VecValue = ShuffleBuilder.finalize(VecValue);
7827 
7828       Value *ScalarPtr = SI->getPointerOperand();
7829       Value *VecPtr = Builder.CreateBitCast(
7830           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7831       StoreInst *ST =
7832           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7833 
7834       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7835       // StoreInst to ExternalUses to make sure that an extract will be
7836       // generated in the future.
7837       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7838         // Find which lane we need to extract.
7839         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7840         ExternalUses.push_back(ExternalUser(
7841             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7842             FoundLane));
7843       }
7844 
7845       Value *V = propagateMetadata(ST, E->Scalars);
7846 
7847       E->VectorizedValue = V;
7848       ++NumVectorInstructions;
7849       return V;
7850     }
7851     case Instruction::GetElementPtr: {
7852       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7853       setInsertPointAfterBundle(E);
7854 
7855       Value *Op0 = vectorizeTree(E->getOperand(0));
7856 
7857       SmallVector<Value *> OpVecs;
7858       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7859         Value *OpVec = vectorizeTree(E->getOperand(J));
7860         OpVecs.push_back(OpVec);
7861       }
7862 
7863       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7864       if (Instruction *I = dyn_cast<Instruction>(V))
7865         V = propagateMetadata(I, E->Scalars);
7866 
7867       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7868       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7869       V = ShuffleBuilder.finalize(V);
7870 
7871       E->VectorizedValue = V;
7872       ++NumVectorInstructions;
7873 
7874       return V;
7875     }
7876     case Instruction::Call: {
7877       CallInst *CI = cast<CallInst>(VL0);
7878       setInsertPointAfterBundle(E);
7879 
7880       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7881       if (Function *FI = CI->getCalledFunction())
7882         IID = FI->getIntrinsicID();
7883 
7884       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7885 
7886       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7887       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7888                           VecCallCosts.first <= VecCallCosts.second;
7889 
7890       Value *ScalarArg = nullptr;
7891       std::vector<Value *> OpVecs;
7892       SmallVector<Type *, 2> TysForDecl =
7893           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7894       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7895         ValueList OpVL;
7896         // Some intrinsics have scalar arguments. This argument should not be
7897         // vectorized.
7898         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7899           CallInst *CEI = cast<CallInst>(VL0);
7900           ScalarArg = CEI->getArgOperand(j);
7901           OpVecs.push_back(CEI->getArgOperand(j));
7902           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7903             TysForDecl.push_back(ScalarArg->getType());
7904           continue;
7905         }
7906 
7907         Value *OpVec = vectorizeTree(E->getOperand(j));
7908         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7909         OpVecs.push_back(OpVec);
7910         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7911           TysForDecl.push_back(OpVec->getType());
7912       }
7913 
7914       Function *CF;
7915       if (!UseIntrinsic) {
7916         VFShape Shape =
7917             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7918                                   VecTy->getNumElements())),
7919                          false /*HasGlobalPred*/);
7920         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7921       } else {
7922         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7923       }
7924 
7925       SmallVector<OperandBundleDef, 1> OpBundles;
7926       CI->getOperandBundlesAsDefs(OpBundles);
7927       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7928 
7929       // The scalar argument uses an in-tree scalar so we add the new vectorized
7930       // call to ExternalUses list to make sure that an extract will be
7931       // generated in the future.
7932       if (ScalarArg) {
7933         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7934           // Find which lane we need to extract.
7935           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7936           ExternalUses.push_back(
7937               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7938         }
7939       }
7940 
7941       propagateIRFlags(V, E->Scalars, VL0);
7942       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7943       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7944       V = ShuffleBuilder.finalize(V);
7945 
7946       E->VectorizedValue = V;
7947       ++NumVectorInstructions;
7948       return V;
7949     }
7950     case Instruction::ShuffleVector: {
7951       assert(E->isAltShuffle() &&
7952              ((Instruction::isBinaryOp(E->getOpcode()) &&
7953                Instruction::isBinaryOp(E->getAltOpcode())) ||
7954               (Instruction::isCast(E->getOpcode()) &&
7955                Instruction::isCast(E->getAltOpcode())) ||
7956               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7957              "Invalid Shuffle Vector Operand");
7958 
7959       Value *LHS = nullptr, *RHS = nullptr;
7960       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7961         setInsertPointAfterBundle(E);
7962         LHS = vectorizeTree(E->getOperand(0));
7963         RHS = vectorizeTree(E->getOperand(1));
7964       } else {
7965         setInsertPointAfterBundle(E);
7966         LHS = vectorizeTree(E->getOperand(0));
7967       }
7968 
7969       if (E->VectorizedValue) {
7970         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7971         return E->VectorizedValue;
7972       }
7973 
7974       Value *V0, *V1;
7975       if (Instruction::isBinaryOp(E->getOpcode())) {
7976         V0 = Builder.CreateBinOp(
7977             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7978         V1 = Builder.CreateBinOp(
7979             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7980       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7981         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7982         auto *AltCI = cast<CmpInst>(E->getAltOp());
7983         CmpInst::Predicate AltPred = AltCI->getPredicate();
7984         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7985       } else {
7986         V0 = Builder.CreateCast(
7987             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7988         V1 = Builder.CreateCast(
7989             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7990       }
7991       // Add V0 and V1 to later analysis to try to find and remove matching
7992       // instruction, if any.
7993       for (Value *V : {V0, V1}) {
7994         if (auto *I = dyn_cast<Instruction>(V)) {
7995           GatherShuffleSeq.insert(I);
7996           CSEBlocks.insert(I->getParent());
7997         }
7998       }
7999 
8000       // Create shuffle to take alternate operations from the vector.
8001       // Also, gather up main and alt scalar ops to propagate IR flags to
8002       // each vector operation.
8003       ValueList OpScalars, AltScalars;
8004       SmallVector<int> Mask;
8005       buildShuffleEntryMask(
8006           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
8007           [E](Instruction *I) {
8008             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
8009             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
8010           },
8011           Mask, &OpScalars, &AltScalars);
8012 
8013       propagateIRFlags(V0, OpScalars);
8014       propagateIRFlags(V1, AltScalars);
8015 
8016       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
8017       if (auto *I = dyn_cast<Instruction>(V)) {
8018         V = propagateMetadata(I, E->Scalars);
8019         GatherShuffleSeq.insert(I);
8020         CSEBlocks.insert(I->getParent());
8021       }
8022       V = ShuffleBuilder.finalize(V);
8023 
8024       E->VectorizedValue = V;
8025       ++NumVectorInstructions;
8026 
8027       return V;
8028     }
8029     default:
8030     llvm_unreachable("unknown inst");
8031   }
8032   return nullptr;
8033 }
8034 
8035 Value *BoUpSLP::vectorizeTree() {
8036   ExtraValueToDebugLocsMap ExternallyUsedValues;
8037   return vectorizeTree(ExternallyUsedValues);
8038 }
8039 
8040 Value *
8041 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8042   // All blocks must be scheduled before any instructions are inserted.
8043   for (auto &BSIter : BlocksSchedules) {
8044     scheduleBlock(BSIter.second.get());
8045   }
8046 
8047   Builder.SetInsertPoint(&F->getEntryBlock().front());
8048   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
8049 
8050   // If the vectorized tree can be rewritten in a smaller type, we truncate the
8051   // vectorized root. InstCombine will then rewrite the entire expression. We
8052   // sign extend the extracted values below.
8053   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8054   if (MinBWs.count(ScalarRoot)) {
8055     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
8056       // If current instr is a phi and not the last phi, insert it after the
8057       // last phi node.
8058       if (isa<PHINode>(I))
8059         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
8060       else
8061         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
8062     }
8063     auto BundleWidth = VectorizableTree[0]->Scalars.size();
8064     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8065     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
8066     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
8067     VectorizableTree[0]->VectorizedValue = Trunc;
8068   }
8069 
8070   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
8071                     << " values .\n");
8072 
8073   // Extract all of the elements with the external uses.
8074   for (const auto &ExternalUse : ExternalUses) {
8075     Value *Scalar = ExternalUse.Scalar;
8076     llvm::User *User = ExternalUse.User;
8077 
8078     // Skip users that we already RAUW. This happens when one instruction
8079     // has multiple uses of the same value.
8080     if (User && !is_contained(Scalar->users(), User))
8081       continue;
8082     TreeEntry *E = getTreeEntry(Scalar);
8083     assert(E && "Invalid scalar");
8084     assert(E->State != TreeEntry::NeedToGather &&
8085            "Extracting from a gather list");
8086 
8087     Value *Vec = E->VectorizedValue;
8088     assert(Vec && "Can't find vectorizable value");
8089 
8090     Value *Lane = Builder.getInt32(ExternalUse.Lane);
8091     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
8092       if (Scalar->getType() != Vec->getType()) {
8093         Value *Ex;
8094         // "Reuse" the existing extract to improve final codegen.
8095         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
8096           Ex = Builder.CreateExtractElement(ES->getOperand(0),
8097                                             ES->getOperand(1));
8098         } else {
8099           Ex = Builder.CreateExtractElement(Vec, Lane);
8100         }
8101         // If necessary, sign-extend or zero-extend ScalarRoot
8102         // to the larger type.
8103         if (!MinBWs.count(ScalarRoot))
8104           return Ex;
8105         if (MinBWs[ScalarRoot].second)
8106           return Builder.CreateSExt(Ex, Scalar->getType());
8107         return Builder.CreateZExt(Ex, Scalar->getType());
8108       }
8109       assert(isa<FixedVectorType>(Scalar->getType()) &&
8110              isa<InsertElementInst>(Scalar) &&
8111              "In-tree scalar of vector type is not insertelement?");
8112       return Vec;
8113     };
8114     // If User == nullptr, the Scalar is used as extra arg. Generate
8115     // ExtractElement instruction and update the record for this scalar in
8116     // ExternallyUsedValues.
8117     if (!User) {
8118       assert(ExternallyUsedValues.count(Scalar) &&
8119              "Scalar with nullptr as an external user must be registered in "
8120              "ExternallyUsedValues map");
8121       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8122         Builder.SetInsertPoint(VecI->getParent(),
8123                                std::next(VecI->getIterator()));
8124       } else {
8125         Builder.SetInsertPoint(&F->getEntryBlock().front());
8126       }
8127       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8128       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8129       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8130       auto It = ExternallyUsedValues.find(Scalar);
8131       assert(It != ExternallyUsedValues.end() &&
8132              "Externally used scalar is not found in ExternallyUsedValues");
8133       NewInstLocs.append(It->second);
8134       ExternallyUsedValues.erase(Scalar);
8135       // Required to update internally referenced instructions.
8136       Scalar->replaceAllUsesWith(NewInst);
8137       continue;
8138     }
8139 
8140     // Generate extracts for out-of-tree users.
8141     // Find the insertion point for the extractelement lane.
8142     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8143       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8144         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8145           if (PH->getIncomingValue(i) == Scalar) {
8146             Instruction *IncomingTerminator =
8147                 PH->getIncomingBlock(i)->getTerminator();
8148             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8149               Builder.SetInsertPoint(VecI->getParent(),
8150                                      std::next(VecI->getIterator()));
8151             } else {
8152               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8153             }
8154             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8155             CSEBlocks.insert(PH->getIncomingBlock(i));
8156             PH->setOperand(i, NewInst);
8157           }
8158         }
8159       } else {
8160         Builder.SetInsertPoint(cast<Instruction>(User));
8161         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8162         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8163         User->replaceUsesOfWith(Scalar, NewInst);
8164       }
8165     } else {
8166       Builder.SetInsertPoint(&F->getEntryBlock().front());
8167       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8168       CSEBlocks.insert(&F->getEntryBlock());
8169       User->replaceUsesOfWith(Scalar, NewInst);
8170     }
8171 
8172     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8173   }
8174 
8175   // For each vectorized value:
8176   for (auto &TEPtr : VectorizableTree) {
8177     TreeEntry *Entry = TEPtr.get();
8178 
8179     // No need to handle users of gathered values.
8180     if (Entry->State == TreeEntry::NeedToGather)
8181       continue;
8182 
8183     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8184 
8185     // For each lane:
8186     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8187       Value *Scalar = Entry->Scalars[Lane];
8188 
8189 #ifndef NDEBUG
8190       Type *Ty = Scalar->getType();
8191       if (!Ty->isVoidTy()) {
8192         for (User *U : Scalar->users()) {
8193           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8194 
8195           // It is legal to delete users in the ignorelist.
8196           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
8197                   (isa_and_nonnull<Instruction>(U) &&
8198                    isDeleted(cast<Instruction>(U)))) &&
8199                  "Deleting out-of-tree value");
8200         }
8201       }
8202 #endif
8203       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8204       eraseInstruction(cast<Instruction>(Scalar));
8205     }
8206   }
8207 
8208   Builder.ClearInsertionPoint();
8209   InstrElementSize.clear();
8210 
8211   return VectorizableTree[0]->VectorizedValue;
8212 }
8213 
8214 void BoUpSLP::optimizeGatherSequence() {
8215   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8216                     << " gather sequences instructions.\n");
8217   // LICM InsertElementInst sequences.
8218   for (Instruction *I : GatherShuffleSeq) {
8219     if (isDeleted(I))
8220       continue;
8221 
8222     // Check if this block is inside a loop.
8223     Loop *L = LI->getLoopFor(I->getParent());
8224     if (!L)
8225       continue;
8226 
8227     // Check if it has a preheader.
8228     BasicBlock *PreHeader = L->getLoopPreheader();
8229     if (!PreHeader)
8230       continue;
8231 
8232     // If the vector or the element that we insert into it are
8233     // instructions that are defined in this basic block then we can't
8234     // hoist this instruction.
8235     if (any_of(I->operands(), [L](Value *V) {
8236           auto *OpI = dyn_cast<Instruction>(V);
8237           return OpI && L->contains(OpI);
8238         }))
8239       continue;
8240 
8241     // We can hoist this instruction. Move it to the pre-header.
8242     I->moveBefore(PreHeader->getTerminator());
8243   }
8244 
8245   // Make a list of all reachable blocks in our CSE queue.
8246   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8247   CSEWorkList.reserve(CSEBlocks.size());
8248   for (BasicBlock *BB : CSEBlocks)
8249     if (DomTreeNode *N = DT->getNode(BB)) {
8250       assert(DT->isReachableFromEntry(N));
8251       CSEWorkList.push_back(N);
8252     }
8253 
8254   // Sort blocks by domination. This ensures we visit a block after all blocks
8255   // dominating it are visited.
8256   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8257     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8258            "Different nodes should have different DFS numbers");
8259     return A->getDFSNumIn() < B->getDFSNumIn();
8260   });
8261 
8262   // Less defined shuffles can be replaced by the more defined copies.
8263   // Between two shuffles one is less defined if it has the same vector operands
8264   // and its mask indeces are the same as in the first one or undefs. E.g.
8265   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8266   // poison, <0, 0, 0, 0>.
8267   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8268                                            SmallVectorImpl<int> &NewMask) {
8269     if (I1->getType() != I2->getType())
8270       return false;
8271     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8272     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8273     if (!SI1 || !SI2)
8274       return I1->isIdenticalTo(I2);
8275     if (SI1->isIdenticalTo(SI2))
8276       return true;
8277     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8278       if (SI1->getOperand(I) != SI2->getOperand(I))
8279         return false;
8280     // Check if the second instruction is more defined than the first one.
8281     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8282     ArrayRef<int> SM1 = SI1->getShuffleMask();
8283     // Count trailing undefs in the mask to check the final number of used
8284     // registers.
8285     unsigned LastUndefsCnt = 0;
8286     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8287       if (SM1[I] == UndefMaskElem)
8288         ++LastUndefsCnt;
8289       else
8290         LastUndefsCnt = 0;
8291       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8292           NewMask[I] != SM1[I])
8293         return false;
8294       if (NewMask[I] == UndefMaskElem)
8295         NewMask[I] = SM1[I];
8296     }
8297     // Check if the last undefs actually change the final number of used vector
8298     // registers.
8299     return SM1.size() - LastUndefsCnt > 1 &&
8300            TTI->getNumberOfParts(SI1->getType()) ==
8301                TTI->getNumberOfParts(
8302                    FixedVectorType::get(SI1->getType()->getElementType(),
8303                                         SM1.size() - LastUndefsCnt));
8304   };
8305   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8306   // instructions. TODO: We can further optimize this scan if we split the
8307   // instructions into different buckets based on the insert lane.
8308   SmallVector<Instruction *, 16> Visited;
8309   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8310     assert(*I &&
8311            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8312            "Worklist not sorted properly!");
8313     BasicBlock *BB = (*I)->getBlock();
8314     // For all instructions in blocks containing gather sequences:
8315     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8316       if (isDeleted(&In))
8317         continue;
8318       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8319           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8320         continue;
8321 
8322       // Check if we can replace this instruction with any of the
8323       // visited instructions.
8324       bool Replaced = false;
8325       for (Instruction *&V : Visited) {
8326         SmallVector<int> NewMask;
8327         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8328             DT->dominates(V->getParent(), In.getParent())) {
8329           In.replaceAllUsesWith(V);
8330           eraseInstruction(&In);
8331           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8332             if (!NewMask.empty())
8333               SI->setShuffleMask(NewMask);
8334           Replaced = true;
8335           break;
8336         }
8337         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8338             GatherShuffleSeq.contains(V) &&
8339             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8340             DT->dominates(In.getParent(), V->getParent())) {
8341           In.moveAfter(V);
8342           V->replaceAllUsesWith(&In);
8343           eraseInstruction(V);
8344           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8345             if (!NewMask.empty())
8346               SI->setShuffleMask(NewMask);
8347           V = &In;
8348           Replaced = true;
8349           break;
8350         }
8351       }
8352       if (!Replaced) {
8353         assert(!is_contained(Visited, &In));
8354         Visited.push_back(&In);
8355       }
8356     }
8357   }
8358   CSEBlocks.clear();
8359   GatherShuffleSeq.clear();
8360 }
8361 
8362 BoUpSLP::ScheduleData *
8363 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8364   ScheduleData *Bundle = nullptr;
8365   ScheduleData *PrevInBundle = nullptr;
8366   for (Value *V : VL) {
8367     if (doesNotNeedToBeScheduled(V))
8368       continue;
8369     ScheduleData *BundleMember = getScheduleData(V);
8370     assert(BundleMember &&
8371            "no ScheduleData for bundle member "
8372            "(maybe not in same basic block)");
8373     assert(BundleMember->isSchedulingEntity() &&
8374            "bundle member already part of other bundle");
8375     if (PrevInBundle) {
8376       PrevInBundle->NextInBundle = BundleMember;
8377     } else {
8378       Bundle = BundleMember;
8379     }
8380 
8381     // Group the instructions to a bundle.
8382     BundleMember->FirstInBundle = Bundle;
8383     PrevInBundle = BundleMember;
8384   }
8385   assert(Bundle && "Failed to find schedule bundle");
8386   return Bundle;
8387 }
8388 
8389 // Groups the instructions to a bundle (which is then a single scheduling entity)
8390 // and schedules instructions until the bundle gets ready.
8391 Optional<BoUpSLP::ScheduleData *>
8392 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8393                                             const InstructionsState &S) {
8394   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8395   // instructions.
8396   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8397       doesNotNeedToSchedule(VL))
8398     return nullptr;
8399 
8400   // Initialize the instruction bundle.
8401   Instruction *OldScheduleEnd = ScheduleEnd;
8402   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8403 
8404   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8405                                                          ScheduleData *Bundle) {
8406     // The scheduling region got new instructions at the lower end (or it is a
8407     // new region for the first bundle). This makes it necessary to
8408     // recalculate all dependencies.
8409     // It is seldom that this needs to be done a second time after adding the
8410     // initial bundle to the region.
8411     if (ScheduleEnd != OldScheduleEnd) {
8412       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8413         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8414       ReSchedule = true;
8415     }
8416     if (Bundle) {
8417       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8418                         << " in block " << BB->getName() << "\n");
8419       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8420     }
8421 
8422     if (ReSchedule) {
8423       resetSchedule();
8424       initialFillReadyList(ReadyInsts);
8425     }
8426 
8427     // Now try to schedule the new bundle or (if no bundle) just calculate
8428     // dependencies. As soon as the bundle is "ready" it means that there are no
8429     // cyclic dependencies and we can schedule it. Note that's important that we
8430     // don't "schedule" the bundle yet (see cancelScheduling).
8431     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8432            !ReadyInsts.empty()) {
8433       ScheduleData *Picked = ReadyInsts.pop_back_val();
8434       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8435              "must be ready to schedule");
8436       schedule(Picked, ReadyInsts);
8437     }
8438   };
8439 
8440   // Make sure that the scheduling region contains all
8441   // instructions of the bundle.
8442   for (Value *V : VL) {
8443     if (doesNotNeedToBeScheduled(V))
8444       continue;
8445     if (!extendSchedulingRegion(V, S)) {
8446       // If the scheduling region got new instructions at the lower end (or it
8447       // is a new region for the first bundle). This makes it necessary to
8448       // recalculate all dependencies.
8449       // Otherwise the compiler may crash trying to incorrectly calculate
8450       // dependencies and emit instruction in the wrong order at the actual
8451       // scheduling.
8452       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8453       return None;
8454     }
8455   }
8456 
8457   bool ReSchedule = false;
8458   for (Value *V : VL) {
8459     if (doesNotNeedToBeScheduled(V))
8460       continue;
8461     ScheduleData *BundleMember = getScheduleData(V);
8462     assert(BundleMember &&
8463            "no ScheduleData for bundle member (maybe not in same basic block)");
8464 
8465     // Make sure we don't leave the pieces of the bundle in the ready list when
8466     // whole bundle might not be ready.
8467     ReadyInsts.remove(BundleMember);
8468 
8469     if (!BundleMember->IsScheduled)
8470       continue;
8471     // A bundle member was scheduled as single instruction before and now
8472     // needs to be scheduled as part of the bundle. We just get rid of the
8473     // existing schedule.
8474     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8475                       << " was already scheduled\n");
8476     ReSchedule = true;
8477   }
8478 
8479   auto *Bundle = buildBundle(VL);
8480   TryScheduleBundleImpl(ReSchedule, Bundle);
8481   if (!Bundle->isReady()) {
8482     cancelScheduling(VL, S.OpValue);
8483     return None;
8484   }
8485   return Bundle;
8486 }
8487 
8488 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8489                                                 Value *OpValue) {
8490   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8491       doesNotNeedToSchedule(VL))
8492     return;
8493 
8494   if (doesNotNeedToBeScheduled(OpValue))
8495     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8496   ScheduleData *Bundle = getScheduleData(OpValue);
8497   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8498   assert(!Bundle->IsScheduled &&
8499          "Can't cancel bundle which is already scheduled");
8500   assert(Bundle->isSchedulingEntity() &&
8501          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8502          "tried to unbundle something which is not a bundle");
8503 
8504   // Remove the bundle from the ready list.
8505   if (Bundle->isReady())
8506     ReadyInsts.remove(Bundle);
8507 
8508   // Un-bundle: make single instructions out of the bundle.
8509   ScheduleData *BundleMember = Bundle;
8510   while (BundleMember) {
8511     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8512     BundleMember->FirstInBundle = BundleMember;
8513     ScheduleData *Next = BundleMember->NextInBundle;
8514     BundleMember->NextInBundle = nullptr;
8515     BundleMember->TE = nullptr;
8516     if (BundleMember->unscheduledDepsInBundle() == 0) {
8517       ReadyInsts.insert(BundleMember);
8518     }
8519     BundleMember = Next;
8520   }
8521 }
8522 
8523 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8524   // Allocate a new ScheduleData for the instruction.
8525   if (ChunkPos >= ChunkSize) {
8526     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8527     ChunkPos = 0;
8528   }
8529   return &(ScheduleDataChunks.back()[ChunkPos++]);
8530 }
8531 
8532 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8533                                                       const InstructionsState &S) {
8534   if (getScheduleData(V, isOneOf(S, V)))
8535     return true;
8536   Instruction *I = dyn_cast<Instruction>(V);
8537   assert(I && "bundle member must be an instruction");
8538   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8539          !doesNotNeedToBeScheduled(I) &&
8540          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8541          "be scheduled");
8542   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8543     ScheduleData *ISD = getScheduleData(I);
8544     if (!ISD)
8545       return false;
8546     assert(isInSchedulingRegion(ISD) &&
8547            "ScheduleData not in scheduling region");
8548     ScheduleData *SD = allocateScheduleDataChunks();
8549     SD->Inst = I;
8550     SD->init(SchedulingRegionID, S.OpValue);
8551     ExtraScheduleDataMap[I][S.OpValue] = SD;
8552     return true;
8553   };
8554   if (CheckScheduleForI(I))
8555     return true;
8556   if (!ScheduleStart) {
8557     // It's the first instruction in the new region.
8558     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8559     ScheduleStart = I;
8560     ScheduleEnd = I->getNextNode();
8561     if (isOneOf(S, I) != I)
8562       CheckScheduleForI(I);
8563     assert(ScheduleEnd && "tried to vectorize a terminator?");
8564     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8565     return true;
8566   }
8567   // Search up and down at the same time, because we don't know if the new
8568   // instruction is above or below the existing scheduling region.
8569   BasicBlock::reverse_iterator UpIter =
8570       ++ScheduleStart->getIterator().getReverse();
8571   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8572   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8573   BasicBlock::iterator LowerEnd = BB->end();
8574   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8575          &*DownIter != I) {
8576     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8577       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8578       return false;
8579     }
8580 
8581     ++UpIter;
8582     ++DownIter;
8583   }
8584   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8585     assert(I->getParent() == ScheduleStart->getParent() &&
8586            "Instruction is in wrong basic block.");
8587     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8588     ScheduleStart = I;
8589     if (isOneOf(S, I) != I)
8590       CheckScheduleForI(I);
8591     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8592                       << "\n");
8593     return true;
8594   }
8595   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8596          "Expected to reach top of the basic block or instruction down the "
8597          "lower end.");
8598   assert(I->getParent() == ScheduleEnd->getParent() &&
8599          "Instruction is in wrong basic block.");
8600   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8601                    nullptr);
8602   ScheduleEnd = I->getNextNode();
8603   if (isOneOf(S, I) != I)
8604     CheckScheduleForI(I);
8605   assert(ScheduleEnd && "tried to vectorize a terminator?");
8606   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8607   return true;
8608 }
8609 
8610 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8611                                                 Instruction *ToI,
8612                                                 ScheduleData *PrevLoadStore,
8613                                                 ScheduleData *NextLoadStore) {
8614   ScheduleData *CurrentLoadStore = PrevLoadStore;
8615   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8616     // No need to allocate data for non-schedulable instructions.
8617     if (doesNotNeedToBeScheduled(I))
8618       continue;
8619     ScheduleData *SD = ScheduleDataMap.lookup(I);
8620     if (!SD) {
8621       SD = allocateScheduleDataChunks();
8622       ScheduleDataMap[I] = SD;
8623       SD->Inst = I;
8624     }
8625     assert(!isInSchedulingRegion(SD) &&
8626            "new ScheduleData already in scheduling region");
8627     SD->init(SchedulingRegionID, I);
8628 
8629     if (I->mayReadOrWriteMemory() &&
8630         (!isa<IntrinsicInst>(I) ||
8631          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8632           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8633               Intrinsic::pseudoprobe))) {
8634       // Update the linked list of memory accessing instructions.
8635       if (CurrentLoadStore) {
8636         CurrentLoadStore->NextLoadStore = SD;
8637       } else {
8638         FirstLoadStoreInRegion = SD;
8639       }
8640       CurrentLoadStore = SD;
8641     }
8642 
8643     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8644         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8645       RegionHasStackSave = true;
8646   }
8647   if (NextLoadStore) {
8648     if (CurrentLoadStore)
8649       CurrentLoadStore->NextLoadStore = NextLoadStore;
8650   } else {
8651     LastLoadStoreInRegion = CurrentLoadStore;
8652   }
8653 }
8654 
8655 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8656                                                      bool InsertInReadyList,
8657                                                      BoUpSLP *SLP) {
8658   assert(SD->isSchedulingEntity());
8659 
8660   SmallVector<ScheduleData *, 10> WorkList;
8661   WorkList.push_back(SD);
8662 
8663   while (!WorkList.empty()) {
8664     ScheduleData *SD = WorkList.pop_back_val();
8665     for (ScheduleData *BundleMember = SD; BundleMember;
8666          BundleMember = BundleMember->NextInBundle) {
8667       assert(isInSchedulingRegion(BundleMember));
8668       if (BundleMember->hasValidDependencies())
8669         continue;
8670 
8671       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8672                  << "\n");
8673       BundleMember->Dependencies = 0;
8674       BundleMember->resetUnscheduledDeps();
8675 
8676       // Handle def-use chain dependencies.
8677       if (BundleMember->OpValue != BundleMember->Inst) {
8678         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8679           BundleMember->Dependencies++;
8680           ScheduleData *DestBundle = UseSD->FirstInBundle;
8681           if (!DestBundle->IsScheduled)
8682             BundleMember->incrementUnscheduledDeps(1);
8683           if (!DestBundle->hasValidDependencies())
8684             WorkList.push_back(DestBundle);
8685         }
8686       } else {
8687         for (User *U : BundleMember->Inst->users()) {
8688           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8689             BundleMember->Dependencies++;
8690             ScheduleData *DestBundle = UseSD->FirstInBundle;
8691             if (!DestBundle->IsScheduled)
8692               BundleMember->incrementUnscheduledDeps(1);
8693             if (!DestBundle->hasValidDependencies())
8694               WorkList.push_back(DestBundle);
8695           }
8696         }
8697       }
8698 
8699       auto makeControlDependent = [&](Instruction *I) {
8700         auto *DepDest = getScheduleData(I);
8701         assert(DepDest && "must be in schedule window");
8702         DepDest->ControlDependencies.push_back(BundleMember);
8703         BundleMember->Dependencies++;
8704         ScheduleData *DestBundle = DepDest->FirstInBundle;
8705         if (!DestBundle->IsScheduled)
8706           BundleMember->incrementUnscheduledDeps(1);
8707         if (!DestBundle->hasValidDependencies())
8708           WorkList.push_back(DestBundle);
8709       };
8710 
8711       // Any instruction which isn't safe to speculate at the begining of the
8712       // block is control dependend on any early exit or non-willreturn call
8713       // which proceeds it.
8714       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8715         for (Instruction *I = BundleMember->Inst->getNextNode();
8716              I != ScheduleEnd; I = I->getNextNode()) {
8717           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8718             continue;
8719 
8720           // Add the dependency
8721           makeControlDependent(I);
8722 
8723           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8724             // Everything past here must be control dependent on I.
8725             break;
8726         }
8727       }
8728 
8729       if (RegionHasStackSave) {
8730         // If we have an inalloc alloca instruction, it needs to be scheduled
8731         // after any preceeding stacksave.  We also need to prevent any alloca
8732         // from reordering above a preceeding stackrestore.
8733         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8734             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8735           for (Instruction *I = BundleMember->Inst->getNextNode();
8736                I != ScheduleEnd; I = I->getNextNode()) {
8737             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8738                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8739               // Any allocas past here must be control dependent on I, and I
8740               // must be memory dependend on BundleMember->Inst.
8741               break;
8742 
8743             if (!isa<AllocaInst>(I))
8744               continue;
8745 
8746             // Add the dependency
8747             makeControlDependent(I);
8748           }
8749         }
8750 
8751         // In addition to the cases handle just above, we need to prevent
8752         // allocas from moving below a stacksave.  The stackrestore case
8753         // is currently thought to be conservatism.
8754         if (isa<AllocaInst>(BundleMember->Inst)) {
8755           for (Instruction *I = BundleMember->Inst->getNextNode();
8756                I != ScheduleEnd; I = I->getNextNode()) {
8757             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8758                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8759               continue;
8760 
8761             // Add the dependency
8762             makeControlDependent(I);
8763             break;
8764           }
8765         }
8766       }
8767 
8768       // Handle the memory dependencies (if any).
8769       ScheduleData *DepDest = BundleMember->NextLoadStore;
8770       if (!DepDest)
8771         continue;
8772       Instruction *SrcInst = BundleMember->Inst;
8773       assert(SrcInst->mayReadOrWriteMemory() &&
8774              "NextLoadStore list for non memory effecting bundle?");
8775       MemoryLocation SrcLoc = getLocation(SrcInst);
8776       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8777       unsigned numAliased = 0;
8778       unsigned DistToSrc = 1;
8779 
8780       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8781         assert(isInSchedulingRegion(DepDest));
8782 
8783         // We have two limits to reduce the complexity:
8784         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8785         //    SLP->isAliased (which is the expensive part in this loop).
8786         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8787         //    the whole loop (even if the loop is fast, it's quadratic).
8788         //    It's important for the loop break condition (see below) to
8789         //    check this limit even between two read-only instructions.
8790         if (DistToSrc >= MaxMemDepDistance ||
8791             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8792              (numAliased >= AliasedCheckLimit ||
8793               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8794 
8795           // We increment the counter only if the locations are aliased
8796           // (instead of counting all alias checks). This gives a better
8797           // balance between reduced runtime and accurate dependencies.
8798           numAliased++;
8799 
8800           DepDest->MemoryDependencies.push_back(BundleMember);
8801           BundleMember->Dependencies++;
8802           ScheduleData *DestBundle = DepDest->FirstInBundle;
8803           if (!DestBundle->IsScheduled) {
8804             BundleMember->incrementUnscheduledDeps(1);
8805           }
8806           if (!DestBundle->hasValidDependencies()) {
8807             WorkList.push_back(DestBundle);
8808           }
8809         }
8810 
8811         // Example, explaining the loop break condition: Let's assume our
8812         // starting instruction is i0 and MaxMemDepDistance = 3.
8813         //
8814         //                      +--------v--v--v
8815         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8816         //             +--------^--^--^
8817         //
8818         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8819         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8820         // Previously we already added dependencies from i3 to i6,i7,i8
8821         // (because of MaxMemDepDistance). As we added a dependency from
8822         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8823         // and we can abort this loop at i6.
8824         if (DistToSrc >= 2 * MaxMemDepDistance)
8825           break;
8826         DistToSrc++;
8827       }
8828     }
8829     if (InsertInReadyList && SD->isReady()) {
8830       ReadyInsts.insert(SD);
8831       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8832                         << "\n");
8833     }
8834   }
8835 }
8836 
8837 void BoUpSLP::BlockScheduling::resetSchedule() {
8838   assert(ScheduleStart &&
8839          "tried to reset schedule on block which has not been scheduled");
8840   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8841     doForAllOpcodes(I, [&](ScheduleData *SD) {
8842       assert(isInSchedulingRegion(SD) &&
8843              "ScheduleData not in scheduling region");
8844       SD->IsScheduled = false;
8845       SD->resetUnscheduledDeps();
8846     });
8847   }
8848   ReadyInsts.clear();
8849 }
8850 
8851 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8852   if (!BS->ScheduleStart)
8853     return;
8854 
8855   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8856 
8857   // A key point - if we got here, pre-scheduling was able to find a valid
8858   // scheduling of the sub-graph of the scheduling window which consists
8859   // of all vector bundles and their transitive users.  As such, we do not
8860   // need to reschedule anything *outside of* that subgraph.
8861 
8862   BS->resetSchedule();
8863 
8864   // For the real scheduling we use a more sophisticated ready-list: it is
8865   // sorted by the original instruction location. This lets the final schedule
8866   // be as  close as possible to the original instruction order.
8867   // WARNING: If changing this order causes a correctness issue, that means
8868   // there is some missing dependence edge in the schedule data graph.
8869   struct ScheduleDataCompare {
8870     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8871       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8872     }
8873   };
8874   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8875 
8876   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8877   // and fill the ready-list with initial instructions.
8878   int Idx = 0;
8879   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8880        I = I->getNextNode()) {
8881     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8882       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8883       (void)SDTE;
8884       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8885               SD->isPartOfBundle() ==
8886                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8887              "scheduler and vectorizer bundle mismatch");
8888       SD->FirstInBundle->SchedulingPriority = Idx++;
8889 
8890       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8891         BS->calculateDependencies(SD, false, this);
8892     });
8893   }
8894   BS->initialFillReadyList(ReadyInsts);
8895 
8896   Instruction *LastScheduledInst = BS->ScheduleEnd;
8897 
8898   // Do the "real" scheduling.
8899   while (!ReadyInsts.empty()) {
8900     ScheduleData *picked = *ReadyInsts.begin();
8901     ReadyInsts.erase(ReadyInsts.begin());
8902 
8903     // Move the scheduled instruction(s) to their dedicated places, if not
8904     // there yet.
8905     for (ScheduleData *BundleMember = picked; BundleMember;
8906          BundleMember = BundleMember->NextInBundle) {
8907       Instruction *pickedInst = BundleMember->Inst;
8908       if (pickedInst->getNextNode() != LastScheduledInst)
8909         pickedInst->moveBefore(LastScheduledInst);
8910       LastScheduledInst = pickedInst;
8911     }
8912 
8913     BS->schedule(picked, ReadyInsts);
8914   }
8915 
8916   // Check that we didn't break any of our invariants.
8917 #ifdef EXPENSIVE_CHECKS
8918   BS->verify();
8919 #endif
8920 
8921 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8922   // Check that all schedulable entities got scheduled
8923   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8924     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8925       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8926         assert(SD->IsScheduled && "must be scheduled at this point");
8927       }
8928     });
8929   }
8930 #endif
8931 
8932   // Avoid duplicate scheduling of the block.
8933   BS->ScheduleStart = nullptr;
8934 }
8935 
8936 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8937   // If V is a store, just return the width of the stored value (or value
8938   // truncated just before storing) without traversing the expression tree.
8939   // This is the common case.
8940   if (auto *Store = dyn_cast<StoreInst>(V))
8941     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8942 
8943   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8944     return getVectorElementSize(IEI->getOperand(1));
8945 
8946   auto E = InstrElementSize.find(V);
8947   if (E != InstrElementSize.end())
8948     return E->second;
8949 
8950   // If V is not a store, we can traverse the expression tree to find loads
8951   // that feed it. The type of the loaded value may indicate a more suitable
8952   // width than V's type. We want to base the vector element size on the width
8953   // of memory operations where possible.
8954   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8955   SmallPtrSet<Instruction *, 16> Visited;
8956   if (auto *I = dyn_cast<Instruction>(V)) {
8957     Worklist.emplace_back(I, I->getParent());
8958     Visited.insert(I);
8959   }
8960 
8961   // Traverse the expression tree in bottom-up order looking for loads. If we
8962   // encounter an instruction we don't yet handle, we give up.
8963   auto Width = 0u;
8964   while (!Worklist.empty()) {
8965     Instruction *I;
8966     BasicBlock *Parent;
8967     std::tie(I, Parent) = Worklist.pop_back_val();
8968 
8969     // We should only be looking at scalar instructions here. If the current
8970     // instruction has a vector type, skip.
8971     auto *Ty = I->getType();
8972     if (isa<VectorType>(Ty))
8973       continue;
8974 
8975     // If the current instruction is a load, update MaxWidth to reflect the
8976     // width of the loaded value.
8977     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8978         isa<ExtractValueInst>(I))
8979       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8980 
8981     // Otherwise, we need to visit the operands of the instruction. We only
8982     // handle the interesting cases from buildTree here. If an operand is an
8983     // instruction we haven't yet visited and from the same basic block as the
8984     // user or the use is a PHI node, we add it to the worklist.
8985     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8986              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8987              isa<UnaryOperator>(I)) {
8988       for (Use &U : I->operands())
8989         if (auto *J = dyn_cast<Instruction>(U.get()))
8990           if (Visited.insert(J).second &&
8991               (isa<PHINode>(I) || J->getParent() == Parent))
8992             Worklist.emplace_back(J, J->getParent());
8993     } else {
8994       break;
8995     }
8996   }
8997 
8998   // If we didn't encounter a memory access in the expression tree, or if we
8999   // gave up for some reason, just return the width of V. Otherwise, return the
9000   // maximum width we found.
9001   if (!Width) {
9002     if (auto *CI = dyn_cast<CmpInst>(V))
9003       V = CI->getOperand(0);
9004     Width = DL->getTypeSizeInBits(V->getType());
9005   }
9006 
9007   for (Instruction *I : Visited)
9008     InstrElementSize[I] = Width;
9009 
9010   return Width;
9011 }
9012 
9013 // Determine if a value V in a vectorizable expression Expr can be demoted to a
9014 // smaller type with a truncation. We collect the values that will be demoted
9015 // in ToDemote and additional roots that require investigating in Roots.
9016 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
9017                                   SmallVectorImpl<Value *> &ToDemote,
9018                                   SmallVectorImpl<Value *> &Roots) {
9019   // We can always demote constants.
9020   if (isa<Constant>(V)) {
9021     ToDemote.push_back(V);
9022     return true;
9023   }
9024 
9025   // If the value is not an instruction in the expression with only one use, it
9026   // cannot be demoted.
9027   auto *I = dyn_cast<Instruction>(V);
9028   if (!I || !I->hasOneUse() || !Expr.count(I))
9029     return false;
9030 
9031   switch (I->getOpcode()) {
9032 
9033   // We can always demote truncations and extensions. Since truncations can
9034   // seed additional demotion, we save the truncated value.
9035   case Instruction::Trunc:
9036     Roots.push_back(I->getOperand(0));
9037     break;
9038   case Instruction::ZExt:
9039   case Instruction::SExt:
9040     if (isa<ExtractElementInst>(I->getOperand(0)) ||
9041         isa<InsertElementInst>(I->getOperand(0)))
9042       return false;
9043     break;
9044 
9045   // We can demote certain binary operations if we can demote both of their
9046   // operands.
9047   case Instruction::Add:
9048   case Instruction::Sub:
9049   case Instruction::Mul:
9050   case Instruction::And:
9051   case Instruction::Or:
9052   case Instruction::Xor:
9053     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
9054         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
9055       return false;
9056     break;
9057 
9058   // We can demote selects if we can demote their true and false values.
9059   case Instruction::Select: {
9060     SelectInst *SI = cast<SelectInst>(I);
9061     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
9062         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
9063       return false;
9064     break;
9065   }
9066 
9067   // We can demote phis if we can demote all their incoming operands. Note that
9068   // we don't need to worry about cycles since we ensure single use above.
9069   case Instruction::PHI: {
9070     PHINode *PN = cast<PHINode>(I);
9071     for (Value *IncValue : PN->incoming_values())
9072       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
9073         return false;
9074     break;
9075   }
9076 
9077   // Otherwise, conservatively give up.
9078   default:
9079     return false;
9080   }
9081 
9082   // Record the value that we can demote.
9083   ToDemote.push_back(V);
9084   return true;
9085 }
9086 
9087 void BoUpSLP::computeMinimumValueSizes() {
9088   // If there are no external uses, the expression tree must be rooted by a
9089   // store. We can't demote in-memory values, so there is nothing to do here.
9090   if (ExternalUses.empty())
9091     return;
9092 
9093   // We only attempt to truncate integer expressions.
9094   auto &TreeRoot = VectorizableTree[0]->Scalars;
9095   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
9096   if (!TreeRootIT)
9097     return;
9098 
9099   // If the expression is not rooted by a store, these roots should have
9100   // external uses. We will rely on InstCombine to rewrite the expression in
9101   // the narrower type. However, InstCombine only rewrites single-use values.
9102   // This means that if a tree entry other than a root is used externally, it
9103   // must have multiple uses and InstCombine will not rewrite it. The code
9104   // below ensures that only the roots are used externally.
9105   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
9106   for (auto &EU : ExternalUses)
9107     if (!Expr.erase(EU.Scalar))
9108       return;
9109   if (!Expr.empty())
9110     return;
9111 
9112   // Collect the scalar values of the vectorizable expression. We will use this
9113   // context to determine which values can be demoted. If we see a truncation,
9114   // we mark it as seeding another demotion.
9115   for (auto &EntryPtr : VectorizableTree)
9116     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
9117 
9118   // Ensure the roots of the vectorizable tree don't form a cycle. They must
9119   // have a single external user that is not in the vectorizable tree.
9120   for (auto *Root : TreeRoot)
9121     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9122       return;
9123 
9124   // Conservatively determine if we can actually truncate the roots of the
9125   // expression. Collect the values that can be demoted in ToDemote and
9126   // additional roots that require investigating in Roots.
9127   SmallVector<Value *, 32> ToDemote;
9128   SmallVector<Value *, 4> Roots;
9129   for (auto *Root : TreeRoot)
9130     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9131       return;
9132 
9133   // The maximum bit width required to represent all the values that can be
9134   // demoted without loss of precision. It would be safe to truncate the roots
9135   // of the expression to this width.
9136   auto MaxBitWidth = 8u;
9137 
9138   // We first check if all the bits of the roots are demanded. If they're not,
9139   // we can truncate the roots to this narrower type.
9140   for (auto *Root : TreeRoot) {
9141     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9142     MaxBitWidth = std::max<unsigned>(
9143         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9144   }
9145 
9146   // True if the roots can be zero-extended back to their original type, rather
9147   // than sign-extended. We know that if the leading bits are not demanded, we
9148   // can safely zero-extend. So we initialize IsKnownPositive to True.
9149   bool IsKnownPositive = true;
9150 
9151   // If all the bits of the roots are demanded, we can try a little harder to
9152   // compute a narrower type. This can happen, for example, if the roots are
9153   // getelementptr indices. InstCombine promotes these indices to the pointer
9154   // width. Thus, all their bits are technically demanded even though the
9155   // address computation might be vectorized in a smaller type.
9156   //
9157   // We start by looking at each entry that can be demoted. We compute the
9158   // maximum bit width required to store the scalar by using ValueTracking to
9159   // compute the number of high-order bits we can truncate.
9160   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9161       llvm::all_of(TreeRoot, [](Value *R) {
9162         assert(R->hasOneUse() && "Root should have only one use!");
9163         return isa<GetElementPtrInst>(R->user_back());
9164       })) {
9165     MaxBitWidth = 8u;
9166 
9167     // Determine if the sign bit of all the roots is known to be zero. If not,
9168     // IsKnownPositive is set to False.
9169     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9170       KnownBits Known = computeKnownBits(R, *DL);
9171       return Known.isNonNegative();
9172     });
9173 
9174     // Determine the maximum number of bits required to store the scalar
9175     // values.
9176     for (auto *Scalar : ToDemote) {
9177       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9178       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9179       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9180     }
9181 
9182     // If we can't prove that the sign bit is zero, we must add one to the
9183     // maximum bit width to account for the unknown sign bit. This preserves
9184     // the existing sign bit so we can safely sign-extend the root back to the
9185     // original type. Otherwise, if we know the sign bit is zero, we will
9186     // zero-extend the root instead.
9187     //
9188     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9189     //        one to the maximum bit width will yield a larger-than-necessary
9190     //        type. In general, we need to add an extra bit only if we can't
9191     //        prove that the upper bit of the original type is equal to the
9192     //        upper bit of the proposed smaller type. If these two bits are the
9193     //        same (either zero or one) we know that sign-extending from the
9194     //        smaller type will result in the same value. Here, since we can't
9195     //        yet prove this, we are just making the proposed smaller type
9196     //        larger to ensure correctness.
9197     if (!IsKnownPositive)
9198       ++MaxBitWidth;
9199   }
9200 
9201   // Round MaxBitWidth up to the next power-of-two.
9202   if (!isPowerOf2_64(MaxBitWidth))
9203     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9204 
9205   // If the maximum bit width we compute is less than the with of the roots'
9206   // type, we can proceed with the narrowing. Otherwise, do nothing.
9207   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9208     return;
9209 
9210   // If we can truncate the root, we must collect additional values that might
9211   // be demoted as a result. That is, those seeded by truncations we will
9212   // modify.
9213   while (!Roots.empty())
9214     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9215 
9216   // Finally, map the values we can demote to the maximum bit with we computed.
9217   for (auto *Scalar : ToDemote)
9218     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9219 }
9220 
9221 namespace {
9222 
9223 /// The SLPVectorizer Pass.
9224 struct SLPVectorizer : public FunctionPass {
9225   SLPVectorizerPass Impl;
9226 
9227   /// Pass identification, replacement for typeid
9228   static char ID;
9229 
9230   explicit SLPVectorizer() : FunctionPass(ID) {
9231     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9232   }
9233 
9234   bool doInitialization(Module &M) override { return false; }
9235 
9236   bool runOnFunction(Function &F) override {
9237     if (skipFunction(F))
9238       return false;
9239 
9240     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9241     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9242     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9243     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9244     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9245     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9246     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9247     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9248     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9249     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9250 
9251     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9252   }
9253 
9254   void getAnalysisUsage(AnalysisUsage &AU) const override {
9255     FunctionPass::getAnalysisUsage(AU);
9256     AU.addRequired<AssumptionCacheTracker>();
9257     AU.addRequired<ScalarEvolutionWrapperPass>();
9258     AU.addRequired<AAResultsWrapperPass>();
9259     AU.addRequired<TargetTransformInfoWrapperPass>();
9260     AU.addRequired<LoopInfoWrapperPass>();
9261     AU.addRequired<DominatorTreeWrapperPass>();
9262     AU.addRequired<DemandedBitsWrapperPass>();
9263     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9264     AU.addRequired<InjectTLIMappingsLegacy>();
9265     AU.addPreserved<LoopInfoWrapperPass>();
9266     AU.addPreserved<DominatorTreeWrapperPass>();
9267     AU.addPreserved<AAResultsWrapperPass>();
9268     AU.addPreserved<GlobalsAAWrapperPass>();
9269     AU.setPreservesCFG();
9270   }
9271 };
9272 
9273 } // end anonymous namespace
9274 
9275 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9276   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9277   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9278   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9279   auto *AA = &AM.getResult<AAManager>(F);
9280   auto *LI = &AM.getResult<LoopAnalysis>(F);
9281   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9282   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9283   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9284   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9285 
9286   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9287   if (!Changed)
9288     return PreservedAnalyses::all();
9289 
9290   PreservedAnalyses PA;
9291   PA.preserveSet<CFGAnalyses>();
9292   return PA;
9293 }
9294 
9295 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9296                                 TargetTransformInfo *TTI_,
9297                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9298                                 LoopInfo *LI_, DominatorTree *DT_,
9299                                 AssumptionCache *AC_, DemandedBits *DB_,
9300                                 OptimizationRemarkEmitter *ORE_) {
9301   if (!RunSLPVectorization)
9302     return false;
9303   SE = SE_;
9304   TTI = TTI_;
9305   TLI = TLI_;
9306   AA = AA_;
9307   LI = LI_;
9308   DT = DT_;
9309   AC = AC_;
9310   DB = DB_;
9311   DL = &F.getParent()->getDataLayout();
9312 
9313   Stores.clear();
9314   GEPs.clear();
9315   bool Changed = false;
9316 
9317   // If the target claims to have no vector registers don't attempt
9318   // vectorization.
9319   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9320     LLVM_DEBUG(
9321         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9322     return false;
9323   }
9324 
9325   // Don't vectorize when the attribute NoImplicitFloat is used.
9326   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9327     return false;
9328 
9329   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9330 
9331   // Use the bottom up slp vectorizer to construct chains that start with
9332   // store instructions.
9333   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9334 
9335   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9336   // delete instructions.
9337 
9338   // Update DFS numbers now so that we can use them for ordering.
9339   DT->updateDFSNumbers();
9340 
9341   // Scan the blocks in the function in post order.
9342   for (auto BB : post_order(&F.getEntryBlock())) {
9343     // Start new block - clear the list of reduction roots.
9344     R.clearReductionData();
9345     collectSeedInstructions(BB);
9346 
9347     // Vectorize trees that end at stores.
9348     if (!Stores.empty()) {
9349       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9350                         << " underlying objects.\n");
9351       Changed |= vectorizeStoreChains(R);
9352     }
9353 
9354     // Vectorize trees that end at reductions.
9355     Changed |= vectorizeChainsInBlock(BB, R);
9356 
9357     // Vectorize the index computations of getelementptr instructions. This
9358     // is primarily intended to catch gather-like idioms ending at
9359     // non-consecutive loads.
9360     if (!GEPs.empty()) {
9361       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9362                         << " underlying objects.\n");
9363       Changed |= vectorizeGEPIndices(BB, R);
9364     }
9365   }
9366 
9367   if (Changed) {
9368     R.optimizeGatherSequence();
9369     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9370   }
9371   return Changed;
9372 }
9373 
9374 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9375                                             unsigned Idx, unsigned MinVF) {
9376   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9377                     << "\n");
9378   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9379   unsigned VF = Chain.size();
9380 
9381   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9382     return false;
9383 
9384   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9385                     << "\n");
9386 
9387   R.buildTree(Chain);
9388   if (R.isTreeTinyAndNotFullyVectorizable())
9389     return false;
9390   if (R.isLoadCombineCandidate())
9391     return false;
9392   R.reorderTopToBottom();
9393   R.reorderBottomToTop();
9394   R.buildExternalUses();
9395 
9396   R.computeMinimumValueSizes();
9397 
9398   InstructionCost Cost = R.getTreeCost();
9399 
9400   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9401   if (Cost < -SLPCostThreshold) {
9402     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9403 
9404     using namespace ore;
9405 
9406     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9407                                         cast<StoreInst>(Chain[0]))
9408                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9409                      << " and with tree size "
9410                      << NV("TreeSize", R.getTreeSize()));
9411 
9412     R.vectorizeTree();
9413     return true;
9414   }
9415 
9416   return false;
9417 }
9418 
9419 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9420                                         BoUpSLP &R) {
9421   // We may run into multiple chains that merge into a single chain. We mark the
9422   // stores that we vectorized so that we don't visit the same store twice.
9423   BoUpSLP::ValueSet VectorizedStores;
9424   bool Changed = false;
9425 
9426   int E = Stores.size();
9427   SmallBitVector Tails(E, false);
9428   int MaxIter = MaxStoreLookup.getValue();
9429   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9430       E, std::make_pair(E, INT_MAX));
9431   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9432   int IterCnt;
9433   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9434                                   &CheckedPairs,
9435                                   &ConsecutiveChain](int K, int Idx) {
9436     if (IterCnt >= MaxIter)
9437       return true;
9438     if (CheckedPairs[Idx].test(K))
9439       return ConsecutiveChain[K].second == 1 &&
9440              ConsecutiveChain[K].first == Idx;
9441     ++IterCnt;
9442     CheckedPairs[Idx].set(K);
9443     CheckedPairs[K].set(Idx);
9444     Optional<int> Diff = getPointersDiff(
9445         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9446         Stores[Idx]->getValueOperand()->getType(),
9447         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9448     if (!Diff || *Diff == 0)
9449       return false;
9450     int Val = *Diff;
9451     if (Val < 0) {
9452       if (ConsecutiveChain[Idx].second > -Val) {
9453         Tails.set(K);
9454         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9455       }
9456       return false;
9457     }
9458     if (ConsecutiveChain[K].second <= Val)
9459       return false;
9460 
9461     Tails.set(Idx);
9462     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9463     return Val == 1;
9464   };
9465   // Do a quadratic search on all of the given stores in reverse order and find
9466   // all of the pairs of stores that follow each other.
9467   for (int Idx = E - 1; Idx >= 0; --Idx) {
9468     // If a store has multiple consecutive store candidates, search according
9469     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9470     // This is because usually pairing with immediate succeeding or preceding
9471     // candidate create the best chance to find slp vectorization opportunity.
9472     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9473     IterCnt = 0;
9474     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9475       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9476           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9477         break;
9478   }
9479 
9480   // Tracks if we tried to vectorize stores starting from the given tail
9481   // already.
9482   SmallBitVector TriedTails(E, false);
9483   // For stores that start but don't end a link in the chain:
9484   for (int Cnt = E; Cnt > 0; --Cnt) {
9485     int I = Cnt - 1;
9486     if (ConsecutiveChain[I].first == E || Tails.test(I))
9487       continue;
9488     // We found a store instr that starts a chain. Now follow the chain and try
9489     // to vectorize it.
9490     BoUpSLP::ValueList Operands;
9491     // Collect the chain into a list.
9492     while (I != E && !VectorizedStores.count(Stores[I])) {
9493       Operands.push_back(Stores[I]);
9494       Tails.set(I);
9495       if (ConsecutiveChain[I].second != 1) {
9496         // Mark the new end in the chain and go back, if required. It might be
9497         // required if the original stores come in reversed order, for example.
9498         if (ConsecutiveChain[I].first != E &&
9499             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9500             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9501           TriedTails.set(I);
9502           Tails.reset(ConsecutiveChain[I].first);
9503           if (Cnt < ConsecutiveChain[I].first + 2)
9504             Cnt = ConsecutiveChain[I].first + 2;
9505         }
9506         break;
9507       }
9508       // Move to the next value in the chain.
9509       I = ConsecutiveChain[I].first;
9510     }
9511     assert(!Operands.empty() && "Expected non-empty list of stores.");
9512 
9513     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9514     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9515     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9516 
9517     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9518                               MaxElts);
9519     auto *Store = cast<StoreInst>(Operands[0]);
9520     Type *StoreTy = Store->getValueOperand()->getType();
9521     Type *ValueTy = StoreTy;
9522     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9523       ValueTy = Trunc->getSrcTy();
9524     unsigned MinVF = TTI->getStoreMinimumVF(
9525         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9526 
9527     // FIXME: Is division-by-2 the correct step? Should we assert that the
9528     // register size is a power-of-2?
9529     unsigned StartIdx = 0;
9530     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9531       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9532         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9533         if (!VectorizedStores.count(Slice.front()) &&
9534             !VectorizedStores.count(Slice.back()) &&
9535             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9536           // Mark the vectorized stores so that we don't vectorize them again.
9537           VectorizedStores.insert(Slice.begin(), Slice.end());
9538           Changed = true;
9539           // If we vectorized initial block, no need to try to vectorize it
9540           // again.
9541           if (Cnt == StartIdx)
9542             StartIdx += Size;
9543           Cnt += Size;
9544           continue;
9545         }
9546         ++Cnt;
9547       }
9548       // Check if the whole array was vectorized already - exit.
9549       if (StartIdx >= Operands.size())
9550         break;
9551     }
9552   }
9553 
9554   return Changed;
9555 }
9556 
9557 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9558   // Initialize the collections. We will make a single pass over the block.
9559   Stores.clear();
9560   GEPs.clear();
9561 
9562   // Visit the store and getelementptr instructions in BB and organize them in
9563   // Stores and GEPs according to the underlying objects of their pointer
9564   // operands.
9565   for (Instruction &I : *BB) {
9566     // Ignore store instructions that are volatile or have a pointer operand
9567     // that doesn't point to a scalar type.
9568     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9569       if (!SI->isSimple())
9570         continue;
9571       if (!isValidElementType(SI->getValueOperand()->getType()))
9572         continue;
9573       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9574     }
9575 
9576     // Ignore getelementptr instructions that have more than one index, a
9577     // constant index, or a pointer operand that doesn't point to a scalar
9578     // type.
9579     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9580       auto Idx = GEP->idx_begin()->get();
9581       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9582         continue;
9583       if (!isValidElementType(Idx->getType()))
9584         continue;
9585       if (GEP->getType()->isVectorTy())
9586         continue;
9587       GEPs[GEP->getPointerOperand()].push_back(GEP);
9588     }
9589   }
9590 }
9591 
9592 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9593   if (!A || !B)
9594     return false;
9595   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9596     return false;
9597   Value *VL[] = {A, B};
9598   return tryToVectorizeList(VL, R);
9599 }
9600 
9601 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9602                                            bool LimitForRegisterSize) {
9603   if (VL.size() < 2)
9604     return false;
9605 
9606   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9607                     << VL.size() << ".\n");
9608 
9609   // Check that all of the parts are instructions of the same type,
9610   // we permit an alternate opcode via InstructionsState.
9611   InstructionsState S = getSameOpcode(VL);
9612   if (!S.getOpcode())
9613     return false;
9614 
9615   Instruction *I0 = cast<Instruction>(S.OpValue);
9616   // Make sure invalid types (including vector type) are rejected before
9617   // determining vectorization factor for scalar instructions.
9618   for (Value *V : VL) {
9619     Type *Ty = V->getType();
9620     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9621       // NOTE: the following will give user internal llvm type name, which may
9622       // not be useful.
9623       R.getORE()->emit([&]() {
9624         std::string type_str;
9625         llvm::raw_string_ostream rso(type_str);
9626         Ty->print(rso);
9627         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9628                << "Cannot SLP vectorize list: type "
9629                << rso.str() + " is unsupported by vectorizer";
9630       });
9631       return false;
9632     }
9633   }
9634 
9635   unsigned Sz = R.getVectorElementSize(I0);
9636   unsigned MinVF = R.getMinVF(Sz);
9637   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9638   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9639   if (MaxVF < 2) {
9640     R.getORE()->emit([&]() {
9641       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9642              << "Cannot SLP vectorize list: vectorization factor "
9643              << "less than 2 is not supported";
9644     });
9645     return false;
9646   }
9647 
9648   bool Changed = false;
9649   bool CandidateFound = false;
9650   InstructionCost MinCost = SLPCostThreshold.getValue();
9651   Type *ScalarTy = VL[0]->getType();
9652   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9653     ScalarTy = IE->getOperand(1)->getType();
9654 
9655   unsigned NextInst = 0, MaxInst = VL.size();
9656   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9657     // No actual vectorization should happen, if number of parts is the same as
9658     // provided vectorization factor (i.e. the scalar type is used for vector
9659     // code during codegen).
9660     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9661     if (TTI->getNumberOfParts(VecTy) == VF)
9662       continue;
9663     for (unsigned I = NextInst; I < MaxInst; ++I) {
9664       unsigned OpsWidth = 0;
9665 
9666       if (I + VF > MaxInst)
9667         OpsWidth = MaxInst - I;
9668       else
9669         OpsWidth = VF;
9670 
9671       if (!isPowerOf2_32(OpsWidth))
9672         continue;
9673 
9674       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9675           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9676         break;
9677 
9678       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9679       // Check that a previous iteration of this loop did not delete the Value.
9680       if (llvm::any_of(Ops, [&R](Value *V) {
9681             auto *I = dyn_cast<Instruction>(V);
9682             return I && R.isDeleted(I);
9683           }))
9684         continue;
9685 
9686       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9687                         << "\n");
9688 
9689       R.buildTree(Ops);
9690       if (R.isTreeTinyAndNotFullyVectorizable())
9691         continue;
9692       R.reorderTopToBottom();
9693       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9694       R.buildExternalUses();
9695 
9696       R.computeMinimumValueSizes();
9697       InstructionCost Cost = R.getTreeCost();
9698       CandidateFound = true;
9699       MinCost = std::min(MinCost, Cost);
9700 
9701       if (Cost < -SLPCostThreshold) {
9702         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9703         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9704                                                     cast<Instruction>(Ops[0]))
9705                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9706                                  << " and with tree size "
9707                                  << ore::NV("TreeSize", R.getTreeSize()));
9708 
9709         R.vectorizeTree();
9710         // Move to the next bundle.
9711         I += VF - 1;
9712         NextInst = I + 1;
9713         Changed = true;
9714       }
9715     }
9716   }
9717 
9718   if (!Changed && CandidateFound) {
9719     R.getORE()->emit([&]() {
9720       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9721              << "List vectorization was possible but not beneficial with cost "
9722              << ore::NV("Cost", MinCost) << " >= "
9723              << ore::NV("Treshold", -SLPCostThreshold);
9724     });
9725   } else if (!Changed) {
9726     R.getORE()->emit([&]() {
9727       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9728              << "Cannot SLP vectorize list: vectorization was impossible"
9729              << " with available vectorization factors";
9730     });
9731   }
9732   return Changed;
9733 }
9734 
9735 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9736   if (!I)
9737     return false;
9738 
9739   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9740       isa<VectorType>(I->getType()))
9741     return false;
9742 
9743   Value *P = I->getParent();
9744 
9745   // Vectorize in current basic block only.
9746   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9747   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9748   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9749     return false;
9750 
9751   // First collect all possible candidates
9752   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9753   Candidates.emplace_back(Op0, Op1);
9754 
9755   auto *A = dyn_cast<BinaryOperator>(Op0);
9756   auto *B = dyn_cast<BinaryOperator>(Op1);
9757   // Try to skip B.
9758   if (A && B && B->hasOneUse()) {
9759     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9760     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9761     if (B0 && B0->getParent() == P)
9762       Candidates.emplace_back(A, B0);
9763     if (B1 && B1->getParent() == P)
9764       Candidates.emplace_back(A, B1);
9765   }
9766   // Try to skip A.
9767   if (B && A && A->hasOneUse()) {
9768     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9769     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9770     if (A0 && A0->getParent() == P)
9771       Candidates.emplace_back(A0, B);
9772     if (A1 && A1->getParent() == P)
9773       Candidates.emplace_back(A1, B);
9774   }
9775 
9776   if (Candidates.size() == 1)
9777     return tryToVectorizePair(Op0, Op1, R);
9778 
9779   // We have multiple options. Try to pick the single best.
9780   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9781   if (!BestCandidate)
9782     return false;
9783   return tryToVectorizePair(Candidates[*BestCandidate].first,
9784                             Candidates[*BestCandidate].second, R);
9785 }
9786 
9787 namespace {
9788 
9789 /// Model horizontal reductions.
9790 ///
9791 /// A horizontal reduction is a tree of reduction instructions that has values
9792 /// that can be put into a vector as its leaves. For example:
9793 ///
9794 /// mul mul mul mul
9795 ///  \  /    \  /
9796 ///   +       +
9797 ///    \     /
9798 ///       +
9799 /// This tree has "mul" as its leaf values and "+" as its reduction
9800 /// instructions. A reduction can feed into a store or a binary operation
9801 /// feeding a phi.
9802 ///    ...
9803 ///    \  /
9804 ///     +
9805 ///     |
9806 ///  phi +=
9807 ///
9808 ///  Or:
9809 ///    ...
9810 ///    \  /
9811 ///     +
9812 ///     |
9813 ///   *p =
9814 ///
9815 class HorizontalReduction {
9816   using ReductionOpsType = SmallVector<Value *, 16>;
9817   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9818   ReductionOpsListType ReductionOps;
9819   /// List of possibly reduced values.
9820   SmallVector<SmallVector<Value *>> ReducedVals;
9821   /// Maps reduced value to the corresponding reduction operation.
9822   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9823   // Use map vector to make stable output.
9824   MapVector<Instruction *, Value *> ExtraArgs;
9825   WeakTrackingVH ReductionRoot;
9826   /// The type of reduction operation.
9827   RecurKind RdxKind;
9828 
9829   static bool isCmpSelMinMax(Instruction *I) {
9830     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9831            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9832   }
9833 
9834   // And/or are potentially poison-safe logical patterns like:
9835   // select x, y, false
9836   // select x, true, y
9837   static bool isBoolLogicOp(Instruction *I) {
9838     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9839            match(I, m_LogicalOr(m_Value(), m_Value()));
9840   }
9841 
9842   /// Checks if instruction is associative and can be vectorized.
9843   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9844     if (Kind == RecurKind::None)
9845       return false;
9846 
9847     // Integer ops that map to select instructions or intrinsics are fine.
9848     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9849         isBoolLogicOp(I))
9850       return true;
9851 
9852     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9853       // FP min/max are associative except for NaN and -0.0. We do not
9854       // have to rule out -0.0 here because the intrinsic semantics do not
9855       // specify a fixed result for it.
9856       return I->getFastMathFlags().noNaNs();
9857     }
9858 
9859     return I->isAssociative();
9860   }
9861 
9862   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9863     // Poison-safe 'or' takes the form: select X, true, Y
9864     // To make that work with the normal operand processing, we skip the
9865     // true value operand.
9866     // TODO: Change the code and data structures to handle this without a hack.
9867     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9868       return I->getOperand(2);
9869     return I->getOperand(Index);
9870   }
9871 
9872   /// Creates reduction operation with the current opcode.
9873   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9874                          Value *RHS, const Twine &Name, bool UseSelect) {
9875     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9876     switch (Kind) {
9877     case RecurKind::Or:
9878       if (UseSelect &&
9879           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9880         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9881       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9882                                  Name);
9883     case RecurKind::And:
9884       if (UseSelect &&
9885           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9886         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9887       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9888                                  Name);
9889     case RecurKind::Add:
9890     case RecurKind::Mul:
9891     case RecurKind::Xor:
9892     case RecurKind::FAdd:
9893     case RecurKind::FMul:
9894       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9895                                  Name);
9896     case RecurKind::FMax:
9897       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9898     case RecurKind::FMin:
9899       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9900     case RecurKind::SMax:
9901       if (UseSelect) {
9902         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9903         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9904       }
9905       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9906     case RecurKind::SMin:
9907       if (UseSelect) {
9908         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9909         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9910       }
9911       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9912     case RecurKind::UMax:
9913       if (UseSelect) {
9914         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9915         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9916       }
9917       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9918     case RecurKind::UMin:
9919       if (UseSelect) {
9920         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9921         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9922       }
9923       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9924     default:
9925       llvm_unreachable("Unknown reduction operation.");
9926     }
9927   }
9928 
9929   /// Creates reduction operation with the current opcode with the IR flags
9930   /// from \p ReductionOps.
9931   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9932                          Value *RHS, const Twine &Name,
9933                          const ReductionOpsListType &ReductionOps) {
9934     bool UseSelect = ReductionOps.size() == 2 ||
9935                      // Logical or/and.
9936                      (ReductionOps.size() == 1 &&
9937                       isa<SelectInst>(ReductionOps.front().front()));
9938     assert((!UseSelect || ReductionOps.size() != 2 ||
9939             isa<SelectInst>(ReductionOps[1][0])) &&
9940            "Expected cmp + select pairs for reduction");
9941     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9942     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9943       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9944         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9945         propagateIRFlags(Op, ReductionOps[1]);
9946         return Op;
9947       }
9948     }
9949     propagateIRFlags(Op, ReductionOps[0]);
9950     return Op;
9951   }
9952 
9953   /// Creates reduction operation with the current opcode with the IR flags
9954   /// from \p I.
9955   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9956                          Value *RHS, const Twine &Name, Value *I) {
9957     auto *SelI = dyn_cast<SelectInst>(I);
9958     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9959     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9960       if (auto *Sel = dyn_cast<SelectInst>(Op))
9961         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9962     }
9963     propagateIRFlags(Op, I);
9964     return Op;
9965   }
9966 
9967   static RecurKind getRdxKind(Value *V) {
9968     auto *I = dyn_cast<Instruction>(V);
9969     if (!I)
9970       return RecurKind::None;
9971     if (match(I, m_Add(m_Value(), m_Value())))
9972       return RecurKind::Add;
9973     if (match(I, m_Mul(m_Value(), m_Value())))
9974       return RecurKind::Mul;
9975     if (match(I, m_And(m_Value(), m_Value())) ||
9976         match(I, m_LogicalAnd(m_Value(), m_Value())))
9977       return RecurKind::And;
9978     if (match(I, m_Or(m_Value(), m_Value())) ||
9979         match(I, m_LogicalOr(m_Value(), m_Value())))
9980       return RecurKind::Or;
9981     if (match(I, m_Xor(m_Value(), m_Value())))
9982       return RecurKind::Xor;
9983     if (match(I, m_FAdd(m_Value(), m_Value())))
9984       return RecurKind::FAdd;
9985     if (match(I, m_FMul(m_Value(), m_Value())))
9986       return RecurKind::FMul;
9987 
9988     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9989       return RecurKind::FMax;
9990     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9991       return RecurKind::FMin;
9992 
9993     // This matches either cmp+select or intrinsics. SLP is expected to handle
9994     // either form.
9995     // TODO: If we are canonicalizing to intrinsics, we can remove several
9996     //       special-case paths that deal with selects.
9997     if (match(I, m_SMax(m_Value(), m_Value())))
9998       return RecurKind::SMax;
9999     if (match(I, m_SMin(m_Value(), m_Value())))
10000       return RecurKind::SMin;
10001     if (match(I, m_UMax(m_Value(), m_Value())))
10002       return RecurKind::UMax;
10003     if (match(I, m_UMin(m_Value(), m_Value())))
10004       return RecurKind::UMin;
10005 
10006     if (auto *Select = dyn_cast<SelectInst>(I)) {
10007       // Try harder: look for min/max pattern based on instructions producing
10008       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
10009       // During the intermediate stages of SLP, it's very common to have
10010       // pattern like this (since optimizeGatherSequence is run only once
10011       // at the end):
10012       // %1 = extractelement <2 x i32> %a, i32 0
10013       // %2 = extractelement <2 x i32> %a, i32 1
10014       // %cond = icmp sgt i32 %1, %2
10015       // %3 = extractelement <2 x i32> %a, i32 0
10016       // %4 = extractelement <2 x i32> %a, i32 1
10017       // %select = select i1 %cond, i32 %3, i32 %4
10018       CmpInst::Predicate Pred;
10019       Instruction *L1;
10020       Instruction *L2;
10021 
10022       Value *LHS = Select->getTrueValue();
10023       Value *RHS = Select->getFalseValue();
10024       Value *Cond = Select->getCondition();
10025 
10026       // TODO: Support inverse predicates.
10027       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
10028         if (!isa<ExtractElementInst>(RHS) ||
10029             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10030           return RecurKind::None;
10031       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
10032         if (!isa<ExtractElementInst>(LHS) ||
10033             !L1->isIdenticalTo(cast<Instruction>(LHS)))
10034           return RecurKind::None;
10035       } else {
10036         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
10037           return RecurKind::None;
10038         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
10039             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
10040             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10041           return RecurKind::None;
10042       }
10043 
10044       switch (Pred) {
10045       default:
10046         return RecurKind::None;
10047       case CmpInst::ICMP_SGT:
10048       case CmpInst::ICMP_SGE:
10049         return RecurKind::SMax;
10050       case CmpInst::ICMP_SLT:
10051       case CmpInst::ICMP_SLE:
10052         return RecurKind::SMin;
10053       case CmpInst::ICMP_UGT:
10054       case CmpInst::ICMP_UGE:
10055         return RecurKind::UMax;
10056       case CmpInst::ICMP_ULT:
10057       case CmpInst::ICMP_ULE:
10058         return RecurKind::UMin;
10059       }
10060     }
10061     return RecurKind::None;
10062   }
10063 
10064   /// Get the index of the first operand.
10065   static unsigned getFirstOperandIndex(Instruction *I) {
10066     return isCmpSelMinMax(I) ? 1 : 0;
10067   }
10068 
10069   /// Total number of operands in the reduction operation.
10070   static unsigned getNumberOfOperands(Instruction *I) {
10071     return isCmpSelMinMax(I) ? 3 : 2;
10072   }
10073 
10074   /// Checks if the instruction is in basic block \p BB.
10075   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
10076   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
10077     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
10078       auto *Sel = cast<SelectInst>(I);
10079       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
10080       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
10081     }
10082     return I->getParent() == BB;
10083   }
10084 
10085   /// Expected number of uses for reduction operations/reduced values.
10086   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
10087     if (IsCmpSelMinMax) {
10088       // SelectInst must be used twice while the condition op must have single
10089       // use only.
10090       if (auto *Sel = dyn_cast<SelectInst>(I))
10091         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
10092       return I->hasNUses(2);
10093     }
10094 
10095     // Arithmetic reduction operation must be used once only.
10096     return I->hasOneUse();
10097   }
10098 
10099   /// Initializes the list of reduction operations.
10100   void initReductionOps(Instruction *I) {
10101     if (isCmpSelMinMax(I))
10102       ReductionOps.assign(2, ReductionOpsType());
10103     else
10104       ReductionOps.assign(1, ReductionOpsType());
10105   }
10106 
10107   /// Add all reduction operations for the reduction instruction \p I.
10108   void addReductionOps(Instruction *I) {
10109     if (isCmpSelMinMax(I)) {
10110       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
10111       ReductionOps[1].emplace_back(I);
10112     } else {
10113       ReductionOps[0].emplace_back(I);
10114     }
10115   }
10116 
10117   static Value *getLHS(RecurKind Kind, Instruction *I) {
10118     if (Kind == RecurKind::None)
10119       return nullptr;
10120     return I->getOperand(getFirstOperandIndex(I));
10121   }
10122   static Value *getRHS(RecurKind Kind, Instruction *I) {
10123     if (Kind == RecurKind::None)
10124       return nullptr;
10125     return I->getOperand(getFirstOperandIndex(I) + 1);
10126   }
10127 
10128 public:
10129   HorizontalReduction() = default;
10130 
10131   /// Try to find a reduction tree.
10132   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10133                                  ScalarEvolution &SE, const DataLayout &DL,
10134                                  const TargetLibraryInfo &TLI) {
10135     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10136            "Phi needs to use the binary operator");
10137     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10138             isa<IntrinsicInst>(Inst)) &&
10139            "Expected binop, select, or intrinsic for reduction matching");
10140     RdxKind = getRdxKind(Inst);
10141 
10142     // We could have a initial reductions that is not an add.
10143     //  r *= v1 + v2 + v3 + v4
10144     // In such a case start looking for a tree rooted in the first '+'.
10145     if (Phi) {
10146       if (getLHS(RdxKind, Inst) == Phi) {
10147         Phi = nullptr;
10148         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10149         if (!Inst)
10150           return false;
10151         RdxKind = getRdxKind(Inst);
10152       } else if (getRHS(RdxKind, Inst) == Phi) {
10153         Phi = nullptr;
10154         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10155         if (!Inst)
10156           return false;
10157         RdxKind = getRdxKind(Inst);
10158       }
10159     }
10160 
10161     if (!isVectorizable(RdxKind, Inst))
10162       return false;
10163 
10164     // Analyze "regular" integer/FP types for reductions - no target-specific
10165     // types or pointers.
10166     Type *Ty = Inst->getType();
10167     if (!isValidElementType(Ty) || Ty->isPointerTy())
10168       return false;
10169 
10170     // Though the ultimate reduction may have multiple uses, its condition must
10171     // have only single use.
10172     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10173       if (!Sel->getCondition()->hasOneUse())
10174         return false;
10175 
10176     ReductionRoot = Inst;
10177 
10178     // Iterate through all the operands of the possible reduction tree and
10179     // gather all the reduced values, sorting them by their value id.
10180     BasicBlock *BB = Inst->getParent();
10181     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10182     SmallVector<Instruction *> Worklist(1, Inst);
10183     // Checks if the operands of the \p TreeN instruction are also reduction
10184     // operations or should be treated as reduced values or an extra argument,
10185     // which is not part of the reduction.
10186     auto &&CheckOperands = [this, IsCmpSelMinMax,
10187                             BB](Instruction *TreeN,
10188                                 SmallVectorImpl<Value *> &ExtraArgs,
10189                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10190                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10191       for (int I = getFirstOperandIndex(TreeN),
10192                End = getNumberOfOperands(TreeN);
10193            I < End; ++I) {
10194         Value *EdgeVal = getRdxOperand(TreeN, I);
10195         ReducedValsToOps[EdgeVal].push_back(TreeN);
10196         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10197         // Edge has wrong parent - mark as an extra argument.
10198         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10199             !hasSameParent(EdgeInst, BB)) {
10200           ExtraArgs.push_back(EdgeVal);
10201           continue;
10202         }
10203         // If the edge is not an instruction, or it is different from the main
10204         // reduction opcode or has too many uses - possible reduced value.
10205         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10206             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10207             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10208           PossibleReducedVals.push_back(EdgeVal);
10209           continue;
10210         }
10211         ReductionOps.push_back(EdgeInst);
10212       }
10213     };
10214     // Try to regroup reduced values so that it gets more profitable to try to
10215     // reduce them. Values are grouped by their value ids, instructions - by
10216     // instruction op id and/or alternate op id, plus do extra analysis for
10217     // loads (grouping them by the distabce between pointers) and cmp
10218     // instructions (grouping them by the predicate).
10219     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10220         PossibleReducedVals;
10221     initReductionOps(Inst);
10222     while (!Worklist.empty()) {
10223       Instruction *TreeN = Worklist.pop_back_val();
10224       SmallVector<Value *> Args;
10225       SmallVector<Value *> PossibleRedVals;
10226       SmallVector<Instruction *> PossibleReductionOps;
10227       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10228       // If too many extra args - mark the instruction itself as a reduction
10229       // value, not a reduction operation.
10230       if (Args.size() < 2) {
10231         addReductionOps(TreeN);
10232         // Add extra args.
10233         if (!Args.empty()) {
10234           assert(Args.size() == 1 && "Expected only single argument.");
10235           ExtraArgs[TreeN] = Args.front();
10236         }
10237         // Add reduction values. The values are sorted for better vectorization
10238         // results.
10239         for (Value *V : PossibleRedVals) {
10240           size_t Key, Idx;
10241           std::tie(Key, Idx) = generateKeySubkey(
10242               V, &TLI,
10243               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10244                 for (const auto &LoadData : PossibleReducedVals[Key]) {
10245                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10246                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10247                                       LI->getType(), LI->getPointerOperand(),
10248                                       DL, SE, /*StrictCheck=*/true))
10249                     return hash_value(RLI->getPointerOperand());
10250                 }
10251                 return hash_value(LI->getPointerOperand());
10252               },
10253               /*AllowAlternate=*/false);
10254           ++PossibleReducedVals[Key][Idx]
10255                 .insert(std::make_pair(V, 0))
10256                 .first->second;
10257         }
10258         Worklist.append(PossibleReductionOps.rbegin(),
10259                         PossibleReductionOps.rend());
10260       } else {
10261         size_t Key, Idx;
10262         std::tie(Key, Idx) = generateKeySubkey(
10263             TreeN, &TLI,
10264             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10265               for (const auto &LoadData : PossibleReducedVals[Key]) {
10266                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10267                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10268                                     LI->getType(), LI->getPointerOperand(), DL,
10269                                     SE, /*StrictCheck=*/true))
10270                   return hash_value(RLI->getPointerOperand());
10271               }
10272               return hash_value(LI->getPointerOperand());
10273             },
10274             /*AllowAlternate=*/false);
10275         ++PossibleReducedVals[Key][Idx]
10276               .insert(std::make_pair(TreeN, 0))
10277               .first->second;
10278       }
10279     }
10280     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10281     // Sort values by the total number of values kinds to start the reduction
10282     // from the longest possible reduced values sequences.
10283     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10284       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10285       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10286       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10287            It != E; ++It) {
10288         PossibleRedValsVect.emplace_back();
10289         auto RedValsVect = It->second.takeVector();
10290         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10291           return P1.second < P2.second;
10292         });
10293         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10294           PossibleRedValsVect.back().append(Data.second, Data.first);
10295       }
10296       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10297         return P1.size() > P2.size();
10298       });
10299       ReducedVals.emplace_back();
10300       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10301         ReducedVals.back().append(Data.rbegin(), Data.rend());
10302     }
10303     // Sort the reduced values by number of same/alternate opcode and/or pointer
10304     // operand.
10305     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10306       return P1.size() > P2.size();
10307     });
10308     return true;
10309   }
10310 
10311   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10312   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10313     constexpr int ReductionLimit = 4;
10314     // If there are a sufficient number of reduction values, reduce
10315     // to a nearby power-of-2. We can safely generate oversized
10316     // vectors and rely on the backend to split them to legal sizes.
10317     unsigned NumReducedVals = std::accumulate(
10318         ReducedVals.begin(), ReducedVals.end(), 0,
10319         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10320     if (NumReducedVals < ReductionLimit)
10321       return nullptr;
10322 
10323     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10324 
10325     // Track the reduced values in case if they are replaced by extractelement
10326     // because of the vectorization.
10327     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10328     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10329     // The same extra argument may be used several times, so log each attempt
10330     // to use it.
10331     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10332       assert(Pair.first && "DebugLoc must be set.");
10333       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10334       TrackedVals.try_emplace(Pair.second, Pair.second);
10335     }
10336 
10337     // The compare instruction of a min/max is the insertion point for new
10338     // instructions and may be replaced with a new compare instruction.
10339     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10340       assert(isa<SelectInst>(RdxRootInst) &&
10341              "Expected min/max reduction to have select root instruction");
10342       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10343       assert(isa<Instruction>(ScalarCond) &&
10344              "Expected min/max reduction to have compare condition");
10345       return cast<Instruction>(ScalarCond);
10346     };
10347 
10348     // The reduction root is used as the insertion point for new instructions,
10349     // so set it as externally used to prevent it from being deleted.
10350     ExternallyUsedValues[ReductionRoot];
10351     SmallVector<Value *> IgnoreList;
10352     for (ReductionOpsType &RdxOps : ReductionOps)
10353       for (Value *RdxOp : RdxOps) {
10354         if (!RdxOp)
10355           continue;
10356         IgnoreList.push_back(RdxOp);
10357       }
10358     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10359 
10360     // Need to track reduced vals, they may be changed during vectorization of
10361     // subvectors.
10362     for (ArrayRef<Value *> Candidates : ReducedVals)
10363       for (Value *V : Candidates)
10364         TrackedVals.try_emplace(V, V);
10365 
10366     DenseMap<Value *, unsigned> VectorizedVals;
10367     Value *VectorizedTree = nullptr;
10368     bool CheckForReusedReductionOps = false;
10369     // Try to vectorize elements based on their type.
10370     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10371       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10372       InstructionsState S = getSameOpcode(OrigReducedVals);
10373       SmallVector<Value *> Candidates;
10374       DenseMap<Value *, Value *> TrackedToOrig;
10375       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10376         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10377         // Check if the reduction value was not overriden by the extractelement
10378         // instruction because of the vectorization and exclude it, if it is not
10379         // compatible with other values.
10380         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10381           if (isVectorLikeInstWithConstOps(Inst) &&
10382               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10383             continue;
10384         Candidates.push_back(RdxVal);
10385         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10386       }
10387       bool ShuffledExtracts = false;
10388       // Try to handle shuffled extractelements.
10389       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10390           I + 1 < E) {
10391         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10392         if (NextS.getOpcode() == Instruction::ExtractElement &&
10393             !NextS.isAltShuffle()) {
10394           SmallVector<Value *> CommonCandidates(Candidates);
10395           for (Value *RV : ReducedVals[I + 1]) {
10396             Value *RdxVal = TrackedVals.find(RV)->second;
10397             // Check if the reduction value was not overriden by the
10398             // extractelement instruction because of the vectorization and
10399             // exclude it, if it is not compatible with other values.
10400             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10401               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10402                 continue;
10403             CommonCandidates.push_back(RdxVal);
10404             TrackedToOrig.try_emplace(RdxVal, RV);
10405           }
10406           SmallVector<int> Mask;
10407           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10408             ++I;
10409             Candidates.swap(CommonCandidates);
10410             ShuffledExtracts = true;
10411           }
10412         }
10413       }
10414       unsigned NumReducedVals = Candidates.size();
10415       if (NumReducedVals < ReductionLimit)
10416         continue;
10417 
10418       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10419       unsigned Start = 0;
10420       unsigned Pos = Start;
10421       // Restarts vectorization attempt with lower vector factor.
10422       unsigned PrevReduxWidth = ReduxWidth;
10423       bool CheckForReusedReductionOpsLocal = false;
10424       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10425                                   &CheckForReusedReductionOpsLocal,
10426                                   &PrevReduxWidth, &V,
10427                                   &IgnoreList](bool IgnoreVL = false) {
10428         bool IsAnyRedOpGathered =
10429             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10430               return V.isGathered(RedOp);
10431             });
10432         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10433           // Check if any of the reduction ops are gathered. If so, worth
10434           // trying again with less number of reduction ops.
10435           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10436         }
10437         ++Pos;
10438         if (Pos < NumReducedVals - ReduxWidth + 1)
10439           return IsAnyRedOpGathered;
10440         Pos = Start;
10441         ReduxWidth /= 2;
10442         return IsAnyRedOpGathered;
10443       };
10444       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10445              ReduxWidth >= ReductionLimit) {
10446         // Dependency in tree of the reduction ops - drop this attempt, try
10447         // later.
10448         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10449             Start == 0) {
10450           CheckForReusedReductionOps = true;
10451           break;
10452         }
10453         PrevReduxWidth = ReduxWidth;
10454         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10455         // Beeing analyzed already - skip.
10456         if (V.areAnalyzedReductionVals(VL)) {
10457           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10458           continue;
10459         }
10460         // Early exit if any of the reduction values were deleted during
10461         // previous vectorization attempts.
10462         if (any_of(VL, [&V](Value *RedVal) {
10463               auto *RedValI = dyn_cast<Instruction>(RedVal);
10464               if (!RedValI)
10465                 return false;
10466               return V.isDeleted(RedValI);
10467             }))
10468           break;
10469         V.buildTree(VL, IgnoreList);
10470         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10471           if (!AdjustReducedVals())
10472             V.analyzedReductionVals(VL);
10473           continue;
10474         }
10475         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10476           if (!AdjustReducedVals())
10477             V.analyzedReductionVals(VL);
10478           continue;
10479         }
10480         V.reorderTopToBottom();
10481         // No need to reorder the root node at all.
10482         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10483         // Keep extracted other reduction values, if they are used in the
10484         // vectorization trees.
10485         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10486             ExternallyUsedValues);
10487         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10488           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10489             continue;
10490           for_each(ReducedVals[Cnt],
10491                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10492                      if (isa<Instruction>(V))
10493                        LocalExternallyUsedValues[TrackedVals[V]];
10494                    });
10495         }
10496         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10497           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10498             continue;
10499           unsigned NumOps = VectorizedVals.lookup(Candidates[Cnt]) +
10500                             std::count(VL.begin(), VL.end(), Candidates[Cnt]);
10501           if (NumOps != ReducedValsToOps.find(Candidates[Cnt])->second.size())
10502             LocalExternallyUsedValues[Candidates[Cnt]];
10503         }
10504         V.buildExternalUses(LocalExternallyUsedValues);
10505 
10506         V.computeMinimumValueSizes();
10507 
10508         // Intersect the fast-math-flags from all reduction operations.
10509         FastMathFlags RdxFMF;
10510         RdxFMF.set();
10511         for (Value *U : IgnoreList)
10512           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10513             RdxFMF &= FPMO->getFastMathFlags();
10514         // Estimate cost.
10515         InstructionCost TreeCost = V.getTreeCost(VL);
10516         InstructionCost ReductionCost =
10517             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10518         InstructionCost Cost = TreeCost + ReductionCost;
10519         if (!Cost.isValid()) {
10520           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10521           return nullptr;
10522         }
10523         if (Cost >= -SLPCostThreshold) {
10524           V.getORE()->emit([&]() {
10525             return OptimizationRemarkMissed(
10526                        SV_NAME, "HorSLPNotBeneficial",
10527                        ReducedValsToOps.find(VL[0])->second.front())
10528                    << "Vectorizing horizontal reduction is possible"
10529                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10530                    << " and threshold "
10531                    << ore::NV("Threshold", -SLPCostThreshold);
10532           });
10533           if (!AdjustReducedVals())
10534             V.analyzedReductionVals(VL);
10535           continue;
10536         }
10537 
10538         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10539                           << Cost << ". (HorRdx)\n");
10540         V.getORE()->emit([&]() {
10541           return OptimizationRemark(
10542                      SV_NAME, "VectorizedHorizontalReduction",
10543                      ReducedValsToOps.find(VL[0])->second.front())
10544                  << "Vectorized horizontal reduction with cost "
10545                  << ore::NV("Cost", Cost) << " and with tree size "
10546                  << ore::NV("TreeSize", V.getTreeSize());
10547         });
10548 
10549         Builder.setFastMathFlags(RdxFMF);
10550 
10551         // Vectorize a tree.
10552         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10553 
10554         // Emit a reduction. If the root is a select (min/max idiom), the insert
10555         // point is the compare condition of that select.
10556         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10557         if (IsCmpSelMinMax)
10558           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10559         else
10560           Builder.SetInsertPoint(RdxRootInst);
10561 
10562         // To prevent poison from leaking across what used to be sequential,
10563         // safe, scalar boolean logic operations, the reduction operand must be
10564         // frozen.
10565         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10566           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10567 
10568         Value *ReducedSubTree =
10569             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10570 
10571         if (!VectorizedTree) {
10572           // Initialize the final value in the reduction.
10573           VectorizedTree = ReducedSubTree;
10574         } else {
10575           // Update the final value in the reduction.
10576           Builder.SetCurrentDebugLocation(
10577               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10578           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10579                                     ReducedSubTree, "op.rdx", ReductionOps);
10580         }
10581         // Count vectorized reduced values to exclude them from final reduction.
10582         for (Value *V : VL)
10583           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10584                 .first->getSecond();
10585         Pos += ReduxWidth;
10586         Start = Pos;
10587         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10588       }
10589     }
10590     if (VectorizedTree) {
10591       // Finish the reduction.
10592       // Need to add extra arguments and not vectorized possible reduction
10593       // values.
10594       SmallPtrSet<Value *, 8> Visited;
10595       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10596         ArrayRef<Value *> Candidates = ReducedVals[I];
10597         for (Value *RdxVal : Candidates) {
10598           if (!Visited.insert(RdxVal).second)
10599             continue;
10600           Value *StableRdxVal = RdxVal;
10601           auto TVIt = TrackedVals.find(RdxVal);
10602           if (TVIt != TrackedVals.end())
10603             StableRdxVal = TVIt->second;
10604           unsigned NumOps = VectorizedVals.lookup(RdxVal);
10605           for (Instruction *RedOp :
10606                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10607                    .drop_back(NumOps)) {
10608             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10609             ReductionOpsListType Ops;
10610             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10611               Ops.emplace_back().push_back(Sel->getCondition());
10612             Ops.emplace_back().push_back(RedOp);
10613             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10614                                       StableRdxVal, "op.rdx", Ops);
10615           }
10616         }
10617       }
10618       for (auto &Pair : ExternallyUsedValues) {
10619         // Add each externally used value to the final reduction.
10620         for (auto *I : Pair.second) {
10621           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10622           ReductionOpsListType Ops;
10623           if (auto *Sel = dyn_cast<SelectInst>(I))
10624             Ops.emplace_back().push_back(Sel->getCondition());
10625           Ops.emplace_back().push_back(I);
10626           Value *StableRdxVal = Pair.first;
10627           auto TVIt = TrackedVals.find(Pair.first);
10628           if (TVIt != TrackedVals.end())
10629             StableRdxVal = TVIt->second;
10630           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10631                                     StableRdxVal, "op.rdx", Ops);
10632         }
10633       }
10634 
10635       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10636 
10637       // The original scalar reduction is expected to have no remaining
10638       // uses outside the reduction tree itself.  Assert that we got this
10639       // correct, replace internal uses with undef, and mark for eventual
10640       // deletion.
10641 #ifndef NDEBUG
10642       SmallSet<Value *, 4> IgnoreSet;
10643       for (ArrayRef<Value *> RdxOps : ReductionOps)
10644         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10645 #endif
10646       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10647         for (Value *Ignore : RdxOps) {
10648           if (!Ignore)
10649             continue;
10650 #ifndef NDEBUG
10651           for (auto *U : Ignore->users()) {
10652             assert(IgnoreSet.count(U) &&
10653                    "All users must be either in the reduction ops list.");
10654           }
10655 #endif
10656           if (!Ignore->use_empty()) {
10657             Value *Undef = UndefValue::get(Ignore->getType());
10658             Ignore->replaceAllUsesWith(Undef);
10659           }
10660           V.eraseInstruction(cast<Instruction>(Ignore));
10661         }
10662       }
10663     } else if (!CheckForReusedReductionOps) {
10664       for (ReductionOpsType &RdxOps : ReductionOps)
10665         for (Value *RdxOp : RdxOps)
10666           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10667     }
10668     return VectorizedTree;
10669   }
10670 
10671 private:
10672   /// Calculate the cost of a reduction.
10673   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10674                                    Value *FirstReducedVal, unsigned ReduxWidth,
10675                                    FastMathFlags FMF) {
10676     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10677     Type *ScalarTy = FirstReducedVal->getType();
10678     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10679     InstructionCost VectorCost, ScalarCost;
10680     switch (RdxKind) {
10681     case RecurKind::Add:
10682     case RecurKind::Mul:
10683     case RecurKind::Or:
10684     case RecurKind::And:
10685     case RecurKind::Xor:
10686     case RecurKind::FAdd:
10687     case RecurKind::FMul: {
10688       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10689       VectorCost =
10690           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10691       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10692       break;
10693     }
10694     case RecurKind::FMax:
10695     case RecurKind::FMin: {
10696       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10697       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10698       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10699                                                /*IsUnsigned=*/false, CostKind);
10700       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10701       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10702                                            SclCondTy, RdxPred, CostKind) +
10703                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10704                                            SclCondTy, RdxPred, CostKind);
10705       break;
10706     }
10707     case RecurKind::SMax:
10708     case RecurKind::SMin:
10709     case RecurKind::UMax:
10710     case RecurKind::UMin: {
10711       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10712       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10713       bool IsUnsigned =
10714           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10715       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10716                                                CostKind);
10717       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10718       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10719                                            SclCondTy, RdxPred, CostKind) +
10720                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10721                                            SclCondTy, RdxPred, CostKind);
10722       break;
10723     }
10724     default:
10725       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10726     }
10727 
10728     // Scalar cost is repeated for N-1 elements.
10729     ScalarCost *= (ReduxWidth - 1);
10730     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10731                       << " for reduction that starts with " << *FirstReducedVal
10732                       << " (It is a splitting reduction)\n");
10733     return VectorCost - ScalarCost;
10734   }
10735 
10736   /// Emit a horizontal reduction of the vectorized value.
10737   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10738                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10739     assert(VectorizedValue && "Need to have a vectorized tree node");
10740     assert(isPowerOf2_32(ReduxWidth) &&
10741            "We only handle power-of-two reductions for now");
10742     assert(RdxKind != RecurKind::FMulAdd &&
10743            "A call to the llvm.fmuladd intrinsic is not handled yet");
10744 
10745     ++NumVectorInstructions;
10746     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10747   }
10748 };
10749 
10750 } // end anonymous namespace
10751 
10752 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10753   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10754     return cast<FixedVectorType>(IE->getType())->getNumElements();
10755 
10756   unsigned AggregateSize = 1;
10757   auto *IV = cast<InsertValueInst>(InsertInst);
10758   Type *CurrentType = IV->getType();
10759   do {
10760     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10761       for (auto *Elt : ST->elements())
10762         if (Elt != ST->getElementType(0)) // check homogeneity
10763           return None;
10764       AggregateSize *= ST->getNumElements();
10765       CurrentType = ST->getElementType(0);
10766     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10767       AggregateSize *= AT->getNumElements();
10768       CurrentType = AT->getElementType();
10769     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10770       AggregateSize *= VT->getNumElements();
10771       return AggregateSize;
10772     } else if (CurrentType->isSingleValueType()) {
10773       return AggregateSize;
10774     } else {
10775       return None;
10776     }
10777   } while (true);
10778 }
10779 
10780 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10781                                    TargetTransformInfo *TTI,
10782                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10783                                    SmallVectorImpl<Value *> &InsertElts,
10784                                    unsigned OperandOffset) {
10785   do {
10786     Value *InsertedOperand = LastInsertInst->getOperand(1);
10787     Optional<unsigned> OperandIndex =
10788         getInsertIndex(LastInsertInst, OperandOffset);
10789     if (!OperandIndex)
10790       return;
10791     if (isa<InsertElementInst>(InsertedOperand) ||
10792         isa<InsertValueInst>(InsertedOperand)) {
10793       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10794                              BuildVectorOpds, InsertElts, *OperandIndex);
10795 
10796     } else {
10797       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10798       InsertElts[*OperandIndex] = LastInsertInst;
10799     }
10800     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10801   } while (LastInsertInst != nullptr &&
10802            (isa<InsertValueInst>(LastInsertInst) ||
10803             isa<InsertElementInst>(LastInsertInst)) &&
10804            LastInsertInst->hasOneUse());
10805 }
10806 
10807 /// Recognize construction of vectors like
10808 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10809 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10810 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10811 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10812 ///  starting from the last insertelement or insertvalue instruction.
10813 ///
10814 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10815 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10816 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10817 ///
10818 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10819 ///
10820 /// \return true if it matches.
10821 static bool findBuildAggregate(Instruction *LastInsertInst,
10822                                TargetTransformInfo *TTI,
10823                                SmallVectorImpl<Value *> &BuildVectorOpds,
10824                                SmallVectorImpl<Value *> &InsertElts) {
10825 
10826   assert((isa<InsertElementInst>(LastInsertInst) ||
10827           isa<InsertValueInst>(LastInsertInst)) &&
10828          "Expected insertelement or insertvalue instruction!");
10829 
10830   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10831          "Expected empty result vectors!");
10832 
10833   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10834   if (!AggregateSize)
10835     return false;
10836   BuildVectorOpds.resize(*AggregateSize);
10837   InsertElts.resize(*AggregateSize);
10838 
10839   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10840   llvm::erase_value(BuildVectorOpds, nullptr);
10841   llvm::erase_value(InsertElts, nullptr);
10842   if (BuildVectorOpds.size() >= 2)
10843     return true;
10844 
10845   return false;
10846 }
10847 
10848 /// Try and get a reduction value from a phi node.
10849 ///
10850 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10851 /// if they come from either \p ParentBB or a containing loop latch.
10852 ///
10853 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10854 /// if not possible.
10855 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10856                                 BasicBlock *ParentBB, LoopInfo *LI) {
10857   // There are situations where the reduction value is not dominated by the
10858   // reduction phi. Vectorizing such cases has been reported to cause
10859   // miscompiles. See PR25787.
10860   auto DominatedReduxValue = [&](Value *R) {
10861     return isa<Instruction>(R) &&
10862            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10863   };
10864 
10865   Value *Rdx = nullptr;
10866 
10867   // Return the incoming value if it comes from the same BB as the phi node.
10868   if (P->getIncomingBlock(0) == ParentBB) {
10869     Rdx = P->getIncomingValue(0);
10870   } else if (P->getIncomingBlock(1) == ParentBB) {
10871     Rdx = P->getIncomingValue(1);
10872   }
10873 
10874   if (Rdx && DominatedReduxValue(Rdx))
10875     return Rdx;
10876 
10877   // Otherwise, check whether we have a loop latch to look at.
10878   Loop *BBL = LI->getLoopFor(ParentBB);
10879   if (!BBL)
10880     return nullptr;
10881   BasicBlock *BBLatch = BBL->getLoopLatch();
10882   if (!BBLatch)
10883     return nullptr;
10884 
10885   // There is a loop latch, return the incoming value if it comes from
10886   // that. This reduction pattern occasionally turns up.
10887   if (P->getIncomingBlock(0) == BBLatch) {
10888     Rdx = P->getIncomingValue(0);
10889   } else if (P->getIncomingBlock(1) == BBLatch) {
10890     Rdx = P->getIncomingValue(1);
10891   }
10892 
10893   if (Rdx && DominatedReduxValue(Rdx))
10894     return Rdx;
10895 
10896   return nullptr;
10897 }
10898 
10899 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10900   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10901     return true;
10902   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10903     return true;
10904   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10905     return true;
10906   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10907     return true;
10908   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10909     return true;
10910   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10911     return true;
10912   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10913     return true;
10914   return false;
10915 }
10916 
10917 /// Attempt to reduce a horizontal reduction.
10918 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10919 /// with reduction operators \a Root (or one of its operands) in a basic block
10920 /// \a BB, then check if it can be done. If horizontal reduction is not found
10921 /// and root instruction is a binary operation, vectorization of the operands is
10922 /// attempted.
10923 /// \returns true if a horizontal reduction was matched and reduced or operands
10924 /// of one of the binary instruction were vectorized.
10925 /// \returns false if a horizontal reduction was not matched (or not possible)
10926 /// or no vectorization of any binary operation feeding \a Root instruction was
10927 /// performed.
10928 static bool tryToVectorizeHorReductionOrInstOperands(
10929     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10930     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10931     const TargetLibraryInfo &TLI,
10932     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10933   if (!ShouldVectorizeHor)
10934     return false;
10935 
10936   if (!Root)
10937     return false;
10938 
10939   if (Root->getParent() != BB || isa<PHINode>(Root))
10940     return false;
10941   // Start analysis starting from Root instruction. If horizontal reduction is
10942   // found, try to vectorize it. If it is not a horizontal reduction or
10943   // vectorization is not possible or not effective, and currently analyzed
10944   // instruction is a binary operation, try to vectorize the operands, using
10945   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10946   // the same procedure considering each operand as a possible root of the
10947   // horizontal reduction.
10948   // Interrupt the process if the Root instruction itself was vectorized or all
10949   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10950   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10951   // CmpInsts so we can skip extra attempts in
10952   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10953   std::queue<std::pair<Instruction *, unsigned>> Stack;
10954   Stack.emplace(Root, 0);
10955   SmallPtrSet<Value *, 8> VisitedInstrs;
10956   SmallVector<WeakTrackingVH> PostponedInsts;
10957   bool Res = false;
10958   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10959                                                      Value *&B0,
10960                                                      Value *&B1) -> Value * {
10961     if (R.isAnalizedReductionRoot(Inst))
10962       return nullptr;
10963     bool IsBinop = matchRdxBop(Inst, B0, B1);
10964     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10965     if (IsBinop || IsSelect) {
10966       HorizontalReduction HorRdx;
10967       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10968         return HorRdx.tryToReduce(R, TTI);
10969     }
10970     return nullptr;
10971   };
10972   while (!Stack.empty()) {
10973     Instruction *Inst;
10974     unsigned Level;
10975     std::tie(Inst, Level) = Stack.front();
10976     Stack.pop();
10977     // Do not try to analyze instruction that has already been vectorized.
10978     // This may happen when we vectorize instruction operands on a previous
10979     // iteration while stack was populated before that happened.
10980     if (R.isDeleted(Inst))
10981       continue;
10982     Value *B0 = nullptr, *B1 = nullptr;
10983     if (Value *V = TryToReduce(Inst, B0, B1)) {
10984       Res = true;
10985       // Set P to nullptr to avoid re-analysis of phi node in
10986       // matchAssociativeReduction function unless this is the root node.
10987       P = nullptr;
10988       if (auto *I = dyn_cast<Instruction>(V)) {
10989         // Try to find another reduction.
10990         Stack.emplace(I, Level);
10991         continue;
10992       }
10993     } else {
10994       bool IsBinop = B0 && B1;
10995       if (P && IsBinop) {
10996         Inst = dyn_cast<Instruction>(B0);
10997         if (Inst == P)
10998           Inst = dyn_cast<Instruction>(B1);
10999         if (!Inst) {
11000           // Set P to nullptr to avoid re-analysis of phi node in
11001           // matchAssociativeReduction function unless this is the root node.
11002           P = nullptr;
11003           continue;
11004         }
11005       }
11006       // Set P to nullptr to avoid re-analysis of phi node in
11007       // matchAssociativeReduction function unless this is the root node.
11008       P = nullptr;
11009       // Do not try to vectorize CmpInst operands, this is done separately.
11010       // Final attempt for binop args vectorization should happen after the loop
11011       // to try to find reductions.
11012       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
11013         PostponedInsts.push_back(Inst);
11014     }
11015 
11016     // Try to vectorize operands.
11017     // Continue analysis for the instruction from the same basic block only to
11018     // save compile time.
11019     if (++Level < RecursionMaxDepth)
11020       for (auto *Op : Inst->operand_values())
11021         if (VisitedInstrs.insert(Op).second)
11022           if (auto *I = dyn_cast<Instruction>(Op))
11023             // Do not try to vectorize CmpInst operands,  this is done
11024             // separately.
11025             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
11026                 !R.isDeleted(I) && I->getParent() == BB)
11027               Stack.emplace(I, Level);
11028   }
11029   // Try to vectorized binops where reductions were not found.
11030   for (Value *V : PostponedInsts)
11031     if (auto *Inst = dyn_cast<Instruction>(V))
11032       if (!R.isDeleted(Inst))
11033         Res |= Vectorize(Inst, R);
11034   return Res;
11035 }
11036 
11037 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
11038                                                  BasicBlock *BB, BoUpSLP &R,
11039                                                  TargetTransformInfo *TTI) {
11040   auto *I = dyn_cast_or_null<Instruction>(V);
11041   if (!I)
11042     return false;
11043 
11044   if (!isa<BinaryOperator>(I))
11045     P = nullptr;
11046   // Try to match and vectorize a horizontal reduction.
11047   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
11048     return tryToVectorize(I, R);
11049   };
11050   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
11051                                                   *TLI, ExtraVectorization);
11052 }
11053 
11054 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
11055                                                  BasicBlock *BB, BoUpSLP &R) {
11056   const DataLayout &DL = BB->getModule()->getDataLayout();
11057   if (!R.canMapToVector(IVI->getType(), DL))
11058     return false;
11059 
11060   SmallVector<Value *, 16> BuildVectorOpds;
11061   SmallVector<Value *, 16> BuildVectorInsts;
11062   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
11063     return false;
11064 
11065   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
11066   // Aggregate value is unlikely to be processed in vector register.
11067   return tryToVectorizeList(BuildVectorOpds, R);
11068 }
11069 
11070 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
11071                                                    BasicBlock *BB, BoUpSLP &R) {
11072   SmallVector<Value *, 16> BuildVectorInsts;
11073   SmallVector<Value *, 16> BuildVectorOpds;
11074   SmallVector<int> Mask;
11075   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
11076       (llvm::all_of(
11077            BuildVectorOpds,
11078            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
11079        isFixedVectorShuffle(BuildVectorOpds, Mask)))
11080     return false;
11081 
11082   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
11083   return tryToVectorizeList(BuildVectorInsts, R);
11084 }
11085 
11086 template <typename T>
11087 static bool
11088 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
11089                        function_ref<unsigned(T *)> Limit,
11090                        function_ref<bool(T *, T *)> Comparator,
11091                        function_ref<bool(T *, T *)> AreCompatible,
11092                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
11093                        bool LimitForRegisterSize) {
11094   bool Changed = false;
11095   // Sort by type, parent, operands.
11096   stable_sort(Incoming, Comparator);
11097 
11098   // Try to vectorize elements base on their type.
11099   SmallVector<T *> Candidates;
11100   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
11101     // Look for the next elements with the same type, parent and operand
11102     // kinds.
11103     auto *SameTypeIt = IncIt;
11104     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
11105       ++SameTypeIt;
11106 
11107     // Try to vectorize them.
11108     unsigned NumElts = (SameTypeIt - IncIt);
11109     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
11110                       << NumElts << ")\n");
11111     // The vectorization is a 3-state attempt:
11112     // 1. Try to vectorize instructions with the same/alternate opcodes with the
11113     // size of maximal register at first.
11114     // 2. Try to vectorize remaining instructions with the same type, if
11115     // possible. This may result in the better vectorization results rather than
11116     // if we try just to vectorize instructions with the same/alternate opcodes.
11117     // 3. Final attempt to try to vectorize all instructions with the
11118     // same/alternate ops only, this may result in some extra final
11119     // vectorization.
11120     if (NumElts > 1 &&
11121         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11122       // Success start over because instructions might have been changed.
11123       Changed = true;
11124     } else if (NumElts < Limit(*IncIt) &&
11125                (Candidates.empty() ||
11126                 Candidates.front()->getType() == (*IncIt)->getType())) {
11127       Candidates.append(IncIt, std::next(IncIt, NumElts));
11128     }
11129     // Final attempt to vectorize instructions with the same types.
11130     if (Candidates.size() > 1 &&
11131         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11132       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11133         // Success start over because instructions might have been changed.
11134         Changed = true;
11135       } else if (LimitForRegisterSize) {
11136         // Try to vectorize using small vectors.
11137         for (auto *It = Candidates.begin(), *End = Candidates.end();
11138              It != End;) {
11139           auto *SameTypeIt = It;
11140           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11141             ++SameTypeIt;
11142           unsigned NumElts = (SameTypeIt - It);
11143           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11144                                             /*LimitForRegisterSize=*/false))
11145             Changed = true;
11146           It = SameTypeIt;
11147         }
11148       }
11149       Candidates.clear();
11150     }
11151 
11152     // Start over at the next instruction of a different type (or the end).
11153     IncIt = SameTypeIt;
11154   }
11155   return Changed;
11156 }
11157 
11158 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11159 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11160 /// operands. If IsCompatibility is false, function implements strict weak
11161 /// ordering relation between two cmp instructions, returning true if the first
11162 /// instruction is "less" than the second, i.e. its predicate is less than the
11163 /// predicate of the second or the operands IDs are less than the operands IDs
11164 /// of the second cmp instruction.
11165 template <bool IsCompatibility>
11166 static bool compareCmp(Value *V, Value *V2,
11167                        function_ref<bool(Instruction *)> IsDeleted) {
11168   auto *CI1 = cast<CmpInst>(V);
11169   auto *CI2 = cast<CmpInst>(V2);
11170   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11171     return false;
11172   if (CI1->getOperand(0)->getType()->getTypeID() <
11173       CI2->getOperand(0)->getType()->getTypeID())
11174     return !IsCompatibility;
11175   if (CI1->getOperand(0)->getType()->getTypeID() >
11176       CI2->getOperand(0)->getType()->getTypeID())
11177     return false;
11178   CmpInst::Predicate Pred1 = CI1->getPredicate();
11179   CmpInst::Predicate Pred2 = CI2->getPredicate();
11180   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11181   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11182   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11183   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11184   if (BasePred1 < BasePred2)
11185     return !IsCompatibility;
11186   if (BasePred1 > BasePred2)
11187     return false;
11188   // Compare operands.
11189   bool LEPreds = Pred1 <= Pred2;
11190   bool GEPreds = Pred1 >= Pred2;
11191   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11192     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11193     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11194     if (Op1->getValueID() < Op2->getValueID())
11195       return !IsCompatibility;
11196     if (Op1->getValueID() > Op2->getValueID())
11197       return false;
11198     if (auto *I1 = dyn_cast<Instruction>(Op1))
11199       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11200         if (I1->getParent() != I2->getParent())
11201           return false;
11202         InstructionsState S = getSameOpcode({I1, I2});
11203         if (S.getOpcode())
11204           continue;
11205         return false;
11206       }
11207   }
11208   return IsCompatibility;
11209 }
11210 
11211 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11212     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11213     bool AtTerminator) {
11214   bool OpsChanged = false;
11215   SmallVector<Instruction *, 4> PostponedCmps;
11216   for (auto *I : reverse(Instructions)) {
11217     if (R.isDeleted(I))
11218       continue;
11219     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11220       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11221     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11222       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11223     } else if (isa<CmpInst>(I)) {
11224       PostponedCmps.push_back(I);
11225       continue;
11226     }
11227     // Try to find reductions in buildvector sequnces.
11228     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11229   }
11230   if (AtTerminator) {
11231     // Try to find reductions first.
11232     for (Instruction *I : PostponedCmps) {
11233       if (R.isDeleted(I))
11234         continue;
11235       for (Value *Op : I->operands())
11236         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11237     }
11238     // Try to vectorize operands as vector bundles.
11239     for (Instruction *I : PostponedCmps) {
11240       if (R.isDeleted(I))
11241         continue;
11242       OpsChanged |= tryToVectorize(I, R);
11243     }
11244     // Try to vectorize list of compares.
11245     // Sort by type, compare predicate, etc.
11246     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11247       return compareCmp<false>(V, V2,
11248                                [&R](Instruction *I) { return R.isDeleted(I); });
11249     };
11250 
11251     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11252       if (V1 == V2)
11253         return true;
11254       return compareCmp<true>(V1, V2,
11255                               [&R](Instruction *I) { return R.isDeleted(I); });
11256     };
11257     auto Limit = [&R](Value *V) {
11258       unsigned EltSize = R.getVectorElementSize(V);
11259       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11260     };
11261 
11262     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11263     OpsChanged |= tryToVectorizeSequence<Value>(
11264         Vals, Limit, CompareSorter, AreCompatibleCompares,
11265         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11266           // Exclude possible reductions from other blocks.
11267           bool ArePossiblyReducedInOtherBlock =
11268               any_of(Candidates, [](Value *V) {
11269                 return any_of(V->users(), [V](User *U) {
11270                   return isa<SelectInst>(U) &&
11271                          cast<SelectInst>(U)->getParent() !=
11272                              cast<Instruction>(V)->getParent();
11273                 });
11274               });
11275           if (ArePossiblyReducedInOtherBlock)
11276             return false;
11277           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11278         },
11279         /*LimitForRegisterSize=*/true);
11280     Instructions.clear();
11281   } else {
11282     // Insert in reverse order since the PostponedCmps vector was filled in
11283     // reverse order.
11284     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11285   }
11286   return OpsChanged;
11287 }
11288 
11289 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11290   bool Changed = false;
11291   SmallVector<Value *, 4> Incoming;
11292   SmallPtrSet<Value *, 16> VisitedInstrs;
11293   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11294   // node. Allows better to identify the chains that can be vectorized in the
11295   // better way.
11296   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11297   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11298     assert(isValidElementType(V1->getType()) &&
11299            isValidElementType(V2->getType()) &&
11300            "Expected vectorizable types only.");
11301     // It is fine to compare type IDs here, since we expect only vectorizable
11302     // types, like ints, floats and pointers, we don't care about other type.
11303     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11304       return true;
11305     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11306       return false;
11307     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11308     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11309     if (Opcodes1.size() < Opcodes2.size())
11310       return true;
11311     if (Opcodes1.size() > Opcodes2.size())
11312       return false;
11313     Optional<bool> ConstOrder;
11314     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11315       // Undefs are compatible with any other value.
11316       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11317         if (!ConstOrder)
11318           ConstOrder =
11319               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11320         continue;
11321       }
11322       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11323         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11324           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11325           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11326           if (!NodeI1)
11327             return NodeI2 != nullptr;
11328           if (!NodeI2)
11329             return false;
11330           assert((NodeI1 == NodeI2) ==
11331                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11332                  "Different nodes should have different DFS numbers");
11333           if (NodeI1 != NodeI2)
11334             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11335           InstructionsState S = getSameOpcode({I1, I2});
11336           if (S.getOpcode())
11337             continue;
11338           return I1->getOpcode() < I2->getOpcode();
11339         }
11340       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11341         if (!ConstOrder)
11342           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11343         continue;
11344       }
11345       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11346         return true;
11347       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11348         return false;
11349     }
11350     return ConstOrder && *ConstOrder;
11351   };
11352   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11353     if (V1 == V2)
11354       return true;
11355     if (V1->getType() != V2->getType())
11356       return false;
11357     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11358     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11359     if (Opcodes1.size() != Opcodes2.size())
11360       return false;
11361     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11362       // Undefs are compatible with any other value.
11363       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11364         continue;
11365       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11366         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11367           if (I1->getParent() != I2->getParent())
11368             return false;
11369           InstructionsState S = getSameOpcode({I1, I2});
11370           if (S.getOpcode())
11371             continue;
11372           return false;
11373         }
11374       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11375         continue;
11376       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11377         return false;
11378     }
11379     return true;
11380   };
11381   auto Limit = [&R](Value *V) {
11382     unsigned EltSize = R.getVectorElementSize(V);
11383     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11384   };
11385 
11386   bool HaveVectorizedPhiNodes = false;
11387   do {
11388     // Collect the incoming values from the PHIs.
11389     Incoming.clear();
11390     for (Instruction &I : *BB) {
11391       PHINode *P = dyn_cast<PHINode>(&I);
11392       if (!P)
11393         break;
11394 
11395       // No need to analyze deleted, vectorized and non-vectorizable
11396       // instructions.
11397       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11398           isValidElementType(P->getType()))
11399         Incoming.push_back(P);
11400     }
11401 
11402     // Find the corresponding non-phi nodes for better matching when trying to
11403     // build the tree.
11404     for (Value *V : Incoming) {
11405       SmallVectorImpl<Value *> &Opcodes =
11406           PHIToOpcodes.try_emplace(V).first->getSecond();
11407       if (!Opcodes.empty())
11408         continue;
11409       SmallVector<Value *, 4> Nodes(1, V);
11410       SmallPtrSet<Value *, 4> Visited;
11411       while (!Nodes.empty()) {
11412         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11413         if (!Visited.insert(PHI).second)
11414           continue;
11415         for (Value *V : PHI->incoming_values()) {
11416           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11417             Nodes.push_back(PHI1);
11418             continue;
11419           }
11420           Opcodes.emplace_back(V);
11421         }
11422       }
11423     }
11424 
11425     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11426         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11427         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11428           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11429         },
11430         /*LimitForRegisterSize=*/true);
11431     Changed |= HaveVectorizedPhiNodes;
11432     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11433   } while (HaveVectorizedPhiNodes);
11434 
11435   VisitedInstrs.clear();
11436 
11437   SmallVector<Instruction *, 8> PostProcessInstructions;
11438   SmallDenseSet<Instruction *, 4> KeyNodes;
11439   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11440     // Skip instructions with scalable type. The num of elements is unknown at
11441     // compile-time for scalable type.
11442     if (isa<ScalableVectorType>(it->getType()))
11443       continue;
11444 
11445     // Skip instructions marked for the deletion.
11446     if (R.isDeleted(&*it))
11447       continue;
11448     // We may go through BB multiple times so skip the one we have checked.
11449     if (!VisitedInstrs.insert(&*it).second) {
11450       if (it->use_empty() && KeyNodes.contains(&*it) &&
11451           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11452                                       it->isTerminator())) {
11453         // We would like to start over since some instructions are deleted
11454         // and the iterator may become invalid value.
11455         Changed = true;
11456         it = BB->begin();
11457         e = BB->end();
11458       }
11459       continue;
11460     }
11461 
11462     if (isa<DbgInfoIntrinsic>(it))
11463       continue;
11464 
11465     // Try to vectorize reductions that use PHINodes.
11466     if (PHINode *P = dyn_cast<PHINode>(it)) {
11467       // Check that the PHI is a reduction PHI.
11468       if (P->getNumIncomingValues() == 2) {
11469         // Try to match and vectorize a horizontal reduction.
11470         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11471                                      TTI)) {
11472           Changed = true;
11473           it = BB->begin();
11474           e = BB->end();
11475           continue;
11476         }
11477       }
11478       // Try to vectorize the incoming values of the PHI, to catch reductions
11479       // that feed into PHIs.
11480       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11481         // Skip if the incoming block is the current BB for now. Also, bypass
11482         // unreachable IR for efficiency and to avoid crashing.
11483         // TODO: Collect the skipped incoming values and try to vectorize them
11484         // after processing BB.
11485         if (BB == P->getIncomingBlock(I) ||
11486             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11487           continue;
11488 
11489         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11490                                             P->getIncomingBlock(I), R, TTI);
11491       }
11492       continue;
11493     }
11494 
11495     // Ran into an instruction without users, like terminator, or function call
11496     // with ignored return value, store. Ignore unused instructions (basing on
11497     // instruction type, except for CallInst and InvokeInst).
11498     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11499                             isa<InvokeInst>(it))) {
11500       KeyNodes.insert(&*it);
11501       bool OpsChanged = false;
11502       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11503         for (auto *V : it->operand_values()) {
11504           // Try to match and vectorize a horizontal reduction.
11505           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11506         }
11507       }
11508       // Start vectorization of post-process list of instructions from the
11509       // top-tree instructions to try to vectorize as many instructions as
11510       // possible.
11511       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11512                                                 it->isTerminator());
11513       if (OpsChanged) {
11514         // We would like to start over since some instructions are deleted
11515         // and the iterator may become invalid value.
11516         Changed = true;
11517         it = BB->begin();
11518         e = BB->end();
11519         continue;
11520       }
11521     }
11522 
11523     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11524         isa<InsertValueInst>(it))
11525       PostProcessInstructions.push_back(&*it);
11526   }
11527 
11528   return Changed;
11529 }
11530 
11531 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11532   auto Changed = false;
11533   for (auto &Entry : GEPs) {
11534     // If the getelementptr list has fewer than two elements, there's nothing
11535     // to do.
11536     if (Entry.second.size() < 2)
11537       continue;
11538 
11539     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11540                       << Entry.second.size() << ".\n");
11541 
11542     // Process the GEP list in chunks suitable for the target's supported
11543     // vector size. If a vector register can't hold 1 element, we are done. We
11544     // are trying to vectorize the index computations, so the maximum number of
11545     // elements is based on the size of the index expression, rather than the
11546     // size of the GEP itself (the target's pointer size).
11547     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11548     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11549     if (MaxVecRegSize < EltSize)
11550       continue;
11551 
11552     unsigned MaxElts = MaxVecRegSize / EltSize;
11553     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11554       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11555       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11556 
11557       // Initialize a set a candidate getelementptrs. Note that we use a
11558       // SetVector here to preserve program order. If the index computations
11559       // are vectorizable and begin with loads, we want to minimize the chance
11560       // of having to reorder them later.
11561       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11562 
11563       // Some of the candidates may have already been vectorized after we
11564       // initially collected them. If so, they are marked as deleted, so remove
11565       // them from the set of candidates.
11566       Candidates.remove_if(
11567           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11568 
11569       // Remove from the set of candidates all pairs of getelementptrs with
11570       // constant differences. Such getelementptrs are likely not good
11571       // candidates for vectorization in a bottom-up phase since one can be
11572       // computed from the other. We also ensure all candidate getelementptr
11573       // indices are unique.
11574       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11575         auto *GEPI = GEPList[I];
11576         if (!Candidates.count(GEPI))
11577           continue;
11578         auto *SCEVI = SE->getSCEV(GEPList[I]);
11579         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11580           auto *GEPJ = GEPList[J];
11581           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11582           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11583             Candidates.remove(GEPI);
11584             Candidates.remove(GEPJ);
11585           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11586             Candidates.remove(GEPJ);
11587           }
11588         }
11589       }
11590 
11591       // We break out of the above computation as soon as we know there are
11592       // fewer than two candidates remaining.
11593       if (Candidates.size() < 2)
11594         continue;
11595 
11596       // Add the single, non-constant index of each candidate to the bundle. We
11597       // ensured the indices met these constraints when we originally collected
11598       // the getelementptrs.
11599       SmallVector<Value *, 16> Bundle(Candidates.size());
11600       auto BundleIndex = 0u;
11601       for (auto *V : Candidates) {
11602         auto *GEP = cast<GetElementPtrInst>(V);
11603         auto *GEPIdx = GEP->idx_begin()->get();
11604         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11605         Bundle[BundleIndex++] = GEPIdx;
11606       }
11607 
11608       // Try and vectorize the indices. We are currently only interested in
11609       // gather-like cases of the form:
11610       //
11611       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11612       //
11613       // where the loads of "a", the loads of "b", and the subtractions can be
11614       // performed in parallel. It's likely that detecting this pattern in a
11615       // bottom-up phase will be simpler and less costly than building a
11616       // full-blown top-down phase beginning at the consecutive loads.
11617       Changed |= tryToVectorizeList(Bundle, R);
11618     }
11619   }
11620   return Changed;
11621 }
11622 
11623 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11624   bool Changed = false;
11625   // Sort by type, base pointers and values operand. Value operands must be
11626   // compatible (have the same opcode, same parent), otherwise it is
11627   // definitely not profitable to try to vectorize them.
11628   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11629     if (V->getPointerOperandType()->getTypeID() <
11630         V2->getPointerOperandType()->getTypeID())
11631       return true;
11632     if (V->getPointerOperandType()->getTypeID() >
11633         V2->getPointerOperandType()->getTypeID())
11634       return false;
11635     // UndefValues are compatible with all other values.
11636     if (isa<UndefValue>(V->getValueOperand()) ||
11637         isa<UndefValue>(V2->getValueOperand()))
11638       return false;
11639     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11640       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11641         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11642             DT->getNode(I1->getParent());
11643         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11644             DT->getNode(I2->getParent());
11645         assert(NodeI1 && "Should only process reachable instructions");
11646         assert(NodeI2 && "Should only process reachable instructions");
11647         assert((NodeI1 == NodeI2) ==
11648                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11649                "Different nodes should have different DFS numbers");
11650         if (NodeI1 != NodeI2)
11651           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11652         InstructionsState S = getSameOpcode({I1, I2});
11653         if (S.getOpcode())
11654           return false;
11655         return I1->getOpcode() < I2->getOpcode();
11656       }
11657     if (isa<Constant>(V->getValueOperand()) &&
11658         isa<Constant>(V2->getValueOperand()))
11659       return false;
11660     return V->getValueOperand()->getValueID() <
11661            V2->getValueOperand()->getValueID();
11662   };
11663 
11664   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11665     if (V1 == V2)
11666       return true;
11667     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11668       return false;
11669     // Undefs are compatible with any other value.
11670     if (isa<UndefValue>(V1->getValueOperand()) ||
11671         isa<UndefValue>(V2->getValueOperand()))
11672       return true;
11673     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11674       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11675         if (I1->getParent() != I2->getParent())
11676           return false;
11677         InstructionsState S = getSameOpcode({I1, I2});
11678         return S.getOpcode() > 0;
11679       }
11680     if (isa<Constant>(V1->getValueOperand()) &&
11681         isa<Constant>(V2->getValueOperand()))
11682       return true;
11683     return V1->getValueOperand()->getValueID() ==
11684            V2->getValueOperand()->getValueID();
11685   };
11686   auto Limit = [&R, this](StoreInst *SI) {
11687     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11688     return R.getMinVF(EltSize);
11689   };
11690 
11691   // Attempt to sort and vectorize each of the store-groups.
11692   for (auto &Pair : Stores) {
11693     if (Pair.second.size() < 2)
11694       continue;
11695 
11696     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11697                       << Pair.second.size() << ".\n");
11698 
11699     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11700       continue;
11701 
11702     Changed |= tryToVectorizeSequence<StoreInst>(
11703         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11704         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11705           return vectorizeStores(Candidates, R);
11706         },
11707         /*LimitForRegisterSize=*/false);
11708   }
11709   return Changed;
11710 }
11711 
11712 char SLPVectorizer::ID = 0;
11713 
11714 static const char lv_name[] = "SLP Vectorizer";
11715 
11716 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11717 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11718 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11719 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11720 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11721 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11722 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11723 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11724 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11725 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11726 
11727 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11728