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 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6583   InstructionCost Cost = 0;
6584   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6585                     << VectorizableTree.size() << ".\n");
6586 
6587   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6588 
6589   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6590     TreeEntry &TE = *VectorizableTree[I];
6591 
6592     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6593     Cost += C;
6594     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6595                       << " for bundle that starts with " << *TE.Scalars[0]
6596                       << ".\n"
6597                       << "SLP: Current total cost = " << Cost << "\n");
6598   }
6599 
6600   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6601   InstructionCost ExtractCost = 0;
6602   SmallVector<unsigned> VF;
6603   SmallVector<SmallVector<int>> ShuffleMask;
6604   SmallVector<Value *> FirstUsers;
6605   SmallVector<APInt> DemandedElts;
6606   for (ExternalUser &EU : ExternalUses) {
6607     // We only add extract cost once for the same scalar.
6608     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6609         !ExtractCostCalculated.insert(EU.Scalar).second)
6610       continue;
6611 
6612     // Uses by ephemeral values are free (because the ephemeral value will be
6613     // removed prior to code generation, and so the extraction will be
6614     // removed as well).
6615     if (EphValues.count(EU.User))
6616       continue;
6617 
6618     // No extract cost for vector "scalar"
6619     if (isa<FixedVectorType>(EU.Scalar->getType()))
6620       continue;
6621 
6622     // Already counted the cost for external uses when tried to adjust the cost
6623     // for extractelements, no need to add it again.
6624     if (isa<ExtractElementInst>(EU.Scalar))
6625       continue;
6626 
6627     // If found user is an insertelement, do not calculate extract cost but try
6628     // to detect it as a final shuffled/identity match.
6629     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6630       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6631         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6632         if (InsertIdx) {
6633           auto *It = find_if(FirstUsers, [VU](Value *V) {
6634             return areTwoInsertFromSameBuildVector(VU,
6635                                                    cast<InsertElementInst>(V));
6636           });
6637           int VecId = -1;
6638           if (It == FirstUsers.end()) {
6639             VF.push_back(FTy->getNumElements());
6640             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6641             // Find the insertvector, vectorized in tree, if any.
6642             Value *Base = VU;
6643             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6644               // Build the mask for the vectorized insertelement instructions.
6645               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6646                 VU = IEBase;
6647                 do {
6648                   int Idx = E->findLaneForValue(Base);
6649                   ShuffleMask.back()[Idx] = Idx;
6650                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6651                 } while (E == getTreeEntry(Base));
6652                 break;
6653               }
6654               Base = cast<InsertElementInst>(Base)->getOperand(0);
6655             }
6656             FirstUsers.push_back(VU);
6657             DemandedElts.push_back(APInt::getZero(VF.back()));
6658             VecId = FirstUsers.size() - 1;
6659           } else {
6660             VecId = std::distance(FirstUsers.begin(), It);
6661           }
6662           int InIdx = *InsertIdx;
6663           ShuffleMask[VecId][InIdx] = EU.Lane;
6664           DemandedElts[VecId].setBit(InIdx);
6665           continue;
6666         }
6667       }
6668     }
6669 
6670     // If we plan to rewrite the tree in a smaller type, we will need to sign
6671     // extend the extracted value back to the original type. Here, we account
6672     // for the extract and the added cost of the sign extend if needed.
6673     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6674     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6675     if (MinBWs.count(ScalarRoot)) {
6676       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6677       auto Extend =
6678           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6679       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6680       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6681                                                    VecTy, EU.Lane);
6682     } else {
6683       ExtractCost +=
6684           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6685     }
6686   }
6687 
6688   InstructionCost SpillCost = getSpillCost();
6689   Cost += SpillCost + ExtractCost;
6690   if (FirstUsers.size() == 1) {
6691     int Limit = ShuffleMask.front().size() * 2;
6692     if (!all_of(ShuffleMask.front(),
6693                 [Limit](int Idx) { return Idx < Limit; }) ||
6694         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6695       InstructionCost C = TTI->getShuffleCost(
6696           TTI::SK_PermuteSingleSrc,
6697           cast<FixedVectorType>(FirstUsers.front()->getType()),
6698           ShuffleMask.front());
6699       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6700                         << " for final shuffle of insertelement external users "
6701                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6702                         << "SLP: Current total cost = " << Cost << "\n");
6703       Cost += C;
6704     }
6705     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6706         cast<FixedVectorType>(FirstUsers.front()->getType()),
6707         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6708     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6709                       << " for insertelements gather.\n"
6710                       << "SLP: Current total cost = " << Cost << "\n");
6711     Cost -= InsertCost;
6712   } else if (FirstUsers.size() >= 2) {
6713     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6714     // Combined masks of the first 2 vectors.
6715     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6716     copy(ShuffleMask.front(), CombinedMask.begin());
6717     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6718     auto *VecTy = FixedVectorType::get(
6719         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6720         MaxVF);
6721     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6722       if (ShuffleMask[1][I] != UndefMaskElem) {
6723         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6724         CombinedDemandedElts.setBit(I);
6725       }
6726     }
6727     InstructionCost C =
6728         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6729     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6730                       << " for final shuffle of vector node and external "
6731                          "insertelement users "
6732                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6733                       << "SLP: Current total cost = " << Cost << "\n");
6734     Cost += C;
6735     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6736         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6737     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6738                       << " for insertelements gather.\n"
6739                       << "SLP: Current total cost = " << Cost << "\n");
6740     Cost -= InsertCost;
6741     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6742       if (ShuffleMask[I].empty())
6743         continue;
6744       // Other elements - permutation of 2 vectors (the initial one and the
6745       // next Ith incoming vector).
6746       unsigned VF = ShuffleMask[I].size();
6747       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6748         int Mask = ShuffleMask[I][Idx];
6749         if (Mask != UndefMaskElem)
6750           CombinedMask[Idx] = MaxVF + Mask;
6751         else if (CombinedMask[Idx] != UndefMaskElem)
6752           CombinedMask[Idx] = Idx;
6753       }
6754       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6755         if (CombinedMask[Idx] != UndefMaskElem)
6756           CombinedMask[Idx] = Idx;
6757       InstructionCost C =
6758           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6759       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6760                         << " for final shuffle of vector node and external "
6761                            "insertelement users "
6762                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6763                         << "SLP: Current total cost = " << Cost << "\n");
6764       Cost += C;
6765       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6766           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6767           /*Insert*/ true, /*Extract*/ false);
6768       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6769                         << " for insertelements gather.\n"
6770                         << "SLP: Current total cost = " << Cost << "\n");
6771       Cost -= InsertCost;
6772     }
6773   }
6774 
6775 #ifndef NDEBUG
6776   SmallString<256> Str;
6777   {
6778     raw_svector_ostream OS(Str);
6779     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6780        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6781        << "SLP: Total Cost = " << Cost << ".\n";
6782   }
6783   LLVM_DEBUG(dbgs() << Str);
6784   if (ViewSLPTree)
6785     ViewGraph(this, "SLP" + F->getName(), false, Str);
6786 #endif
6787 
6788   return Cost;
6789 }
6790 
6791 Optional<TargetTransformInfo::ShuffleKind>
6792 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6793                                SmallVectorImpl<const TreeEntry *> &Entries) {
6794   // TODO: currently checking only for Scalars in the tree entry, need to count
6795   // reused elements too for better cost estimation.
6796   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6797   Entries.clear();
6798   // Build a lists of values to tree entries.
6799   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6800   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6801     if (EntryPtr.get() == TE)
6802       break;
6803     if (EntryPtr->State != TreeEntry::NeedToGather)
6804       continue;
6805     for (Value *V : EntryPtr->Scalars)
6806       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6807   }
6808   // Find all tree entries used by the gathered values. If no common entries
6809   // found - not a shuffle.
6810   // Here we build a set of tree nodes for each gathered value and trying to
6811   // find the intersection between these sets. If we have at least one common
6812   // tree node for each gathered value - we have just a permutation of the
6813   // single vector. If we have 2 different sets, we're in situation where we
6814   // have a permutation of 2 input vectors.
6815   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6816   DenseMap<Value *, int> UsedValuesEntry;
6817   for (Value *V : TE->Scalars) {
6818     if (isa<UndefValue>(V))
6819       continue;
6820     // Build a list of tree entries where V is used.
6821     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6822     auto It = ValueToTEs.find(V);
6823     if (It != ValueToTEs.end())
6824       VToTEs = It->second;
6825     if (const TreeEntry *VTE = getTreeEntry(V))
6826       VToTEs.insert(VTE);
6827     if (VToTEs.empty())
6828       return None;
6829     if (UsedTEs.empty()) {
6830       // The first iteration, just insert the list of nodes to vector.
6831       UsedTEs.push_back(VToTEs);
6832     } else {
6833       // Need to check if there are any previously used tree nodes which use V.
6834       // If there are no such nodes, consider that we have another one input
6835       // vector.
6836       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6837       unsigned Idx = 0;
6838       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6839         // Do we have a non-empty intersection of previously listed tree entries
6840         // and tree entries using current V?
6841         set_intersect(VToTEs, Set);
6842         if (!VToTEs.empty()) {
6843           // Yes, write the new subset and continue analysis for the next
6844           // scalar.
6845           Set.swap(VToTEs);
6846           break;
6847         }
6848         VToTEs = SavedVToTEs;
6849         ++Idx;
6850       }
6851       // No non-empty intersection found - need to add a second set of possible
6852       // source vectors.
6853       if (Idx == UsedTEs.size()) {
6854         // If the number of input vectors is greater than 2 - not a permutation,
6855         // fallback to the regular gather.
6856         if (UsedTEs.size() == 2)
6857           return None;
6858         UsedTEs.push_back(SavedVToTEs);
6859         Idx = UsedTEs.size() - 1;
6860       }
6861       UsedValuesEntry.try_emplace(V, Idx);
6862     }
6863   }
6864 
6865   if (UsedTEs.empty()) {
6866     assert(all_of(TE->Scalars, UndefValue::classof) &&
6867            "Expected vector of undefs only.");
6868     return None;
6869   }
6870 
6871   unsigned VF = 0;
6872   if (UsedTEs.size() == 1) {
6873     // Try to find the perfect match in another gather node at first.
6874     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6875       return EntryPtr->isSame(TE->Scalars);
6876     });
6877     if (It != UsedTEs.front().end()) {
6878       Entries.push_back(*It);
6879       std::iota(Mask.begin(), Mask.end(), 0);
6880       return TargetTransformInfo::SK_PermuteSingleSrc;
6881     }
6882     // No perfect match, just shuffle, so choose the first tree node.
6883     Entries.push_back(*UsedTEs.front().begin());
6884   } else {
6885     // Try to find nodes with the same vector factor.
6886     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6887     DenseMap<int, const TreeEntry *> VFToTE;
6888     for (const TreeEntry *TE : UsedTEs.front())
6889       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6890     for (const TreeEntry *TE : UsedTEs.back()) {
6891       auto It = VFToTE.find(TE->getVectorFactor());
6892       if (It != VFToTE.end()) {
6893         VF = It->first;
6894         Entries.push_back(It->second);
6895         Entries.push_back(TE);
6896         break;
6897       }
6898     }
6899     // No 2 source vectors with the same vector factor - give up and do regular
6900     // gather.
6901     if (Entries.empty())
6902       return None;
6903   }
6904 
6905   // Build a shuffle mask for better cost estimation and vector emission.
6906   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6907     Value *V = TE->Scalars[I];
6908     if (isa<UndefValue>(V))
6909       continue;
6910     unsigned Idx = UsedValuesEntry.lookup(V);
6911     const TreeEntry *VTE = Entries[Idx];
6912     int FoundLane = VTE->findLaneForValue(V);
6913     Mask[I] = Idx * VF + FoundLane;
6914     // Extra check required by isSingleSourceMaskImpl function (called by
6915     // ShuffleVectorInst::isSingleSourceMask).
6916     if (Mask[I] >= 2 * E)
6917       return None;
6918   }
6919   switch (Entries.size()) {
6920   case 1:
6921     return TargetTransformInfo::SK_PermuteSingleSrc;
6922   case 2:
6923     return TargetTransformInfo::SK_PermuteTwoSrc;
6924   default:
6925     break;
6926   }
6927   return None;
6928 }
6929 
6930 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6931                                        const APInt &ShuffledIndices,
6932                                        bool NeedToShuffle) const {
6933   InstructionCost Cost =
6934       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6935                                     /*Extract*/ false);
6936   if (NeedToShuffle)
6937     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6938   return Cost;
6939 }
6940 
6941 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6942   // Find the type of the operands in VL.
6943   Type *ScalarTy = VL[0]->getType();
6944   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6945     ScalarTy = SI->getValueOperand()->getType();
6946   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6947   bool DuplicateNonConst = false;
6948   // Find the cost of inserting/extracting values from the vector.
6949   // Check if the same elements are inserted several times and count them as
6950   // shuffle candidates.
6951   APInt ShuffledElements = APInt::getZero(VL.size());
6952   DenseSet<Value *> UniqueElements;
6953   // Iterate in reverse order to consider insert elements with the high cost.
6954   for (unsigned I = VL.size(); I > 0; --I) {
6955     unsigned Idx = I - 1;
6956     // No need to shuffle duplicates for constants.
6957     if (isConstant(VL[Idx])) {
6958       ShuffledElements.setBit(Idx);
6959       continue;
6960     }
6961     if (!UniqueElements.insert(VL[Idx]).second) {
6962       DuplicateNonConst = true;
6963       ShuffledElements.setBit(Idx);
6964     }
6965   }
6966   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6967 }
6968 
6969 // Perform operand reordering on the instructions in VL and return the reordered
6970 // operands in Left and Right.
6971 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6972                                              SmallVectorImpl<Value *> &Left,
6973                                              SmallVectorImpl<Value *> &Right,
6974                                              const DataLayout &DL,
6975                                              ScalarEvolution &SE,
6976                                              const BoUpSLP &R) {
6977   if (VL.empty())
6978     return;
6979   VLOperands Ops(VL, DL, SE, R);
6980   // Reorder the operands in place.
6981   Ops.reorder();
6982   Left = Ops.getVL(0);
6983   Right = Ops.getVL(1);
6984 }
6985 
6986 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6987   // Get the basic block this bundle is in. All instructions in the bundle
6988   // should be in this block.
6989   auto *Front = E->getMainOp();
6990   auto *BB = Front->getParent();
6991   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6992     auto *I = cast<Instruction>(V);
6993     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6994   }));
6995 
6996   auto &&FindLastInst = [E, Front]() {
6997     Instruction *LastInst = Front;
6998     for (Value *V : E->Scalars) {
6999       auto *I = dyn_cast<Instruction>(V);
7000       if (!I)
7001         continue;
7002       if (LastInst->comesBefore(I))
7003         LastInst = I;
7004     }
7005     return LastInst;
7006   };
7007 
7008   auto &&FindFirstInst = [E, Front]() {
7009     Instruction *FirstInst = Front;
7010     for (Value *V : E->Scalars) {
7011       auto *I = dyn_cast<Instruction>(V);
7012       if (!I)
7013         continue;
7014       if (I->comesBefore(FirstInst))
7015         FirstInst = I;
7016     }
7017     return FirstInst;
7018   };
7019 
7020   // Set the insert point to the beginning of the basic block if the entry
7021   // should not be scheduled.
7022   if (E->State != TreeEntry::NeedToGather &&
7023       doesNotNeedToSchedule(E->Scalars)) {
7024     Instruction *InsertInst;
7025     if (all_of(E->Scalars, isUsedOutsideBlock))
7026       InsertInst = FindLastInst();
7027     else
7028       InsertInst = FindFirstInst();
7029     // If the instruction is PHI, set the insert point after all the PHIs.
7030     if (isa<PHINode>(InsertInst))
7031       InsertInst = BB->getFirstNonPHI();
7032     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7033     Builder.SetInsertPoint(BB, InsertPt);
7034     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7035     return;
7036   }
7037 
7038   // The last instruction in the bundle in program order.
7039   Instruction *LastInst = nullptr;
7040 
7041   // Find the last instruction. The common case should be that BB has been
7042   // scheduled, and the last instruction is VL.back(). So we start with
7043   // VL.back() and iterate over schedule data until we reach the end of the
7044   // bundle. The end of the bundle is marked by null ScheduleData.
7045   if (BlocksSchedules.count(BB)) {
7046     Value *V = E->isOneOf(E->Scalars.back());
7047     if (doesNotNeedToBeScheduled(V))
7048       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7049     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7050     if (Bundle && Bundle->isPartOfBundle())
7051       for (; Bundle; Bundle = Bundle->NextInBundle)
7052         if (Bundle->OpValue == Bundle->Inst)
7053           LastInst = Bundle->Inst;
7054   }
7055 
7056   // LastInst can still be null at this point if there's either not an entry
7057   // for BB in BlocksSchedules or there's no ScheduleData available for
7058   // VL.back(). This can be the case if buildTree_rec aborts for various
7059   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7060   // size is reached, etc.). ScheduleData is initialized in the scheduling
7061   // "dry-run".
7062   //
7063   // If this happens, we can still find the last instruction by brute force. We
7064   // iterate forwards from Front (inclusive) until we either see all
7065   // instructions in the bundle or reach the end of the block. If Front is the
7066   // last instruction in program order, LastInst will be set to Front, and we
7067   // will visit all the remaining instructions in the block.
7068   //
7069   // One of the reasons we exit early from buildTree_rec is to place an upper
7070   // bound on compile-time. Thus, taking an additional compile-time hit here is
7071   // not ideal. However, this should be exceedingly rare since it requires that
7072   // we both exit early from buildTree_rec and that the bundle be out-of-order
7073   // (causing us to iterate all the way to the end of the block).
7074   if (!LastInst) {
7075     LastInst = FindLastInst();
7076     // If the instruction is PHI, set the insert point after all the PHIs.
7077     if (isa<PHINode>(LastInst))
7078       LastInst = BB->getFirstNonPHI()->getPrevNode();
7079   }
7080   assert(LastInst && "Failed to find last instruction in bundle");
7081 
7082   // Set the insertion point after the last instruction in the bundle. Set the
7083   // debug location to Front.
7084   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7085   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7086 }
7087 
7088 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7089   // List of instructions/lanes from current block and/or the blocks which are
7090   // part of the current loop. These instructions will be inserted at the end to
7091   // make it possible to optimize loops and hoist invariant instructions out of
7092   // the loops body with better chances for success.
7093   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7094   SmallSet<int, 4> PostponedIndices;
7095   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7096   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7097     SmallPtrSet<BasicBlock *, 4> Visited;
7098     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7099       InsertBB = InsertBB->getSinglePredecessor();
7100     return InsertBB && InsertBB == InstBB;
7101   };
7102   for (int I = 0, E = VL.size(); I < E; ++I) {
7103     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7104       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7105            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7106           PostponedIndices.insert(I).second)
7107         PostponedInsts.emplace_back(Inst, I);
7108   }
7109 
7110   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7111     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7112     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7113     if (!InsElt)
7114       return Vec;
7115     GatherShuffleSeq.insert(InsElt);
7116     CSEBlocks.insert(InsElt->getParent());
7117     // Add to our 'need-to-extract' list.
7118     if (TreeEntry *Entry = getTreeEntry(V)) {
7119       // Find which lane we need to extract.
7120       unsigned FoundLane = Entry->findLaneForValue(V);
7121       ExternalUses.emplace_back(V, InsElt, FoundLane);
7122     }
7123     return Vec;
7124   };
7125   Value *Val0 =
7126       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7127   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7128   Value *Vec = PoisonValue::get(VecTy);
7129   SmallVector<int> NonConsts;
7130   // Insert constant values at first.
7131   for (int I = 0, E = VL.size(); I < E; ++I) {
7132     if (PostponedIndices.contains(I))
7133       continue;
7134     if (!isConstant(VL[I])) {
7135       NonConsts.push_back(I);
7136       continue;
7137     }
7138     Vec = CreateInsertElement(Vec, VL[I], I);
7139   }
7140   // Insert non-constant values.
7141   for (int I : NonConsts)
7142     Vec = CreateInsertElement(Vec, VL[I], I);
7143   // Append instructions, which are/may be part of the loop, in the end to make
7144   // it possible to hoist non-loop-based instructions.
7145   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7146     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7147 
7148   return Vec;
7149 }
7150 
7151 namespace {
7152 /// Merges shuffle masks and emits final shuffle instruction, if required.
7153 class ShuffleInstructionBuilder {
7154   IRBuilderBase &Builder;
7155   const unsigned VF = 0;
7156   bool IsFinalized = false;
7157   SmallVector<int, 4> Mask;
7158   /// Holds all of the instructions that we gathered.
7159   SetVector<Instruction *> &GatherShuffleSeq;
7160   /// A list of blocks that we are going to CSE.
7161   SetVector<BasicBlock *> &CSEBlocks;
7162 
7163 public:
7164   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7165                             SetVector<Instruction *> &GatherShuffleSeq,
7166                             SetVector<BasicBlock *> &CSEBlocks)
7167       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7168         CSEBlocks(CSEBlocks) {}
7169 
7170   /// Adds a mask, inverting it before applying.
7171   void addInversedMask(ArrayRef<unsigned> SubMask) {
7172     if (SubMask.empty())
7173       return;
7174     SmallVector<int, 4> NewMask;
7175     inversePermutation(SubMask, NewMask);
7176     addMask(NewMask);
7177   }
7178 
7179   /// Functions adds masks, merging them into  single one.
7180   void addMask(ArrayRef<unsigned> SubMask) {
7181     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7182     addMask(NewMask);
7183   }
7184 
7185   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7186 
7187   Value *finalize(Value *V) {
7188     IsFinalized = true;
7189     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7190     if (VF == ValueVF && Mask.empty())
7191       return V;
7192     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7193     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7194     addMask(NormalizedMask);
7195 
7196     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7197       return V;
7198     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7199     if (auto *I = dyn_cast<Instruction>(Vec)) {
7200       GatherShuffleSeq.insert(I);
7201       CSEBlocks.insert(I->getParent());
7202     }
7203     return Vec;
7204   }
7205 
7206   ~ShuffleInstructionBuilder() {
7207     assert((IsFinalized || Mask.empty()) &&
7208            "Shuffle construction must be finalized.");
7209   }
7210 };
7211 } // namespace
7212 
7213 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7214   const unsigned VF = VL.size();
7215   InstructionsState S = getSameOpcode(VL);
7216   if (S.getOpcode()) {
7217     if (TreeEntry *E = getTreeEntry(S.OpValue))
7218       if (E->isSame(VL)) {
7219         Value *V = vectorizeTree(E);
7220         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7221           if (!E->ReuseShuffleIndices.empty()) {
7222             // Reshuffle to get only unique values.
7223             // If some of the scalars are duplicated in the vectorization tree
7224             // entry, we do not vectorize them but instead generate a mask for
7225             // the reuses. But if there are several users of the same entry,
7226             // they may have different vectorization factors. This is especially
7227             // important for PHI nodes. In this case, we need to adapt the
7228             // resulting instruction for the user vectorization factor and have
7229             // to reshuffle it again to take only unique elements of the vector.
7230             // Without this code the function incorrectly returns reduced vector
7231             // instruction with the same elements, not with the unique ones.
7232 
7233             // block:
7234             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7235             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7236             // ... (use %2)
7237             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7238             // br %block
7239             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7240             SmallSet<int, 4> UsedIdxs;
7241             int Pos = 0;
7242             int Sz = VL.size();
7243             for (int Idx : E->ReuseShuffleIndices) {
7244               if (Idx != Sz && Idx != UndefMaskElem &&
7245                   UsedIdxs.insert(Idx).second)
7246                 UniqueIdxs[Idx] = Pos;
7247               ++Pos;
7248             }
7249             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7250                                             "less than original vector size.");
7251             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7252             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7253           } else {
7254             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7255                    "Expected vectorization factor less "
7256                    "than original vector size.");
7257             SmallVector<int> UniformMask(VF, 0);
7258             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7259             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7260           }
7261           if (auto *I = dyn_cast<Instruction>(V)) {
7262             GatherShuffleSeq.insert(I);
7263             CSEBlocks.insert(I->getParent());
7264           }
7265         }
7266         return V;
7267       }
7268   }
7269 
7270   // Can't vectorize this, so simply build a new vector with each lane
7271   // corresponding to the requested value.
7272   return createBuildVector(VL);
7273 }
7274 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7275   unsigned VF = VL.size();
7276   // Exploit possible reuse of values across lanes.
7277   SmallVector<int> ReuseShuffleIndicies;
7278   SmallVector<Value *> UniqueValues;
7279   if (VL.size() > 2) {
7280     DenseMap<Value *, unsigned> UniquePositions;
7281     unsigned NumValues =
7282         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7283                                     return !isa<UndefValue>(V);
7284                                   }).base());
7285     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7286     int UniqueVals = 0;
7287     for (Value *V : VL.drop_back(VL.size() - VF)) {
7288       if (isa<UndefValue>(V)) {
7289         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7290         continue;
7291       }
7292       if (isConstant(V)) {
7293         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7294         UniqueValues.emplace_back(V);
7295         continue;
7296       }
7297       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7298       ReuseShuffleIndicies.emplace_back(Res.first->second);
7299       if (Res.second) {
7300         UniqueValues.emplace_back(V);
7301         ++UniqueVals;
7302       }
7303     }
7304     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7305       // Emit pure splat vector.
7306       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7307                                   UndefMaskElem);
7308     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7309       ReuseShuffleIndicies.clear();
7310       UniqueValues.clear();
7311       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7312     }
7313     UniqueValues.append(VF - UniqueValues.size(),
7314                         PoisonValue::get(VL[0]->getType()));
7315     VL = UniqueValues;
7316   }
7317 
7318   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7319                                            CSEBlocks);
7320   Value *Vec = gather(VL);
7321   if (!ReuseShuffleIndicies.empty()) {
7322     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7323     Vec = ShuffleBuilder.finalize(Vec);
7324   }
7325   return Vec;
7326 }
7327 
7328 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7329   IRBuilder<>::InsertPointGuard Guard(Builder);
7330 
7331   if (E->VectorizedValue) {
7332     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7333     return E->VectorizedValue;
7334   }
7335 
7336   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7337   unsigned VF = E->getVectorFactor();
7338   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7339                                            CSEBlocks);
7340   if (E->State == TreeEntry::NeedToGather) {
7341     if (E->getMainOp())
7342       setInsertPointAfterBundle(E);
7343     Value *Vec;
7344     SmallVector<int> Mask;
7345     SmallVector<const TreeEntry *> Entries;
7346     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7347         isGatherShuffledEntry(E, Mask, Entries);
7348     if (Shuffle.hasValue()) {
7349       assert((Entries.size() == 1 || Entries.size() == 2) &&
7350              "Expected shuffle of 1 or 2 entries.");
7351       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7352                                         Entries.back()->VectorizedValue, Mask);
7353       if (auto *I = dyn_cast<Instruction>(Vec)) {
7354         GatherShuffleSeq.insert(I);
7355         CSEBlocks.insert(I->getParent());
7356       }
7357     } else {
7358       Vec = gather(E->Scalars);
7359     }
7360     if (NeedToShuffleReuses) {
7361       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7362       Vec = ShuffleBuilder.finalize(Vec);
7363     }
7364     E->VectorizedValue = Vec;
7365     return Vec;
7366   }
7367 
7368   assert((E->State == TreeEntry::Vectorize ||
7369           E->State == TreeEntry::ScatterVectorize) &&
7370          "Unhandled state");
7371   unsigned ShuffleOrOp =
7372       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7373   Instruction *VL0 = E->getMainOp();
7374   Type *ScalarTy = VL0->getType();
7375   if (auto *Store = dyn_cast<StoreInst>(VL0))
7376     ScalarTy = Store->getValueOperand()->getType();
7377   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7378     ScalarTy = IE->getOperand(1)->getType();
7379   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7380   switch (ShuffleOrOp) {
7381     case Instruction::PHI: {
7382       assert(
7383           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7384           "PHI reordering is free.");
7385       auto *PH = cast<PHINode>(VL0);
7386       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7387       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7388       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7389       Value *V = NewPhi;
7390 
7391       // Adjust insertion point once all PHI's have been generated.
7392       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7393       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7394 
7395       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7396       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7397       V = ShuffleBuilder.finalize(V);
7398 
7399       E->VectorizedValue = V;
7400 
7401       // PHINodes may have multiple entries from the same block. We want to
7402       // visit every block once.
7403       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7404 
7405       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7406         ValueList Operands;
7407         BasicBlock *IBB = PH->getIncomingBlock(i);
7408 
7409         if (!VisitedBBs.insert(IBB).second) {
7410           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7411           continue;
7412         }
7413 
7414         Builder.SetInsertPoint(IBB->getTerminator());
7415         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7416         Value *Vec = vectorizeTree(E->getOperand(i));
7417         NewPhi->addIncoming(Vec, IBB);
7418       }
7419 
7420       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7421              "Invalid number of incoming values");
7422       return V;
7423     }
7424 
7425     case Instruction::ExtractElement: {
7426       Value *V = E->getSingleOperand(0);
7427       Builder.SetInsertPoint(VL0);
7428       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7429       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7430       V = ShuffleBuilder.finalize(V);
7431       E->VectorizedValue = V;
7432       return V;
7433     }
7434     case Instruction::ExtractValue: {
7435       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7436       Builder.SetInsertPoint(LI);
7437       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7438       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7439       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7440       Value *NewV = propagateMetadata(V, E->Scalars);
7441       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7442       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7443       NewV = ShuffleBuilder.finalize(NewV);
7444       E->VectorizedValue = NewV;
7445       return NewV;
7446     }
7447     case Instruction::InsertElement: {
7448       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7449       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7450       Value *V = vectorizeTree(E->getOperand(1));
7451 
7452       // Create InsertVector shuffle if necessary
7453       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7454         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7455       }));
7456       const unsigned NumElts =
7457           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7458       const unsigned NumScalars = E->Scalars.size();
7459 
7460       unsigned Offset = *getInsertIndex(VL0);
7461       assert(Offset < NumElts && "Failed to find vector index offset");
7462 
7463       // Create shuffle to resize vector
7464       SmallVector<int> Mask;
7465       if (!E->ReorderIndices.empty()) {
7466         inversePermutation(E->ReorderIndices, Mask);
7467         Mask.append(NumElts - NumScalars, UndefMaskElem);
7468       } else {
7469         Mask.assign(NumElts, UndefMaskElem);
7470         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7471       }
7472       // Create InsertVector shuffle if necessary
7473       bool IsIdentity = true;
7474       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7475       Mask.swap(PrevMask);
7476       for (unsigned I = 0; I < NumScalars; ++I) {
7477         Value *Scalar = E->Scalars[PrevMask[I]];
7478         unsigned InsertIdx = *getInsertIndex(Scalar);
7479         IsIdentity &= InsertIdx - Offset == I;
7480         Mask[InsertIdx - Offset] = I;
7481       }
7482       if (!IsIdentity || NumElts != NumScalars) {
7483         V = Builder.CreateShuffleVector(V, Mask);
7484         if (auto *I = dyn_cast<Instruction>(V)) {
7485           GatherShuffleSeq.insert(I);
7486           CSEBlocks.insert(I->getParent());
7487         }
7488       }
7489 
7490       if ((!IsIdentity || Offset != 0 ||
7491            !isUndefVector(FirstInsert->getOperand(0))) &&
7492           NumElts != NumScalars) {
7493         SmallVector<int> InsertMask(NumElts);
7494         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7495         for (unsigned I = 0; I < NumElts; I++) {
7496           if (Mask[I] != UndefMaskElem)
7497             InsertMask[Offset + I] = NumElts + I;
7498         }
7499 
7500         V = Builder.CreateShuffleVector(
7501             FirstInsert->getOperand(0), V, InsertMask,
7502             cast<Instruction>(E->Scalars.back())->getName());
7503         if (auto *I = dyn_cast<Instruction>(V)) {
7504           GatherShuffleSeq.insert(I);
7505           CSEBlocks.insert(I->getParent());
7506         }
7507       }
7508 
7509       ++NumVectorInstructions;
7510       E->VectorizedValue = V;
7511       return V;
7512     }
7513     case Instruction::ZExt:
7514     case Instruction::SExt:
7515     case Instruction::FPToUI:
7516     case Instruction::FPToSI:
7517     case Instruction::FPExt:
7518     case Instruction::PtrToInt:
7519     case Instruction::IntToPtr:
7520     case Instruction::SIToFP:
7521     case Instruction::UIToFP:
7522     case Instruction::Trunc:
7523     case Instruction::FPTrunc:
7524     case Instruction::BitCast: {
7525       setInsertPointAfterBundle(E);
7526 
7527       Value *InVec = vectorizeTree(E->getOperand(0));
7528 
7529       if (E->VectorizedValue) {
7530         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7531         return E->VectorizedValue;
7532       }
7533 
7534       auto *CI = cast<CastInst>(VL0);
7535       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7536       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7537       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7538       V = ShuffleBuilder.finalize(V);
7539 
7540       E->VectorizedValue = V;
7541       ++NumVectorInstructions;
7542       return V;
7543     }
7544     case Instruction::FCmp:
7545     case Instruction::ICmp: {
7546       setInsertPointAfterBundle(E);
7547 
7548       Value *L = vectorizeTree(E->getOperand(0));
7549       Value *R = vectorizeTree(E->getOperand(1));
7550 
7551       if (E->VectorizedValue) {
7552         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7553         return E->VectorizedValue;
7554       }
7555 
7556       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7557       Value *V = Builder.CreateCmp(P0, L, R);
7558       propagateIRFlags(V, E->Scalars, VL0);
7559       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7560       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7561       V = ShuffleBuilder.finalize(V);
7562 
7563       E->VectorizedValue = V;
7564       ++NumVectorInstructions;
7565       return V;
7566     }
7567     case Instruction::Select: {
7568       setInsertPointAfterBundle(E);
7569 
7570       Value *Cond = vectorizeTree(E->getOperand(0));
7571       Value *True = vectorizeTree(E->getOperand(1));
7572       Value *False = vectorizeTree(E->getOperand(2));
7573 
7574       if (E->VectorizedValue) {
7575         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7576         return E->VectorizedValue;
7577       }
7578 
7579       Value *V = Builder.CreateSelect(Cond, True, False);
7580       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7581       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7582       V = ShuffleBuilder.finalize(V);
7583 
7584       E->VectorizedValue = V;
7585       ++NumVectorInstructions;
7586       return V;
7587     }
7588     case Instruction::FNeg: {
7589       setInsertPointAfterBundle(E);
7590 
7591       Value *Op = vectorizeTree(E->getOperand(0));
7592 
7593       if (E->VectorizedValue) {
7594         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7595         return E->VectorizedValue;
7596       }
7597 
7598       Value *V = Builder.CreateUnOp(
7599           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7600       propagateIRFlags(V, E->Scalars, VL0);
7601       if (auto *I = dyn_cast<Instruction>(V))
7602         V = propagateMetadata(I, E->Scalars);
7603 
7604       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7605       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7606       V = ShuffleBuilder.finalize(V);
7607 
7608       E->VectorizedValue = V;
7609       ++NumVectorInstructions;
7610 
7611       return V;
7612     }
7613     case Instruction::Add:
7614     case Instruction::FAdd:
7615     case Instruction::Sub:
7616     case Instruction::FSub:
7617     case Instruction::Mul:
7618     case Instruction::FMul:
7619     case Instruction::UDiv:
7620     case Instruction::SDiv:
7621     case Instruction::FDiv:
7622     case Instruction::URem:
7623     case Instruction::SRem:
7624     case Instruction::FRem:
7625     case Instruction::Shl:
7626     case Instruction::LShr:
7627     case Instruction::AShr:
7628     case Instruction::And:
7629     case Instruction::Or:
7630     case Instruction::Xor: {
7631       setInsertPointAfterBundle(E);
7632 
7633       Value *LHS = vectorizeTree(E->getOperand(0));
7634       Value *RHS = vectorizeTree(E->getOperand(1));
7635 
7636       if (E->VectorizedValue) {
7637         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7638         return E->VectorizedValue;
7639       }
7640 
7641       Value *V = Builder.CreateBinOp(
7642           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7643           RHS);
7644       propagateIRFlags(V, E->Scalars, VL0);
7645       if (auto *I = dyn_cast<Instruction>(V))
7646         V = propagateMetadata(I, E->Scalars);
7647 
7648       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7649       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7650       V = ShuffleBuilder.finalize(V);
7651 
7652       E->VectorizedValue = V;
7653       ++NumVectorInstructions;
7654 
7655       return V;
7656     }
7657     case Instruction::Load: {
7658       // Loads are inserted at the head of the tree because we don't want to
7659       // sink them all the way down past store instructions.
7660       setInsertPointAfterBundle(E);
7661 
7662       LoadInst *LI = cast<LoadInst>(VL0);
7663       Instruction *NewLI;
7664       unsigned AS = LI->getPointerAddressSpace();
7665       Value *PO = LI->getPointerOperand();
7666       if (E->State == TreeEntry::Vectorize) {
7667         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7668         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7669 
7670         // The pointer operand uses an in-tree scalar so we add the new BitCast
7671         // or LoadInst to ExternalUses list to make sure that an extract will
7672         // be generated in the future.
7673         if (TreeEntry *Entry = getTreeEntry(PO)) {
7674           // Find which lane we need to extract.
7675           unsigned FoundLane = Entry->findLaneForValue(PO);
7676           ExternalUses.emplace_back(
7677               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7678         }
7679       } else {
7680         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7681         Value *VecPtr = vectorizeTree(E->getOperand(0));
7682         // Use the minimum alignment of the gathered loads.
7683         Align CommonAlignment = LI->getAlign();
7684         for (Value *V : E->Scalars)
7685           CommonAlignment =
7686               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7687         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7688       }
7689       Value *V = propagateMetadata(NewLI, E->Scalars);
7690 
7691       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7692       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7693       V = ShuffleBuilder.finalize(V);
7694       E->VectorizedValue = V;
7695       ++NumVectorInstructions;
7696       return V;
7697     }
7698     case Instruction::Store: {
7699       auto *SI = cast<StoreInst>(VL0);
7700       unsigned AS = SI->getPointerAddressSpace();
7701 
7702       setInsertPointAfterBundle(E);
7703 
7704       Value *VecValue = vectorizeTree(E->getOperand(0));
7705       ShuffleBuilder.addMask(E->ReorderIndices);
7706       VecValue = ShuffleBuilder.finalize(VecValue);
7707 
7708       Value *ScalarPtr = SI->getPointerOperand();
7709       Value *VecPtr = Builder.CreateBitCast(
7710           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7711       StoreInst *ST =
7712           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7713 
7714       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7715       // StoreInst to ExternalUses to make sure that an extract will be
7716       // generated in the future.
7717       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7718         // Find which lane we need to extract.
7719         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7720         ExternalUses.push_back(ExternalUser(
7721             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7722             FoundLane));
7723       }
7724 
7725       Value *V = propagateMetadata(ST, E->Scalars);
7726 
7727       E->VectorizedValue = V;
7728       ++NumVectorInstructions;
7729       return V;
7730     }
7731     case Instruction::GetElementPtr: {
7732       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7733       setInsertPointAfterBundle(E);
7734 
7735       Value *Op0 = vectorizeTree(E->getOperand(0));
7736 
7737       SmallVector<Value *> OpVecs;
7738       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7739         Value *OpVec = vectorizeTree(E->getOperand(J));
7740         OpVecs.push_back(OpVec);
7741       }
7742 
7743       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7744       if (Instruction *I = dyn_cast<Instruction>(V))
7745         V = propagateMetadata(I, E->Scalars);
7746 
7747       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7748       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7749       V = ShuffleBuilder.finalize(V);
7750 
7751       E->VectorizedValue = V;
7752       ++NumVectorInstructions;
7753 
7754       return V;
7755     }
7756     case Instruction::Call: {
7757       CallInst *CI = cast<CallInst>(VL0);
7758       setInsertPointAfterBundle(E);
7759 
7760       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7761       if (Function *FI = CI->getCalledFunction())
7762         IID = FI->getIntrinsicID();
7763 
7764       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7765 
7766       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7767       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7768                           VecCallCosts.first <= VecCallCosts.second;
7769 
7770       Value *ScalarArg = nullptr;
7771       std::vector<Value *> OpVecs;
7772       SmallVector<Type *, 2> TysForDecl =
7773           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7774       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7775         ValueList OpVL;
7776         // Some intrinsics have scalar arguments. This argument should not be
7777         // vectorized.
7778         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7779           CallInst *CEI = cast<CallInst>(VL0);
7780           ScalarArg = CEI->getArgOperand(j);
7781           OpVecs.push_back(CEI->getArgOperand(j));
7782           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7783             TysForDecl.push_back(ScalarArg->getType());
7784           continue;
7785         }
7786 
7787         Value *OpVec = vectorizeTree(E->getOperand(j));
7788         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7789         OpVecs.push_back(OpVec);
7790         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7791           TysForDecl.push_back(OpVec->getType());
7792       }
7793 
7794       Function *CF;
7795       if (!UseIntrinsic) {
7796         VFShape Shape =
7797             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7798                                   VecTy->getNumElements())),
7799                          false /*HasGlobalPred*/);
7800         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7801       } else {
7802         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7803       }
7804 
7805       SmallVector<OperandBundleDef, 1> OpBundles;
7806       CI->getOperandBundlesAsDefs(OpBundles);
7807       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7808 
7809       // The scalar argument uses an in-tree scalar so we add the new vectorized
7810       // call to ExternalUses list to make sure that an extract will be
7811       // generated in the future.
7812       if (ScalarArg) {
7813         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7814           // Find which lane we need to extract.
7815           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7816           ExternalUses.push_back(
7817               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7818         }
7819       }
7820 
7821       propagateIRFlags(V, E->Scalars, VL0);
7822       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7823       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7824       V = ShuffleBuilder.finalize(V);
7825 
7826       E->VectorizedValue = V;
7827       ++NumVectorInstructions;
7828       return V;
7829     }
7830     case Instruction::ShuffleVector: {
7831       assert(E->isAltShuffle() &&
7832              ((Instruction::isBinaryOp(E->getOpcode()) &&
7833                Instruction::isBinaryOp(E->getAltOpcode())) ||
7834               (Instruction::isCast(E->getOpcode()) &&
7835                Instruction::isCast(E->getAltOpcode())) ||
7836               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7837              "Invalid Shuffle Vector Operand");
7838 
7839       Value *LHS = nullptr, *RHS = nullptr;
7840       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7841         setInsertPointAfterBundle(E);
7842         LHS = vectorizeTree(E->getOperand(0));
7843         RHS = vectorizeTree(E->getOperand(1));
7844       } else {
7845         setInsertPointAfterBundle(E);
7846         LHS = vectorizeTree(E->getOperand(0));
7847       }
7848 
7849       if (E->VectorizedValue) {
7850         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7851         return E->VectorizedValue;
7852       }
7853 
7854       Value *V0, *V1;
7855       if (Instruction::isBinaryOp(E->getOpcode())) {
7856         V0 = Builder.CreateBinOp(
7857             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7858         V1 = Builder.CreateBinOp(
7859             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7860       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7861         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7862         auto *AltCI = cast<CmpInst>(E->getAltOp());
7863         CmpInst::Predicate AltPred = AltCI->getPredicate();
7864         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7865       } else {
7866         V0 = Builder.CreateCast(
7867             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7868         V1 = Builder.CreateCast(
7869             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7870       }
7871       // Add V0 and V1 to later analysis to try to find and remove matching
7872       // instruction, if any.
7873       for (Value *V : {V0, V1}) {
7874         if (auto *I = dyn_cast<Instruction>(V)) {
7875           GatherShuffleSeq.insert(I);
7876           CSEBlocks.insert(I->getParent());
7877         }
7878       }
7879 
7880       // Create shuffle to take alternate operations from the vector.
7881       // Also, gather up main and alt scalar ops to propagate IR flags to
7882       // each vector operation.
7883       ValueList OpScalars, AltScalars;
7884       SmallVector<int> Mask;
7885       buildShuffleEntryMask(
7886           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7887           [E](Instruction *I) {
7888             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7889             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7890           },
7891           Mask, &OpScalars, &AltScalars);
7892 
7893       propagateIRFlags(V0, OpScalars);
7894       propagateIRFlags(V1, AltScalars);
7895 
7896       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7897       if (auto *I = dyn_cast<Instruction>(V)) {
7898         V = propagateMetadata(I, E->Scalars);
7899         GatherShuffleSeq.insert(I);
7900         CSEBlocks.insert(I->getParent());
7901       }
7902       V = ShuffleBuilder.finalize(V);
7903 
7904       E->VectorizedValue = V;
7905       ++NumVectorInstructions;
7906 
7907       return V;
7908     }
7909     default:
7910     llvm_unreachable("unknown inst");
7911   }
7912   return nullptr;
7913 }
7914 
7915 Value *BoUpSLP::vectorizeTree() {
7916   ExtraValueToDebugLocsMap ExternallyUsedValues;
7917   return vectorizeTree(ExternallyUsedValues);
7918 }
7919 
7920 Value *
7921 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7922   // All blocks must be scheduled before any instructions are inserted.
7923   for (auto &BSIter : BlocksSchedules) {
7924     scheduleBlock(BSIter.second.get());
7925   }
7926 
7927   Builder.SetInsertPoint(&F->getEntryBlock().front());
7928   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7929 
7930   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7931   // vectorized root. InstCombine will then rewrite the entire expression. We
7932   // sign extend the extracted values below.
7933   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7934   if (MinBWs.count(ScalarRoot)) {
7935     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7936       // If current instr is a phi and not the last phi, insert it after the
7937       // last phi node.
7938       if (isa<PHINode>(I))
7939         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7940       else
7941         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7942     }
7943     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7944     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7945     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7946     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7947     VectorizableTree[0]->VectorizedValue = Trunc;
7948   }
7949 
7950   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7951                     << " values .\n");
7952 
7953   // Extract all of the elements with the external uses.
7954   for (const auto &ExternalUse : ExternalUses) {
7955     Value *Scalar = ExternalUse.Scalar;
7956     llvm::User *User = ExternalUse.User;
7957 
7958     // Skip users that we already RAUW. This happens when one instruction
7959     // has multiple uses of the same value.
7960     if (User && !is_contained(Scalar->users(), User))
7961       continue;
7962     TreeEntry *E = getTreeEntry(Scalar);
7963     assert(E && "Invalid scalar");
7964     assert(E->State != TreeEntry::NeedToGather &&
7965            "Extracting from a gather list");
7966 
7967     Value *Vec = E->VectorizedValue;
7968     assert(Vec && "Can't find vectorizable value");
7969 
7970     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7971     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7972       if (Scalar->getType() != Vec->getType()) {
7973         Value *Ex;
7974         // "Reuse" the existing extract to improve final codegen.
7975         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7976           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7977                                             ES->getOperand(1));
7978         } else {
7979           Ex = Builder.CreateExtractElement(Vec, Lane);
7980         }
7981         // If necessary, sign-extend or zero-extend ScalarRoot
7982         // to the larger type.
7983         if (!MinBWs.count(ScalarRoot))
7984           return Ex;
7985         if (MinBWs[ScalarRoot].second)
7986           return Builder.CreateSExt(Ex, Scalar->getType());
7987         return Builder.CreateZExt(Ex, Scalar->getType());
7988       }
7989       assert(isa<FixedVectorType>(Scalar->getType()) &&
7990              isa<InsertElementInst>(Scalar) &&
7991              "In-tree scalar of vector type is not insertelement?");
7992       return Vec;
7993     };
7994     // If User == nullptr, the Scalar is used as extra arg. Generate
7995     // ExtractElement instruction and update the record for this scalar in
7996     // ExternallyUsedValues.
7997     if (!User) {
7998       assert(ExternallyUsedValues.count(Scalar) &&
7999              "Scalar with nullptr as an external user must be registered in "
8000              "ExternallyUsedValues map");
8001       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8002         Builder.SetInsertPoint(VecI->getParent(),
8003                                std::next(VecI->getIterator()));
8004       } else {
8005         Builder.SetInsertPoint(&F->getEntryBlock().front());
8006       }
8007       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8008       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8009       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8010       auto It = ExternallyUsedValues.find(Scalar);
8011       assert(It != ExternallyUsedValues.end() &&
8012              "Externally used scalar is not found in ExternallyUsedValues");
8013       NewInstLocs.append(It->second);
8014       ExternallyUsedValues.erase(Scalar);
8015       // Required to update internally referenced instructions.
8016       Scalar->replaceAllUsesWith(NewInst);
8017       continue;
8018     }
8019 
8020     // Generate extracts for out-of-tree users.
8021     // Find the insertion point for the extractelement lane.
8022     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8023       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8024         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8025           if (PH->getIncomingValue(i) == Scalar) {
8026             Instruction *IncomingTerminator =
8027                 PH->getIncomingBlock(i)->getTerminator();
8028             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8029               Builder.SetInsertPoint(VecI->getParent(),
8030                                      std::next(VecI->getIterator()));
8031             } else {
8032               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8033             }
8034             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8035             CSEBlocks.insert(PH->getIncomingBlock(i));
8036             PH->setOperand(i, NewInst);
8037           }
8038         }
8039       } else {
8040         Builder.SetInsertPoint(cast<Instruction>(User));
8041         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8042         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8043         User->replaceUsesOfWith(Scalar, NewInst);
8044       }
8045     } else {
8046       Builder.SetInsertPoint(&F->getEntryBlock().front());
8047       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8048       CSEBlocks.insert(&F->getEntryBlock());
8049       User->replaceUsesOfWith(Scalar, NewInst);
8050     }
8051 
8052     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8053   }
8054 
8055   // For each vectorized value:
8056   for (auto &TEPtr : VectorizableTree) {
8057     TreeEntry *Entry = TEPtr.get();
8058 
8059     // No need to handle users of gathered values.
8060     if (Entry->State == TreeEntry::NeedToGather)
8061       continue;
8062 
8063     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8064 
8065     // For each lane:
8066     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8067       Value *Scalar = Entry->Scalars[Lane];
8068 
8069 #ifndef NDEBUG
8070       Type *Ty = Scalar->getType();
8071       if (!Ty->isVoidTy()) {
8072         for (User *U : Scalar->users()) {
8073           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8074 
8075           // It is legal to delete users in the ignorelist.
8076           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
8077                   (isa_and_nonnull<Instruction>(U) &&
8078                    isDeleted(cast<Instruction>(U)))) &&
8079                  "Deleting out-of-tree value");
8080         }
8081       }
8082 #endif
8083       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8084       eraseInstruction(cast<Instruction>(Scalar));
8085     }
8086   }
8087 
8088   Builder.ClearInsertionPoint();
8089   InstrElementSize.clear();
8090 
8091   return VectorizableTree[0]->VectorizedValue;
8092 }
8093 
8094 void BoUpSLP::optimizeGatherSequence() {
8095   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8096                     << " gather sequences instructions.\n");
8097   // LICM InsertElementInst sequences.
8098   for (Instruction *I : GatherShuffleSeq) {
8099     if (isDeleted(I))
8100       continue;
8101 
8102     // Check if this block is inside a loop.
8103     Loop *L = LI->getLoopFor(I->getParent());
8104     if (!L)
8105       continue;
8106 
8107     // Check if it has a preheader.
8108     BasicBlock *PreHeader = L->getLoopPreheader();
8109     if (!PreHeader)
8110       continue;
8111 
8112     // If the vector or the element that we insert into it are
8113     // instructions that are defined in this basic block then we can't
8114     // hoist this instruction.
8115     if (any_of(I->operands(), [L](Value *V) {
8116           auto *OpI = dyn_cast<Instruction>(V);
8117           return OpI && L->contains(OpI);
8118         }))
8119       continue;
8120 
8121     // We can hoist this instruction. Move it to the pre-header.
8122     I->moveBefore(PreHeader->getTerminator());
8123   }
8124 
8125   // Make a list of all reachable blocks in our CSE queue.
8126   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8127   CSEWorkList.reserve(CSEBlocks.size());
8128   for (BasicBlock *BB : CSEBlocks)
8129     if (DomTreeNode *N = DT->getNode(BB)) {
8130       assert(DT->isReachableFromEntry(N));
8131       CSEWorkList.push_back(N);
8132     }
8133 
8134   // Sort blocks by domination. This ensures we visit a block after all blocks
8135   // dominating it are visited.
8136   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8137     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8138            "Different nodes should have different DFS numbers");
8139     return A->getDFSNumIn() < B->getDFSNumIn();
8140   });
8141 
8142   // Less defined shuffles can be replaced by the more defined copies.
8143   // Between two shuffles one is less defined if it has the same vector operands
8144   // and its mask indeces are the same as in the first one or undefs. E.g.
8145   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8146   // poison, <0, 0, 0, 0>.
8147   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8148                                            SmallVectorImpl<int> &NewMask) {
8149     if (I1->getType() != I2->getType())
8150       return false;
8151     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8152     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8153     if (!SI1 || !SI2)
8154       return I1->isIdenticalTo(I2);
8155     if (SI1->isIdenticalTo(SI2))
8156       return true;
8157     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8158       if (SI1->getOperand(I) != SI2->getOperand(I))
8159         return false;
8160     // Check if the second instruction is more defined than the first one.
8161     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8162     ArrayRef<int> SM1 = SI1->getShuffleMask();
8163     // Count trailing undefs in the mask to check the final number of used
8164     // registers.
8165     unsigned LastUndefsCnt = 0;
8166     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8167       if (SM1[I] == UndefMaskElem)
8168         ++LastUndefsCnt;
8169       else
8170         LastUndefsCnt = 0;
8171       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8172           NewMask[I] != SM1[I])
8173         return false;
8174       if (NewMask[I] == UndefMaskElem)
8175         NewMask[I] = SM1[I];
8176     }
8177     // Check if the last undefs actually change the final number of used vector
8178     // registers.
8179     return SM1.size() - LastUndefsCnt > 1 &&
8180            TTI->getNumberOfParts(SI1->getType()) ==
8181                TTI->getNumberOfParts(
8182                    FixedVectorType::get(SI1->getType()->getElementType(),
8183                                         SM1.size() - LastUndefsCnt));
8184   };
8185   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8186   // instructions. TODO: We can further optimize this scan if we split the
8187   // instructions into different buckets based on the insert lane.
8188   SmallVector<Instruction *, 16> Visited;
8189   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8190     assert(*I &&
8191            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8192            "Worklist not sorted properly!");
8193     BasicBlock *BB = (*I)->getBlock();
8194     // For all instructions in blocks containing gather sequences:
8195     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8196       if (isDeleted(&In))
8197         continue;
8198       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8199           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8200         continue;
8201 
8202       // Check if we can replace this instruction with any of the
8203       // visited instructions.
8204       bool Replaced = false;
8205       for (Instruction *&V : Visited) {
8206         SmallVector<int> NewMask;
8207         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8208             DT->dominates(V->getParent(), In.getParent())) {
8209           In.replaceAllUsesWith(V);
8210           eraseInstruction(&In);
8211           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8212             if (!NewMask.empty())
8213               SI->setShuffleMask(NewMask);
8214           Replaced = true;
8215           break;
8216         }
8217         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8218             GatherShuffleSeq.contains(V) &&
8219             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8220             DT->dominates(In.getParent(), V->getParent())) {
8221           In.moveAfter(V);
8222           V->replaceAllUsesWith(&In);
8223           eraseInstruction(V);
8224           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8225             if (!NewMask.empty())
8226               SI->setShuffleMask(NewMask);
8227           V = &In;
8228           Replaced = true;
8229           break;
8230         }
8231       }
8232       if (!Replaced) {
8233         assert(!is_contained(Visited, &In));
8234         Visited.push_back(&In);
8235       }
8236     }
8237   }
8238   CSEBlocks.clear();
8239   GatherShuffleSeq.clear();
8240 }
8241 
8242 BoUpSLP::ScheduleData *
8243 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8244   ScheduleData *Bundle = nullptr;
8245   ScheduleData *PrevInBundle = nullptr;
8246   for (Value *V : VL) {
8247     if (doesNotNeedToBeScheduled(V))
8248       continue;
8249     ScheduleData *BundleMember = getScheduleData(V);
8250     assert(BundleMember &&
8251            "no ScheduleData for bundle member "
8252            "(maybe not in same basic block)");
8253     assert(BundleMember->isSchedulingEntity() &&
8254            "bundle member already part of other bundle");
8255     if (PrevInBundle) {
8256       PrevInBundle->NextInBundle = BundleMember;
8257     } else {
8258       Bundle = BundleMember;
8259     }
8260 
8261     // Group the instructions to a bundle.
8262     BundleMember->FirstInBundle = Bundle;
8263     PrevInBundle = BundleMember;
8264   }
8265   assert(Bundle && "Failed to find schedule bundle");
8266   return Bundle;
8267 }
8268 
8269 // Groups the instructions to a bundle (which is then a single scheduling entity)
8270 // and schedules instructions until the bundle gets ready.
8271 Optional<BoUpSLP::ScheduleData *>
8272 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8273                                             const InstructionsState &S) {
8274   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8275   // instructions.
8276   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8277       doesNotNeedToSchedule(VL))
8278     return nullptr;
8279 
8280   // Initialize the instruction bundle.
8281   Instruction *OldScheduleEnd = ScheduleEnd;
8282   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8283 
8284   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8285                                                          ScheduleData *Bundle) {
8286     // The scheduling region got new instructions at the lower end (or it is a
8287     // new region for the first bundle). This makes it necessary to
8288     // recalculate all dependencies.
8289     // It is seldom that this needs to be done a second time after adding the
8290     // initial bundle to the region.
8291     if (ScheduleEnd != OldScheduleEnd) {
8292       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8293         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8294       ReSchedule = true;
8295     }
8296     if (Bundle) {
8297       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8298                         << " in block " << BB->getName() << "\n");
8299       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8300     }
8301 
8302     if (ReSchedule) {
8303       resetSchedule();
8304       initialFillReadyList(ReadyInsts);
8305     }
8306 
8307     // Now try to schedule the new bundle or (if no bundle) just calculate
8308     // dependencies. As soon as the bundle is "ready" it means that there are no
8309     // cyclic dependencies and we can schedule it. Note that's important that we
8310     // don't "schedule" the bundle yet (see cancelScheduling).
8311     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8312            !ReadyInsts.empty()) {
8313       ScheduleData *Picked = ReadyInsts.pop_back_val();
8314       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8315              "must be ready to schedule");
8316       schedule(Picked, ReadyInsts);
8317     }
8318   };
8319 
8320   // Make sure that the scheduling region contains all
8321   // instructions of the bundle.
8322   for (Value *V : VL) {
8323     if (doesNotNeedToBeScheduled(V))
8324       continue;
8325     if (!extendSchedulingRegion(V, S)) {
8326       // If the scheduling region got new instructions at the lower end (or it
8327       // is a new region for the first bundle). This makes it necessary to
8328       // recalculate all dependencies.
8329       // Otherwise the compiler may crash trying to incorrectly calculate
8330       // dependencies and emit instruction in the wrong order at the actual
8331       // scheduling.
8332       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8333       return None;
8334     }
8335   }
8336 
8337   bool ReSchedule = false;
8338   for (Value *V : VL) {
8339     if (doesNotNeedToBeScheduled(V))
8340       continue;
8341     ScheduleData *BundleMember = getScheduleData(V);
8342     assert(BundleMember &&
8343            "no ScheduleData for bundle member (maybe not in same basic block)");
8344 
8345     // Make sure we don't leave the pieces of the bundle in the ready list when
8346     // whole bundle might not be ready.
8347     ReadyInsts.remove(BundleMember);
8348 
8349     if (!BundleMember->IsScheduled)
8350       continue;
8351     // A bundle member was scheduled as single instruction before and now
8352     // needs to be scheduled as part of the bundle. We just get rid of the
8353     // existing schedule.
8354     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8355                       << " was already scheduled\n");
8356     ReSchedule = true;
8357   }
8358 
8359   auto *Bundle = buildBundle(VL);
8360   TryScheduleBundleImpl(ReSchedule, Bundle);
8361   if (!Bundle->isReady()) {
8362     cancelScheduling(VL, S.OpValue);
8363     return None;
8364   }
8365   return Bundle;
8366 }
8367 
8368 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8369                                                 Value *OpValue) {
8370   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8371       doesNotNeedToSchedule(VL))
8372     return;
8373 
8374   if (doesNotNeedToBeScheduled(OpValue))
8375     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8376   ScheduleData *Bundle = getScheduleData(OpValue);
8377   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8378   assert(!Bundle->IsScheduled &&
8379          "Can't cancel bundle which is already scheduled");
8380   assert(Bundle->isSchedulingEntity() &&
8381          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8382          "tried to unbundle something which is not a bundle");
8383 
8384   // Remove the bundle from the ready list.
8385   if (Bundle->isReady())
8386     ReadyInsts.remove(Bundle);
8387 
8388   // Un-bundle: make single instructions out of the bundle.
8389   ScheduleData *BundleMember = Bundle;
8390   while (BundleMember) {
8391     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8392     BundleMember->FirstInBundle = BundleMember;
8393     ScheduleData *Next = BundleMember->NextInBundle;
8394     BundleMember->NextInBundle = nullptr;
8395     BundleMember->TE = nullptr;
8396     if (BundleMember->unscheduledDepsInBundle() == 0) {
8397       ReadyInsts.insert(BundleMember);
8398     }
8399     BundleMember = Next;
8400   }
8401 }
8402 
8403 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8404   // Allocate a new ScheduleData for the instruction.
8405   if (ChunkPos >= ChunkSize) {
8406     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8407     ChunkPos = 0;
8408   }
8409   return &(ScheduleDataChunks.back()[ChunkPos++]);
8410 }
8411 
8412 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8413                                                       const InstructionsState &S) {
8414   if (getScheduleData(V, isOneOf(S, V)))
8415     return true;
8416   Instruction *I = dyn_cast<Instruction>(V);
8417   assert(I && "bundle member must be an instruction");
8418   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8419          !doesNotNeedToBeScheduled(I) &&
8420          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8421          "be scheduled");
8422   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8423     ScheduleData *ISD = getScheduleData(I);
8424     if (!ISD)
8425       return false;
8426     assert(isInSchedulingRegion(ISD) &&
8427            "ScheduleData not in scheduling region");
8428     ScheduleData *SD = allocateScheduleDataChunks();
8429     SD->Inst = I;
8430     SD->init(SchedulingRegionID, S.OpValue);
8431     ExtraScheduleDataMap[I][S.OpValue] = SD;
8432     return true;
8433   };
8434   if (CheckScheduleForI(I))
8435     return true;
8436   if (!ScheduleStart) {
8437     // It's the first instruction in the new region.
8438     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8439     ScheduleStart = I;
8440     ScheduleEnd = I->getNextNode();
8441     if (isOneOf(S, I) != I)
8442       CheckScheduleForI(I);
8443     assert(ScheduleEnd && "tried to vectorize a terminator?");
8444     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8445     return true;
8446   }
8447   // Search up and down at the same time, because we don't know if the new
8448   // instruction is above or below the existing scheduling region.
8449   BasicBlock::reverse_iterator UpIter =
8450       ++ScheduleStart->getIterator().getReverse();
8451   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8452   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8453   BasicBlock::iterator LowerEnd = BB->end();
8454   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8455          &*DownIter != I) {
8456     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8457       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8458       return false;
8459     }
8460 
8461     ++UpIter;
8462     ++DownIter;
8463   }
8464   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8465     assert(I->getParent() == ScheduleStart->getParent() &&
8466            "Instruction is in wrong basic block.");
8467     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8468     ScheduleStart = I;
8469     if (isOneOf(S, I) != I)
8470       CheckScheduleForI(I);
8471     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8472                       << "\n");
8473     return true;
8474   }
8475   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8476          "Expected to reach top of the basic block or instruction down the "
8477          "lower end.");
8478   assert(I->getParent() == ScheduleEnd->getParent() &&
8479          "Instruction is in wrong basic block.");
8480   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8481                    nullptr);
8482   ScheduleEnd = I->getNextNode();
8483   if (isOneOf(S, I) != I)
8484     CheckScheduleForI(I);
8485   assert(ScheduleEnd && "tried to vectorize a terminator?");
8486   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8487   return true;
8488 }
8489 
8490 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8491                                                 Instruction *ToI,
8492                                                 ScheduleData *PrevLoadStore,
8493                                                 ScheduleData *NextLoadStore) {
8494   ScheduleData *CurrentLoadStore = PrevLoadStore;
8495   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8496     // No need to allocate data for non-schedulable instructions.
8497     if (doesNotNeedToBeScheduled(I))
8498       continue;
8499     ScheduleData *SD = ScheduleDataMap.lookup(I);
8500     if (!SD) {
8501       SD = allocateScheduleDataChunks();
8502       ScheduleDataMap[I] = SD;
8503       SD->Inst = I;
8504     }
8505     assert(!isInSchedulingRegion(SD) &&
8506            "new ScheduleData already in scheduling region");
8507     SD->init(SchedulingRegionID, I);
8508 
8509     if (I->mayReadOrWriteMemory() &&
8510         (!isa<IntrinsicInst>(I) ||
8511          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8512           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8513               Intrinsic::pseudoprobe))) {
8514       // Update the linked list of memory accessing instructions.
8515       if (CurrentLoadStore) {
8516         CurrentLoadStore->NextLoadStore = SD;
8517       } else {
8518         FirstLoadStoreInRegion = SD;
8519       }
8520       CurrentLoadStore = SD;
8521     }
8522 
8523     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8524         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8525       RegionHasStackSave = true;
8526   }
8527   if (NextLoadStore) {
8528     if (CurrentLoadStore)
8529       CurrentLoadStore->NextLoadStore = NextLoadStore;
8530   } else {
8531     LastLoadStoreInRegion = CurrentLoadStore;
8532   }
8533 }
8534 
8535 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8536                                                      bool InsertInReadyList,
8537                                                      BoUpSLP *SLP) {
8538   assert(SD->isSchedulingEntity());
8539 
8540   SmallVector<ScheduleData *, 10> WorkList;
8541   WorkList.push_back(SD);
8542 
8543   while (!WorkList.empty()) {
8544     ScheduleData *SD = WorkList.pop_back_val();
8545     for (ScheduleData *BundleMember = SD; BundleMember;
8546          BundleMember = BundleMember->NextInBundle) {
8547       assert(isInSchedulingRegion(BundleMember));
8548       if (BundleMember->hasValidDependencies())
8549         continue;
8550 
8551       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8552                  << "\n");
8553       BundleMember->Dependencies = 0;
8554       BundleMember->resetUnscheduledDeps();
8555 
8556       // Handle def-use chain dependencies.
8557       if (BundleMember->OpValue != BundleMember->Inst) {
8558         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8559           BundleMember->Dependencies++;
8560           ScheduleData *DestBundle = UseSD->FirstInBundle;
8561           if (!DestBundle->IsScheduled)
8562             BundleMember->incrementUnscheduledDeps(1);
8563           if (!DestBundle->hasValidDependencies())
8564             WorkList.push_back(DestBundle);
8565         }
8566       } else {
8567         for (User *U : BundleMember->Inst->users()) {
8568           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8569             BundleMember->Dependencies++;
8570             ScheduleData *DestBundle = UseSD->FirstInBundle;
8571             if (!DestBundle->IsScheduled)
8572               BundleMember->incrementUnscheduledDeps(1);
8573             if (!DestBundle->hasValidDependencies())
8574               WorkList.push_back(DestBundle);
8575           }
8576         }
8577       }
8578 
8579       auto makeControlDependent = [&](Instruction *I) {
8580         auto *DepDest = getScheduleData(I);
8581         assert(DepDest && "must be in schedule window");
8582         DepDest->ControlDependencies.push_back(BundleMember);
8583         BundleMember->Dependencies++;
8584         ScheduleData *DestBundle = DepDest->FirstInBundle;
8585         if (!DestBundle->IsScheduled)
8586           BundleMember->incrementUnscheduledDeps(1);
8587         if (!DestBundle->hasValidDependencies())
8588           WorkList.push_back(DestBundle);
8589       };
8590 
8591       // Any instruction which isn't safe to speculate at the begining of the
8592       // block is control dependend on any early exit or non-willreturn call
8593       // which proceeds it.
8594       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8595         for (Instruction *I = BundleMember->Inst->getNextNode();
8596              I != ScheduleEnd; I = I->getNextNode()) {
8597           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8598             continue;
8599 
8600           // Add the dependency
8601           makeControlDependent(I);
8602 
8603           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8604             // Everything past here must be control dependent on I.
8605             break;
8606         }
8607       }
8608 
8609       if (RegionHasStackSave) {
8610         // If we have an inalloc alloca instruction, it needs to be scheduled
8611         // after any preceeding stacksave.  We also need to prevent any alloca
8612         // from reordering above a preceeding stackrestore.
8613         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8614             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8615           for (Instruction *I = BundleMember->Inst->getNextNode();
8616                I != ScheduleEnd; I = I->getNextNode()) {
8617             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8618                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8619               // Any allocas past here must be control dependent on I, and I
8620               // must be memory dependend on BundleMember->Inst.
8621               break;
8622 
8623             if (!isa<AllocaInst>(I))
8624               continue;
8625 
8626             // Add the dependency
8627             makeControlDependent(I);
8628           }
8629         }
8630 
8631         // In addition to the cases handle just above, we need to prevent
8632         // allocas from moving below a stacksave.  The stackrestore case
8633         // is currently thought to be conservatism.
8634         if (isa<AllocaInst>(BundleMember->Inst)) {
8635           for (Instruction *I = BundleMember->Inst->getNextNode();
8636                I != ScheduleEnd; I = I->getNextNode()) {
8637             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8638                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8639               continue;
8640 
8641             // Add the dependency
8642             makeControlDependent(I);
8643             break;
8644           }
8645         }
8646       }
8647 
8648       // Handle the memory dependencies (if any).
8649       ScheduleData *DepDest = BundleMember->NextLoadStore;
8650       if (!DepDest)
8651         continue;
8652       Instruction *SrcInst = BundleMember->Inst;
8653       assert(SrcInst->mayReadOrWriteMemory() &&
8654              "NextLoadStore list for non memory effecting bundle?");
8655       MemoryLocation SrcLoc = getLocation(SrcInst);
8656       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8657       unsigned numAliased = 0;
8658       unsigned DistToSrc = 1;
8659 
8660       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8661         assert(isInSchedulingRegion(DepDest));
8662 
8663         // We have two limits to reduce the complexity:
8664         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8665         //    SLP->isAliased (which is the expensive part in this loop).
8666         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8667         //    the whole loop (even if the loop is fast, it's quadratic).
8668         //    It's important for the loop break condition (see below) to
8669         //    check this limit even between two read-only instructions.
8670         if (DistToSrc >= MaxMemDepDistance ||
8671             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8672              (numAliased >= AliasedCheckLimit ||
8673               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8674 
8675           // We increment the counter only if the locations are aliased
8676           // (instead of counting all alias checks). This gives a better
8677           // balance between reduced runtime and accurate dependencies.
8678           numAliased++;
8679 
8680           DepDest->MemoryDependencies.push_back(BundleMember);
8681           BundleMember->Dependencies++;
8682           ScheduleData *DestBundle = DepDest->FirstInBundle;
8683           if (!DestBundle->IsScheduled) {
8684             BundleMember->incrementUnscheduledDeps(1);
8685           }
8686           if (!DestBundle->hasValidDependencies()) {
8687             WorkList.push_back(DestBundle);
8688           }
8689         }
8690 
8691         // Example, explaining the loop break condition: Let's assume our
8692         // starting instruction is i0 and MaxMemDepDistance = 3.
8693         //
8694         //                      +--------v--v--v
8695         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8696         //             +--------^--^--^
8697         //
8698         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8699         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8700         // Previously we already added dependencies from i3 to i6,i7,i8
8701         // (because of MaxMemDepDistance). As we added a dependency from
8702         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8703         // and we can abort this loop at i6.
8704         if (DistToSrc >= 2 * MaxMemDepDistance)
8705           break;
8706         DistToSrc++;
8707       }
8708     }
8709     if (InsertInReadyList && SD->isReady()) {
8710       ReadyInsts.insert(SD);
8711       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8712                         << "\n");
8713     }
8714   }
8715 }
8716 
8717 void BoUpSLP::BlockScheduling::resetSchedule() {
8718   assert(ScheduleStart &&
8719          "tried to reset schedule on block which has not been scheduled");
8720   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8721     doForAllOpcodes(I, [&](ScheduleData *SD) {
8722       assert(isInSchedulingRegion(SD) &&
8723              "ScheduleData not in scheduling region");
8724       SD->IsScheduled = false;
8725       SD->resetUnscheduledDeps();
8726     });
8727   }
8728   ReadyInsts.clear();
8729 }
8730 
8731 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8732   if (!BS->ScheduleStart)
8733     return;
8734 
8735   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8736 
8737   // A key point - if we got here, pre-scheduling was able to find a valid
8738   // scheduling of the sub-graph of the scheduling window which consists
8739   // of all vector bundles and their transitive users.  As such, we do not
8740   // need to reschedule anything *outside of* that subgraph.
8741 
8742   BS->resetSchedule();
8743 
8744   // For the real scheduling we use a more sophisticated ready-list: it is
8745   // sorted by the original instruction location. This lets the final schedule
8746   // be as  close as possible to the original instruction order.
8747   // WARNING: If changing this order causes a correctness issue, that means
8748   // there is some missing dependence edge in the schedule data graph.
8749   struct ScheduleDataCompare {
8750     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8751       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8752     }
8753   };
8754   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8755 
8756   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8757   // and fill the ready-list with initial instructions.
8758   int Idx = 0;
8759   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8760        I = I->getNextNode()) {
8761     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8762       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8763       (void)SDTE;
8764       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8765               SD->isPartOfBundle() ==
8766                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8767              "scheduler and vectorizer bundle mismatch");
8768       SD->FirstInBundle->SchedulingPriority = Idx++;
8769 
8770       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8771         BS->calculateDependencies(SD, false, this);
8772     });
8773   }
8774   BS->initialFillReadyList(ReadyInsts);
8775 
8776   Instruction *LastScheduledInst = BS->ScheduleEnd;
8777 
8778   // Do the "real" scheduling.
8779   while (!ReadyInsts.empty()) {
8780     ScheduleData *picked = *ReadyInsts.begin();
8781     ReadyInsts.erase(ReadyInsts.begin());
8782 
8783     // Move the scheduled instruction(s) to their dedicated places, if not
8784     // there yet.
8785     for (ScheduleData *BundleMember = picked; BundleMember;
8786          BundleMember = BundleMember->NextInBundle) {
8787       Instruction *pickedInst = BundleMember->Inst;
8788       if (pickedInst->getNextNode() != LastScheduledInst)
8789         pickedInst->moveBefore(LastScheduledInst);
8790       LastScheduledInst = pickedInst;
8791     }
8792 
8793     BS->schedule(picked, ReadyInsts);
8794   }
8795 
8796   // Check that we didn't break any of our invariants.
8797 #ifdef EXPENSIVE_CHECKS
8798   BS->verify();
8799 #endif
8800 
8801 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8802   // Check that all schedulable entities got scheduled
8803   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8804     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8805       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8806         assert(SD->IsScheduled && "must be scheduled at this point");
8807       }
8808     });
8809   }
8810 #endif
8811 
8812   // Avoid duplicate scheduling of the block.
8813   BS->ScheduleStart = nullptr;
8814 }
8815 
8816 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8817   // If V is a store, just return the width of the stored value (or value
8818   // truncated just before storing) without traversing the expression tree.
8819   // This is the common case.
8820   if (auto *Store = dyn_cast<StoreInst>(V))
8821     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8822 
8823   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8824     return getVectorElementSize(IEI->getOperand(1));
8825 
8826   auto E = InstrElementSize.find(V);
8827   if (E != InstrElementSize.end())
8828     return E->second;
8829 
8830   // If V is not a store, we can traverse the expression tree to find loads
8831   // that feed it. The type of the loaded value may indicate a more suitable
8832   // width than V's type. We want to base the vector element size on the width
8833   // of memory operations where possible.
8834   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8835   SmallPtrSet<Instruction *, 16> Visited;
8836   if (auto *I = dyn_cast<Instruction>(V)) {
8837     Worklist.emplace_back(I, I->getParent());
8838     Visited.insert(I);
8839   }
8840 
8841   // Traverse the expression tree in bottom-up order looking for loads. If we
8842   // encounter an instruction we don't yet handle, we give up.
8843   auto Width = 0u;
8844   while (!Worklist.empty()) {
8845     Instruction *I;
8846     BasicBlock *Parent;
8847     std::tie(I, Parent) = Worklist.pop_back_val();
8848 
8849     // We should only be looking at scalar instructions here. If the current
8850     // instruction has a vector type, skip.
8851     auto *Ty = I->getType();
8852     if (isa<VectorType>(Ty))
8853       continue;
8854 
8855     // If the current instruction is a load, update MaxWidth to reflect the
8856     // width of the loaded value.
8857     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8858         isa<ExtractValueInst>(I))
8859       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8860 
8861     // Otherwise, we need to visit the operands of the instruction. We only
8862     // handle the interesting cases from buildTree here. If an operand is an
8863     // instruction we haven't yet visited and from the same basic block as the
8864     // user or the use is a PHI node, we add it to the worklist.
8865     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8866              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8867              isa<UnaryOperator>(I)) {
8868       for (Use &U : I->operands())
8869         if (auto *J = dyn_cast<Instruction>(U.get()))
8870           if (Visited.insert(J).second &&
8871               (isa<PHINode>(I) || J->getParent() == Parent))
8872             Worklist.emplace_back(J, J->getParent());
8873     } else {
8874       break;
8875     }
8876   }
8877 
8878   // If we didn't encounter a memory access in the expression tree, or if we
8879   // gave up for some reason, just return the width of V. Otherwise, return the
8880   // maximum width we found.
8881   if (!Width) {
8882     if (auto *CI = dyn_cast<CmpInst>(V))
8883       V = CI->getOperand(0);
8884     Width = DL->getTypeSizeInBits(V->getType());
8885   }
8886 
8887   for (Instruction *I : Visited)
8888     InstrElementSize[I] = Width;
8889 
8890   return Width;
8891 }
8892 
8893 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8894 // smaller type with a truncation. We collect the values that will be demoted
8895 // in ToDemote and additional roots that require investigating in Roots.
8896 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8897                                   SmallVectorImpl<Value *> &ToDemote,
8898                                   SmallVectorImpl<Value *> &Roots) {
8899   // We can always demote constants.
8900   if (isa<Constant>(V)) {
8901     ToDemote.push_back(V);
8902     return true;
8903   }
8904 
8905   // If the value is not an instruction in the expression with only one use, it
8906   // cannot be demoted.
8907   auto *I = dyn_cast<Instruction>(V);
8908   if (!I || !I->hasOneUse() || !Expr.count(I))
8909     return false;
8910 
8911   switch (I->getOpcode()) {
8912 
8913   // We can always demote truncations and extensions. Since truncations can
8914   // seed additional demotion, we save the truncated value.
8915   case Instruction::Trunc:
8916     Roots.push_back(I->getOperand(0));
8917     break;
8918   case Instruction::ZExt:
8919   case Instruction::SExt:
8920     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8921         isa<InsertElementInst>(I->getOperand(0)))
8922       return false;
8923     break;
8924 
8925   // We can demote certain binary operations if we can demote both of their
8926   // operands.
8927   case Instruction::Add:
8928   case Instruction::Sub:
8929   case Instruction::Mul:
8930   case Instruction::And:
8931   case Instruction::Or:
8932   case Instruction::Xor:
8933     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8934         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8935       return false;
8936     break;
8937 
8938   // We can demote selects if we can demote their true and false values.
8939   case Instruction::Select: {
8940     SelectInst *SI = cast<SelectInst>(I);
8941     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8942         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8943       return false;
8944     break;
8945   }
8946 
8947   // We can demote phis if we can demote all their incoming operands. Note that
8948   // we don't need to worry about cycles since we ensure single use above.
8949   case Instruction::PHI: {
8950     PHINode *PN = cast<PHINode>(I);
8951     for (Value *IncValue : PN->incoming_values())
8952       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8953         return false;
8954     break;
8955   }
8956 
8957   // Otherwise, conservatively give up.
8958   default:
8959     return false;
8960   }
8961 
8962   // Record the value that we can demote.
8963   ToDemote.push_back(V);
8964   return true;
8965 }
8966 
8967 void BoUpSLP::computeMinimumValueSizes() {
8968   // If there are no external uses, the expression tree must be rooted by a
8969   // store. We can't demote in-memory values, so there is nothing to do here.
8970   if (ExternalUses.empty())
8971     return;
8972 
8973   // We only attempt to truncate integer expressions.
8974   auto &TreeRoot = VectorizableTree[0]->Scalars;
8975   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8976   if (!TreeRootIT)
8977     return;
8978 
8979   // If the expression is not rooted by a store, these roots should have
8980   // external uses. We will rely on InstCombine to rewrite the expression in
8981   // the narrower type. However, InstCombine only rewrites single-use values.
8982   // This means that if a tree entry other than a root is used externally, it
8983   // must have multiple uses and InstCombine will not rewrite it. The code
8984   // below ensures that only the roots are used externally.
8985   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8986   for (auto &EU : ExternalUses)
8987     if (!Expr.erase(EU.Scalar))
8988       return;
8989   if (!Expr.empty())
8990     return;
8991 
8992   // Collect the scalar values of the vectorizable expression. We will use this
8993   // context to determine which values can be demoted. If we see a truncation,
8994   // we mark it as seeding another demotion.
8995   for (auto &EntryPtr : VectorizableTree)
8996     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8997 
8998   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8999   // have a single external user that is not in the vectorizable tree.
9000   for (auto *Root : TreeRoot)
9001     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9002       return;
9003 
9004   // Conservatively determine if we can actually truncate the roots of the
9005   // expression. Collect the values that can be demoted in ToDemote and
9006   // additional roots that require investigating in Roots.
9007   SmallVector<Value *, 32> ToDemote;
9008   SmallVector<Value *, 4> Roots;
9009   for (auto *Root : TreeRoot)
9010     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9011       return;
9012 
9013   // The maximum bit width required to represent all the values that can be
9014   // demoted without loss of precision. It would be safe to truncate the roots
9015   // of the expression to this width.
9016   auto MaxBitWidth = 8u;
9017 
9018   // We first check if all the bits of the roots are demanded. If they're not,
9019   // we can truncate the roots to this narrower type.
9020   for (auto *Root : TreeRoot) {
9021     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9022     MaxBitWidth = std::max<unsigned>(
9023         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9024   }
9025 
9026   // True if the roots can be zero-extended back to their original type, rather
9027   // than sign-extended. We know that if the leading bits are not demanded, we
9028   // can safely zero-extend. So we initialize IsKnownPositive to True.
9029   bool IsKnownPositive = true;
9030 
9031   // If all the bits of the roots are demanded, we can try a little harder to
9032   // compute a narrower type. This can happen, for example, if the roots are
9033   // getelementptr indices. InstCombine promotes these indices to the pointer
9034   // width. Thus, all their bits are technically demanded even though the
9035   // address computation might be vectorized in a smaller type.
9036   //
9037   // We start by looking at each entry that can be demoted. We compute the
9038   // maximum bit width required to store the scalar by using ValueTracking to
9039   // compute the number of high-order bits we can truncate.
9040   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9041       llvm::all_of(TreeRoot, [](Value *R) {
9042         assert(R->hasOneUse() && "Root should have only one use!");
9043         return isa<GetElementPtrInst>(R->user_back());
9044       })) {
9045     MaxBitWidth = 8u;
9046 
9047     // Determine if the sign bit of all the roots is known to be zero. If not,
9048     // IsKnownPositive is set to False.
9049     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9050       KnownBits Known = computeKnownBits(R, *DL);
9051       return Known.isNonNegative();
9052     });
9053 
9054     // Determine the maximum number of bits required to store the scalar
9055     // values.
9056     for (auto *Scalar : ToDemote) {
9057       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9058       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9059       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9060     }
9061 
9062     // If we can't prove that the sign bit is zero, we must add one to the
9063     // maximum bit width to account for the unknown sign bit. This preserves
9064     // the existing sign bit so we can safely sign-extend the root back to the
9065     // original type. Otherwise, if we know the sign bit is zero, we will
9066     // zero-extend the root instead.
9067     //
9068     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9069     //        one to the maximum bit width will yield a larger-than-necessary
9070     //        type. In general, we need to add an extra bit only if we can't
9071     //        prove that the upper bit of the original type is equal to the
9072     //        upper bit of the proposed smaller type. If these two bits are the
9073     //        same (either zero or one) we know that sign-extending from the
9074     //        smaller type will result in the same value. Here, since we can't
9075     //        yet prove this, we are just making the proposed smaller type
9076     //        larger to ensure correctness.
9077     if (!IsKnownPositive)
9078       ++MaxBitWidth;
9079   }
9080 
9081   // Round MaxBitWidth up to the next power-of-two.
9082   if (!isPowerOf2_64(MaxBitWidth))
9083     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9084 
9085   // If the maximum bit width we compute is less than the with of the roots'
9086   // type, we can proceed with the narrowing. Otherwise, do nothing.
9087   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9088     return;
9089 
9090   // If we can truncate the root, we must collect additional values that might
9091   // be demoted as a result. That is, those seeded by truncations we will
9092   // modify.
9093   while (!Roots.empty())
9094     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9095 
9096   // Finally, map the values we can demote to the maximum bit with we computed.
9097   for (auto *Scalar : ToDemote)
9098     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9099 }
9100 
9101 namespace {
9102 
9103 /// The SLPVectorizer Pass.
9104 struct SLPVectorizer : public FunctionPass {
9105   SLPVectorizerPass Impl;
9106 
9107   /// Pass identification, replacement for typeid
9108   static char ID;
9109 
9110   explicit SLPVectorizer() : FunctionPass(ID) {
9111     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9112   }
9113 
9114   bool doInitialization(Module &M) override { return false; }
9115 
9116   bool runOnFunction(Function &F) override {
9117     if (skipFunction(F))
9118       return false;
9119 
9120     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9121     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9122     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9123     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9124     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9125     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9126     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9127     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9128     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9129     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9130 
9131     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9132   }
9133 
9134   void getAnalysisUsage(AnalysisUsage &AU) const override {
9135     FunctionPass::getAnalysisUsage(AU);
9136     AU.addRequired<AssumptionCacheTracker>();
9137     AU.addRequired<ScalarEvolutionWrapperPass>();
9138     AU.addRequired<AAResultsWrapperPass>();
9139     AU.addRequired<TargetTransformInfoWrapperPass>();
9140     AU.addRequired<LoopInfoWrapperPass>();
9141     AU.addRequired<DominatorTreeWrapperPass>();
9142     AU.addRequired<DemandedBitsWrapperPass>();
9143     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9144     AU.addRequired<InjectTLIMappingsLegacy>();
9145     AU.addPreserved<LoopInfoWrapperPass>();
9146     AU.addPreserved<DominatorTreeWrapperPass>();
9147     AU.addPreserved<AAResultsWrapperPass>();
9148     AU.addPreserved<GlobalsAAWrapperPass>();
9149     AU.setPreservesCFG();
9150   }
9151 };
9152 
9153 } // end anonymous namespace
9154 
9155 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9156   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9157   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9158   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9159   auto *AA = &AM.getResult<AAManager>(F);
9160   auto *LI = &AM.getResult<LoopAnalysis>(F);
9161   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9162   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9163   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9164   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9165 
9166   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9167   if (!Changed)
9168     return PreservedAnalyses::all();
9169 
9170   PreservedAnalyses PA;
9171   PA.preserveSet<CFGAnalyses>();
9172   return PA;
9173 }
9174 
9175 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9176                                 TargetTransformInfo *TTI_,
9177                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9178                                 LoopInfo *LI_, DominatorTree *DT_,
9179                                 AssumptionCache *AC_, DemandedBits *DB_,
9180                                 OptimizationRemarkEmitter *ORE_) {
9181   if (!RunSLPVectorization)
9182     return false;
9183   SE = SE_;
9184   TTI = TTI_;
9185   TLI = TLI_;
9186   AA = AA_;
9187   LI = LI_;
9188   DT = DT_;
9189   AC = AC_;
9190   DB = DB_;
9191   DL = &F.getParent()->getDataLayout();
9192 
9193   Stores.clear();
9194   GEPs.clear();
9195   bool Changed = false;
9196 
9197   // If the target claims to have no vector registers don't attempt
9198   // vectorization.
9199   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9200     LLVM_DEBUG(
9201         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9202     return false;
9203   }
9204 
9205   // Don't vectorize when the attribute NoImplicitFloat is used.
9206   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9207     return false;
9208 
9209   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9210 
9211   // Use the bottom up slp vectorizer to construct chains that start with
9212   // store instructions.
9213   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9214 
9215   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9216   // delete instructions.
9217 
9218   // Update DFS numbers now so that we can use them for ordering.
9219   DT->updateDFSNumbers();
9220 
9221   // Scan the blocks in the function in post order.
9222   for (auto BB : post_order(&F.getEntryBlock())) {
9223     // Start new block - clear the list of reduction roots.
9224     R.clearReductionData();
9225     collectSeedInstructions(BB);
9226 
9227     // Vectorize trees that end at stores.
9228     if (!Stores.empty()) {
9229       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9230                         << " underlying objects.\n");
9231       Changed |= vectorizeStoreChains(R);
9232     }
9233 
9234     // Vectorize trees that end at reductions.
9235     Changed |= vectorizeChainsInBlock(BB, R);
9236 
9237     // Vectorize the index computations of getelementptr instructions. This
9238     // is primarily intended to catch gather-like idioms ending at
9239     // non-consecutive loads.
9240     if (!GEPs.empty()) {
9241       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9242                         << " underlying objects.\n");
9243       Changed |= vectorizeGEPIndices(BB, R);
9244     }
9245   }
9246 
9247   if (Changed) {
9248     R.optimizeGatherSequence();
9249     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9250   }
9251   return Changed;
9252 }
9253 
9254 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9255                                             unsigned Idx, unsigned MinVF) {
9256   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9257                     << "\n");
9258   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9259   unsigned VF = Chain.size();
9260 
9261   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9262     return false;
9263 
9264   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9265                     << "\n");
9266 
9267   R.buildTree(Chain);
9268   if (R.isTreeTinyAndNotFullyVectorizable())
9269     return false;
9270   if (R.isLoadCombineCandidate())
9271     return false;
9272   R.reorderTopToBottom();
9273   R.reorderBottomToTop();
9274   R.buildExternalUses();
9275 
9276   R.computeMinimumValueSizes();
9277 
9278   InstructionCost Cost = R.getTreeCost();
9279 
9280   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9281   if (Cost < -SLPCostThreshold) {
9282     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9283 
9284     using namespace ore;
9285 
9286     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9287                                         cast<StoreInst>(Chain[0]))
9288                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9289                      << " and with tree size "
9290                      << NV("TreeSize", R.getTreeSize()));
9291 
9292     R.vectorizeTree();
9293     return true;
9294   }
9295 
9296   return false;
9297 }
9298 
9299 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9300                                         BoUpSLP &R) {
9301   // We may run into multiple chains that merge into a single chain. We mark the
9302   // stores that we vectorized so that we don't visit the same store twice.
9303   BoUpSLP::ValueSet VectorizedStores;
9304   bool Changed = false;
9305 
9306   int E = Stores.size();
9307   SmallBitVector Tails(E, false);
9308   int MaxIter = MaxStoreLookup.getValue();
9309   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9310       E, std::make_pair(E, INT_MAX));
9311   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9312   int IterCnt;
9313   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9314                                   &CheckedPairs,
9315                                   &ConsecutiveChain](int K, int Idx) {
9316     if (IterCnt >= MaxIter)
9317       return true;
9318     if (CheckedPairs[Idx].test(K))
9319       return ConsecutiveChain[K].second == 1 &&
9320              ConsecutiveChain[K].first == Idx;
9321     ++IterCnt;
9322     CheckedPairs[Idx].set(K);
9323     CheckedPairs[K].set(Idx);
9324     Optional<int> Diff = getPointersDiff(
9325         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9326         Stores[Idx]->getValueOperand()->getType(),
9327         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9328     if (!Diff || *Diff == 0)
9329       return false;
9330     int Val = *Diff;
9331     if (Val < 0) {
9332       if (ConsecutiveChain[Idx].second > -Val) {
9333         Tails.set(K);
9334         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9335       }
9336       return false;
9337     }
9338     if (ConsecutiveChain[K].second <= Val)
9339       return false;
9340 
9341     Tails.set(Idx);
9342     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9343     return Val == 1;
9344   };
9345   // Do a quadratic search on all of the given stores in reverse order and find
9346   // all of the pairs of stores that follow each other.
9347   for (int Idx = E - 1; Idx >= 0; --Idx) {
9348     // If a store has multiple consecutive store candidates, search according
9349     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9350     // This is because usually pairing with immediate succeeding or preceding
9351     // candidate create the best chance to find slp vectorization opportunity.
9352     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9353     IterCnt = 0;
9354     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9355       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9356           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9357         break;
9358   }
9359 
9360   // Tracks if we tried to vectorize stores starting from the given tail
9361   // already.
9362   SmallBitVector TriedTails(E, false);
9363   // For stores that start but don't end a link in the chain:
9364   for (int Cnt = E; Cnt > 0; --Cnt) {
9365     int I = Cnt - 1;
9366     if (ConsecutiveChain[I].first == E || Tails.test(I))
9367       continue;
9368     // We found a store instr that starts a chain. Now follow the chain and try
9369     // to vectorize it.
9370     BoUpSLP::ValueList Operands;
9371     // Collect the chain into a list.
9372     while (I != E && !VectorizedStores.count(Stores[I])) {
9373       Operands.push_back(Stores[I]);
9374       Tails.set(I);
9375       if (ConsecutiveChain[I].second != 1) {
9376         // Mark the new end in the chain and go back, if required. It might be
9377         // required if the original stores come in reversed order, for example.
9378         if (ConsecutiveChain[I].first != E &&
9379             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9380             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9381           TriedTails.set(I);
9382           Tails.reset(ConsecutiveChain[I].first);
9383           if (Cnt < ConsecutiveChain[I].first + 2)
9384             Cnt = ConsecutiveChain[I].first + 2;
9385         }
9386         break;
9387       }
9388       // Move to the next value in the chain.
9389       I = ConsecutiveChain[I].first;
9390     }
9391     assert(!Operands.empty() && "Expected non-empty list of stores.");
9392 
9393     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9394     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9395     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9396 
9397     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9398                               MaxElts);
9399     auto *Store = cast<StoreInst>(Operands[0]);
9400     Type *StoreTy = Store->getValueOperand()->getType();
9401     Type *ValueTy = StoreTy;
9402     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9403       ValueTy = Trunc->getSrcTy();
9404     unsigned MinVF = TTI->getStoreMinimumVF(
9405         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9406 
9407     // FIXME: Is division-by-2 the correct step? Should we assert that the
9408     // register size is a power-of-2?
9409     unsigned StartIdx = 0;
9410     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9411       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9412         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9413         if (!VectorizedStores.count(Slice.front()) &&
9414             !VectorizedStores.count(Slice.back()) &&
9415             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9416           // Mark the vectorized stores so that we don't vectorize them again.
9417           VectorizedStores.insert(Slice.begin(), Slice.end());
9418           Changed = true;
9419           // If we vectorized initial block, no need to try to vectorize it
9420           // again.
9421           if (Cnt == StartIdx)
9422             StartIdx += Size;
9423           Cnt += Size;
9424           continue;
9425         }
9426         ++Cnt;
9427       }
9428       // Check if the whole array was vectorized already - exit.
9429       if (StartIdx >= Operands.size())
9430         break;
9431     }
9432   }
9433 
9434   return Changed;
9435 }
9436 
9437 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9438   // Initialize the collections. We will make a single pass over the block.
9439   Stores.clear();
9440   GEPs.clear();
9441 
9442   // Visit the store and getelementptr instructions in BB and organize them in
9443   // Stores and GEPs according to the underlying objects of their pointer
9444   // operands.
9445   for (Instruction &I : *BB) {
9446     // Ignore store instructions that are volatile or have a pointer operand
9447     // that doesn't point to a scalar type.
9448     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9449       if (!SI->isSimple())
9450         continue;
9451       if (!isValidElementType(SI->getValueOperand()->getType()))
9452         continue;
9453       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9454     }
9455 
9456     // Ignore getelementptr instructions that have more than one index, a
9457     // constant index, or a pointer operand that doesn't point to a scalar
9458     // type.
9459     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9460       auto Idx = GEP->idx_begin()->get();
9461       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9462         continue;
9463       if (!isValidElementType(Idx->getType()))
9464         continue;
9465       if (GEP->getType()->isVectorTy())
9466         continue;
9467       GEPs[GEP->getPointerOperand()].push_back(GEP);
9468     }
9469   }
9470 }
9471 
9472 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9473   if (!A || !B)
9474     return false;
9475   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9476     return false;
9477   Value *VL[] = {A, B};
9478   return tryToVectorizeList(VL, R);
9479 }
9480 
9481 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9482                                            bool LimitForRegisterSize) {
9483   if (VL.size() < 2)
9484     return false;
9485 
9486   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9487                     << VL.size() << ".\n");
9488 
9489   // Check that all of the parts are instructions of the same type,
9490   // we permit an alternate opcode via InstructionsState.
9491   InstructionsState S = getSameOpcode(VL);
9492   if (!S.getOpcode())
9493     return false;
9494 
9495   Instruction *I0 = cast<Instruction>(S.OpValue);
9496   // Make sure invalid types (including vector type) are rejected before
9497   // determining vectorization factor for scalar instructions.
9498   for (Value *V : VL) {
9499     Type *Ty = V->getType();
9500     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9501       // NOTE: the following will give user internal llvm type name, which may
9502       // not be useful.
9503       R.getORE()->emit([&]() {
9504         std::string type_str;
9505         llvm::raw_string_ostream rso(type_str);
9506         Ty->print(rso);
9507         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9508                << "Cannot SLP vectorize list: type "
9509                << rso.str() + " is unsupported by vectorizer";
9510       });
9511       return false;
9512     }
9513   }
9514 
9515   unsigned Sz = R.getVectorElementSize(I0);
9516   unsigned MinVF = R.getMinVF(Sz);
9517   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9518   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9519   if (MaxVF < 2) {
9520     R.getORE()->emit([&]() {
9521       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9522              << "Cannot SLP vectorize list: vectorization factor "
9523              << "less than 2 is not supported";
9524     });
9525     return false;
9526   }
9527 
9528   bool Changed = false;
9529   bool CandidateFound = false;
9530   InstructionCost MinCost = SLPCostThreshold.getValue();
9531   Type *ScalarTy = VL[0]->getType();
9532   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9533     ScalarTy = IE->getOperand(1)->getType();
9534 
9535   unsigned NextInst = 0, MaxInst = VL.size();
9536   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9537     // No actual vectorization should happen, if number of parts is the same as
9538     // provided vectorization factor (i.e. the scalar type is used for vector
9539     // code during codegen).
9540     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9541     if (TTI->getNumberOfParts(VecTy) == VF)
9542       continue;
9543     for (unsigned I = NextInst; I < MaxInst; ++I) {
9544       unsigned OpsWidth = 0;
9545 
9546       if (I + VF > MaxInst)
9547         OpsWidth = MaxInst - I;
9548       else
9549         OpsWidth = VF;
9550 
9551       if (!isPowerOf2_32(OpsWidth))
9552         continue;
9553 
9554       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9555           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9556         break;
9557 
9558       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9559       // Check that a previous iteration of this loop did not delete the Value.
9560       if (llvm::any_of(Ops, [&R](Value *V) {
9561             auto *I = dyn_cast<Instruction>(V);
9562             return I && R.isDeleted(I);
9563           }))
9564         continue;
9565 
9566       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9567                         << "\n");
9568 
9569       R.buildTree(Ops);
9570       if (R.isTreeTinyAndNotFullyVectorizable())
9571         continue;
9572       R.reorderTopToBottom();
9573       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9574       R.buildExternalUses();
9575 
9576       R.computeMinimumValueSizes();
9577       InstructionCost Cost = R.getTreeCost();
9578       CandidateFound = true;
9579       MinCost = std::min(MinCost, Cost);
9580 
9581       if (Cost < -SLPCostThreshold) {
9582         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9583         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9584                                                     cast<Instruction>(Ops[0]))
9585                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9586                                  << " and with tree size "
9587                                  << ore::NV("TreeSize", R.getTreeSize()));
9588 
9589         R.vectorizeTree();
9590         // Move to the next bundle.
9591         I += VF - 1;
9592         NextInst = I + 1;
9593         Changed = true;
9594       }
9595     }
9596   }
9597 
9598   if (!Changed && CandidateFound) {
9599     R.getORE()->emit([&]() {
9600       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9601              << "List vectorization was possible but not beneficial with cost "
9602              << ore::NV("Cost", MinCost) << " >= "
9603              << ore::NV("Treshold", -SLPCostThreshold);
9604     });
9605   } else if (!Changed) {
9606     R.getORE()->emit([&]() {
9607       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9608              << "Cannot SLP vectorize list: vectorization was impossible"
9609              << " with available vectorization factors";
9610     });
9611   }
9612   return Changed;
9613 }
9614 
9615 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9616   if (!I)
9617     return false;
9618 
9619   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9620       isa<VectorType>(I->getType()))
9621     return false;
9622 
9623   Value *P = I->getParent();
9624 
9625   // Vectorize in current basic block only.
9626   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9627   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9628   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9629     return false;
9630 
9631   // First collect all possible candidates
9632   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9633   Candidates.emplace_back(Op0, Op1);
9634 
9635   auto *A = dyn_cast<BinaryOperator>(Op0);
9636   auto *B = dyn_cast<BinaryOperator>(Op1);
9637   // Try to skip B.
9638   if (A && B && B->hasOneUse()) {
9639     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9640     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9641     if (B0 && B0->getParent() == P)
9642       Candidates.emplace_back(A, B0);
9643     if (B1 && B1->getParent() == P)
9644       Candidates.emplace_back(A, B1);
9645   }
9646   // Try to skip A.
9647   if (B && A && A->hasOneUse()) {
9648     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9649     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9650     if (A0 && A0->getParent() == P)
9651       Candidates.emplace_back(A0, B);
9652     if (A1 && A1->getParent() == P)
9653       Candidates.emplace_back(A1, B);
9654   }
9655 
9656   if (Candidates.size() == 1)
9657     return tryToVectorizePair(Op0, Op1, R);
9658 
9659   // We have multiple options. Try to pick the single best.
9660   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9661   if (!BestCandidate)
9662     return false;
9663   return tryToVectorizePair(Candidates[*BestCandidate].first,
9664                             Candidates[*BestCandidate].second, R);
9665 }
9666 
9667 namespace {
9668 
9669 /// Model horizontal reductions.
9670 ///
9671 /// A horizontal reduction is a tree of reduction instructions that has values
9672 /// that can be put into a vector as its leaves. For example:
9673 ///
9674 /// mul mul mul mul
9675 ///  \  /    \  /
9676 ///   +       +
9677 ///    \     /
9678 ///       +
9679 /// This tree has "mul" as its leaf values and "+" as its reduction
9680 /// instructions. A reduction can feed into a store or a binary operation
9681 /// feeding a phi.
9682 ///    ...
9683 ///    \  /
9684 ///     +
9685 ///     |
9686 ///  phi +=
9687 ///
9688 ///  Or:
9689 ///    ...
9690 ///    \  /
9691 ///     +
9692 ///     |
9693 ///   *p =
9694 ///
9695 class HorizontalReduction {
9696   using ReductionOpsType = SmallVector<Value *, 16>;
9697   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9698   ReductionOpsListType ReductionOps;
9699   /// List of possibly reduced values.
9700   SmallVector<SmallVector<Value *>> ReducedVals;
9701   /// Maps reduced value to the corresponding reduction operation.
9702   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9703   // Use map vector to make stable output.
9704   MapVector<Instruction *, Value *> ExtraArgs;
9705   WeakTrackingVH ReductionRoot;
9706   /// The type of reduction operation.
9707   RecurKind RdxKind;
9708 
9709   static bool isCmpSelMinMax(Instruction *I) {
9710     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9711            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9712   }
9713 
9714   // And/or are potentially poison-safe logical patterns like:
9715   // select x, y, false
9716   // select x, true, y
9717   static bool isBoolLogicOp(Instruction *I) {
9718     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9719            match(I, m_LogicalOr(m_Value(), m_Value()));
9720   }
9721 
9722   /// Checks if instruction is associative and can be vectorized.
9723   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9724     if (Kind == RecurKind::None)
9725       return false;
9726 
9727     // Integer ops that map to select instructions or intrinsics are fine.
9728     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9729         isBoolLogicOp(I))
9730       return true;
9731 
9732     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9733       // FP min/max are associative except for NaN and -0.0. We do not
9734       // have to rule out -0.0 here because the intrinsic semantics do not
9735       // specify a fixed result for it.
9736       return I->getFastMathFlags().noNaNs();
9737     }
9738 
9739     return I->isAssociative();
9740   }
9741 
9742   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9743     // Poison-safe 'or' takes the form: select X, true, Y
9744     // To make that work with the normal operand processing, we skip the
9745     // true value operand.
9746     // TODO: Change the code and data structures to handle this without a hack.
9747     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9748       return I->getOperand(2);
9749     return I->getOperand(Index);
9750   }
9751 
9752   /// Creates reduction operation with the current opcode.
9753   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9754                          Value *RHS, const Twine &Name, bool UseSelect) {
9755     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9756     switch (Kind) {
9757     case RecurKind::Or:
9758       if (UseSelect &&
9759           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9760         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9761       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9762                                  Name);
9763     case RecurKind::And:
9764       if (UseSelect &&
9765           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9766         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9767       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9768                                  Name);
9769     case RecurKind::Add:
9770     case RecurKind::Mul:
9771     case RecurKind::Xor:
9772     case RecurKind::FAdd:
9773     case RecurKind::FMul:
9774       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9775                                  Name);
9776     case RecurKind::FMax:
9777       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9778     case RecurKind::FMin:
9779       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9780     case RecurKind::SMax:
9781       if (UseSelect) {
9782         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9783         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9784       }
9785       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9786     case RecurKind::SMin:
9787       if (UseSelect) {
9788         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9789         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9790       }
9791       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9792     case RecurKind::UMax:
9793       if (UseSelect) {
9794         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9795         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9796       }
9797       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9798     case RecurKind::UMin:
9799       if (UseSelect) {
9800         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9801         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9802       }
9803       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9804     default:
9805       llvm_unreachable("Unknown reduction operation.");
9806     }
9807   }
9808 
9809   /// Creates reduction operation with the current opcode with the IR flags
9810   /// from \p ReductionOps.
9811   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9812                          Value *RHS, const Twine &Name,
9813                          const ReductionOpsListType &ReductionOps) {
9814     bool UseSelect = ReductionOps.size() == 2 ||
9815                      // Logical or/and.
9816                      (ReductionOps.size() == 1 &&
9817                       isa<SelectInst>(ReductionOps.front().front()));
9818     assert((!UseSelect || ReductionOps.size() != 2 ||
9819             isa<SelectInst>(ReductionOps[1][0])) &&
9820            "Expected cmp + select pairs for reduction");
9821     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9822     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9823       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9824         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9825         propagateIRFlags(Op, ReductionOps[1]);
9826         return Op;
9827       }
9828     }
9829     propagateIRFlags(Op, ReductionOps[0]);
9830     return Op;
9831   }
9832 
9833   /// Creates reduction operation with the current opcode with the IR flags
9834   /// from \p I.
9835   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9836                          Value *RHS, const Twine &Name, Value *I) {
9837     auto *SelI = dyn_cast<SelectInst>(I);
9838     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9839     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9840       if (auto *Sel = dyn_cast<SelectInst>(Op))
9841         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9842     }
9843     propagateIRFlags(Op, I);
9844     return Op;
9845   }
9846 
9847   static RecurKind getRdxKind(Value *V) {
9848     auto *I = dyn_cast<Instruction>(V);
9849     if (!I)
9850       return RecurKind::None;
9851     if (match(I, m_Add(m_Value(), m_Value())))
9852       return RecurKind::Add;
9853     if (match(I, m_Mul(m_Value(), m_Value())))
9854       return RecurKind::Mul;
9855     if (match(I, m_And(m_Value(), m_Value())) ||
9856         match(I, m_LogicalAnd(m_Value(), m_Value())))
9857       return RecurKind::And;
9858     if (match(I, m_Or(m_Value(), m_Value())) ||
9859         match(I, m_LogicalOr(m_Value(), m_Value())))
9860       return RecurKind::Or;
9861     if (match(I, m_Xor(m_Value(), m_Value())))
9862       return RecurKind::Xor;
9863     if (match(I, m_FAdd(m_Value(), m_Value())))
9864       return RecurKind::FAdd;
9865     if (match(I, m_FMul(m_Value(), m_Value())))
9866       return RecurKind::FMul;
9867 
9868     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9869       return RecurKind::FMax;
9870     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9871       return RecurKind::FMin;
9872 
9873     // This matches either cmp+select or intrinsics. SLP is expected to handle
9874     // either form.
9875     // TODO: If we are canonicalizing to intrinsics, we can remove several
9876     //       special-case paths that deal with selects.
9877     if (match(I, m_SMax(m_Value(), m_Value())))
9878       return RecurKind::SMax;
9879     if (match(I, m_SMin(m_Value(), m_Value())))
9880       return RecurKind::SMin;
9881     if (match(I, m_UMax(m_Value(), m_Value())))
9882       return RecurKind::UMax;
9883     if (match(I, m_UMin(m_Value(), m_Value())))
9884       return RecurKind::UMin;
9885 
9886     if (auto *Select = dyn_cast<SelectInst>(I)) {
9887       // Try harder: look for min/max pattern based on instructions producing
9888       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9889       // During the intermediate stages of SLP, it's very common to have
9890       // pattern like this (since optimizeGatherSequence is run only once
9891       // at the end):
9892       // %1 = extractelement <2 x i32> %a, i32 0
9893       // %2 = extractelement <2 x i32> %a, i32 1
9894       // %cond = icmp sgt i32 %1, %2
9895       // %3 = extractelement <2 x i32> %a, i32 0
9896       // %4 = extractelement <2 x i32> %a, i32 1
9897       // %select = select i1 %cond, i32 %3, i32 %4
9898       CmpInst::Predicate Pred;
9899       Instruction *L1;
9900       Instruction *L2;
9901 
9902       Value *LHS = Select->getTrueValue();
9903       Value *RHS = Select->getFalseValue();
9904       Value *Cond = Select->getCondition();
9905 
9906       // TODO: Support inverse predicates.
9907       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9908         if (!isa<ExtractElementInst>(RHS) ||
9909             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9910           return RecurKind::None;
9911       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9912         if (!isa<ExtractElementInst>(LHS) ||
9913             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9914           return RecurKind::None;
9915       } else {
9916         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9917           return RecurKind::None;
9918         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9919             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9920             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9921           return RecurKind::None;
9922       }
9923 
9924       switch (Pred) {
9925       default:
9926         return RecurKind::None;
9927       case CmpInst::ICMP_SGT:
9928       case CmpInst::ICMP_SGE:
9929         return RecurKind::SMax;
9930       case CmpInst::ICMP_SLT:
9931       case CmpInst::ICMP_SLE:
9932         return RecurKind::SMin;
9933       case CmpInst::ICMP_UGT:
9934       case CmpInst::ICMP_UGE:
9935         return RecurKind::UMax;
9936       case CmpInst::ICMP_ULT:
9937       case CmpInst::ICMP_ULE:
9938         return RecurKind::UMin;
9939       }
9940     }
9941     return RecurKind::None;
9942   }
9943 
9944   /// Get the index of the first operand.
9945   static unsigned getFirstOperandIndex(Instruction *I) {
9946     return isCmpSelMinMax(I) ? 1 : 0;
9947   }
9948 
9949   /// Total number of operands in the reduction operation.
9950   static unsigned getNumberOfOperands(Instruction *I) {
9951     return isCmpSelMinMax(I) ? 3 : 2;
9952   }
9953 
9954   /// Checks if the instruction is in basic block \p BB.
9955   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9956   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9957     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9958       auto *Sel = cast<SelectInst>(I);
9959       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9960       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9961     }
9962     return I->getParent() == BB;
9963   }
9964 
9965   /// Expected number of uses for reduction operations/reduced values.
9966   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9967     if (IsCmpSelMinMax) {
9968       // SelectInst must be used twice while the condition op must have single
9969       // use only.
9970       if (auto *Sel = dyn_cast<SelectInst>(I))
9971         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9972       return I->hasNUses(2);
9973     }
9974 
9975     // Arithmetic reduction operation must be used once only.
9976     return I->hasOneUse();
9977   }
9978 
9979   /// Initializes the list of reduction operations.
9980   void initReductionOps(Instruction *I) {
9981     if (isCmpSelMinMax(I))
9982       ReductionOps.assign(2, ReductionOpsType());
9983     else
9984       ReductionOps.assign(1, ReductionOpsType());
9985   }
9986 
9987   /// Add all reduction operations for the reduction instruction \p I.
9988   void addReductionOps(Instruction *I) {
9989     if (isCmpSelMinMax(I)) {
9990       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9991       ReductionOps[1].emplace_back(I);
9992     } else {
9993       ReductionOps[0].emplace_back(I);
9994     }
9995   }
9996 
9997   static Value *getLHS(RecurKind Kind, Instruction *I) {
9998     if (Kind == RecurKind::None)
9999       return nullptr;
10000     return I->getOperand(getFirstOperandIndex(I));
10001   }
10002   static Value *getRHS(RecurKind Kind, Instruction *I) {
10003     if (Kind == RecurKind::None)
10004       return nullptr;
10005     return I->getOperand(getFirstOperandIndex(I) + 1);
10006   }
10007 
10008 public:
10009   HorizontalReduction() = default;
10010 
10011   /// Try to find a reduction tree.
10012   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10013                                  ScalarEvolution &SE, const DataLayout &DL,
10014                                  const TargetLibraryInfo &TLI) {
10015     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10016            "Phi needs to use the binary operator");
10017     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10018             isa<IntrinsicInst>(Inst)) &&
10019            "Expected binop, select, or intrinsic for reduction matching");
10020     RdxKind = getRdxKind(Inst);
10021 
10022     // We could have a initial reductions that is not an add.
10023     //  r *= v1 + v2 + v3 + v4
10024     // In such a case start looking for a tree rooted in the first '+'.
10025     if (Phi) {
10026       if (getLHS(RdxKind, Inst) == Phi) {
10027         Phi = nullptr;
10028         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10029         if (!Inst)
10030           return false;
10031         RdxKind = getRdxKind(Inst);
10032       } else if (getRHS(RdxKind, Inst) == Phi) {
10033         Phi = nullptr;
10034         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10035         if (!Inst)
10036           return false;
10037         RdxKind = getRdxKind(Inst);
10038       }
10039     }
10040 
10041     if (!isVectorizable(RdxKind, Inst))
10042       return false;
10043 
10044     // Analyze "regular" integer/FP types for reductions - no target-specific
10045     // types or pointers.
10046     Type *Ty = Inst->getType();
10047     if (!isValidElementType(Ty) || Ty->isPointerTy())
10048       return false;
10049 
10050     // Though the ultimate reduction may have multiple uses, its condition must
10051     // have only single use.
10052     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10053       if (!Sel->getCondition()->hasOneUse())
10054         return false;
10055 
10056     ReductionRoot = Inst;
10057 
10058     // Iterate through all the operands of the possible reduction tree and
10059     // gather all the reduced values, sorting them by their value id.
10060     BasicBlock *BB = Inst->getParent();
10061     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10062     SmallVector<Instruction *> Worklist(1, Inst);
10063     // Checks if the operands of the \p TreeN instruction are also reduction
10064     // operations or should be treated as reduced values or an extra argument,
10065     // which is not part of the reduction.
10066     auto &&CheckOperands = [this, IsCmpSelMinMax,
10067                             BB](Instruction *TreeN,
10068                                 SmallVectorImpl<Value *> &ExtraArgs,
10069                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10070                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10071       for (int I = getFirstOperandIndex(TreeN),
10072                End = getNumberOfOperands(TreeN);
10073            I < End; ++I) {
10074         Value *EdgeVal = getRdxOperand(TreeN, I);
10075         ReducedValsToOps[EdgeVal].push_back(TreeN);
10076         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10077         // Edge has wrong parent - mark as an extra argument.
10078         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10079             !hasSameParent(EdgeInst, BB)) {
10080           ExtraArgs.push_back(EdgeVal);
10081           continue;
10082         }
10083         // If the edge is not an instruction, or it is different from the main
10084         // reduction opcode or has too many uses - possible reduced value.
10085         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10086             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10087             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10088           PossibleReducedVals.push_back(EdgeVal);
10089           continue;
10090         }
10091         ReductionOps.push_back(EdgeInst);
10092       }
10093     };
10094     // Try to regroup reduced values so that it gets more profitable to try to
10095     // reduce them. Values are grouped by their value ids, instructions - by
10096     // instruction op id and/or alternate op id, plus do extra analysis for
10097     // loads (grouping them by the distabce between pointers) and cmp
10098     // instructions (grouping them by the predicate).
10099     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10100         PossibleReducedVals;
10101     initReductionOps(Inst);
10102     while (!Worklist.empty()) {
10103       Instruction *TreeN = Worklist.pop_back_val();
10104       SmallVector<Value *> Args;
10105       SmallVector<Value *> PossibleRedVals;
10106       SmallVector<Instruction *> PossibleReductionOps;
10107       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10108       // If too many extra args - mark the instruction itself as a reduction
10109       // value, not a reduction operation.
10110       if (Args.size() < 2) {
10111         addReductionOps(TreeN);
10112         // Add extra args.
10113         if (!Args.empty()) {
10114           assert(Args.size() == 1 && "Expected only single argument.");
10115           ExtraArgs[TreeN] = Args.front();
10116         }
10117         // Add reduction values. The values are sorted for better vectorization
10118         // results.
10119         for (Value *V : PossibleRedVals) {
10120           size_t Key, Idx;
10121           std::tie(Key, Idx) = generateKeySubkey(
10122               V, &TLI,
10123               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10124                 for (const auto &LoadData : PossibleReducedVals[Key]) {
10125                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10126                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10127                                       LI->getType(), LI->getPointerOperand(),
10128                                       DL, SE, /*StrictCheck=*/true))
10129                     return hash_value(RLI->getPointerOperand());
10130                 }
10131                 return hash_value(LI->getPointerOperand());
10132               },
10133               /*AllowAlternate=*/false);
10134           ++PossibleReducedVals[Key][Idx]
10135                 .insert(std::make_pair(V, 0))
10136                 .first->second;
10137         }
10138         Worklist.append(PossibleReductionOps.rbegin(),
10139                         PossibleReductionOps.rend());
10140       } else {
10141         size_t Key, Idx;
10142         std::tie(Key, Idx) = generateKeySubkey(
10143             TreeN, &TLI,
10144             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10145               for (const auto &LoadData : PossibleReducedVals[Key]) {
10146                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10147                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10148                                     LI->getType(), LI->getPointerOperand(), DL,
10149                                     SE, /*StrictCheck=*/true))
10150                   return hash_value(RLI->getPointerOperand());
10151               }
10152               return hash_value(LI->getPointerOperand());
10153             },
10154             /*AllowAlternate=*/false);
10155         ++PossibleReducedVals[Key][Idx]
10156               .insert(std::make_pair(TreeN, 0))
10157               .first->second;
10158       }
10159     }
10160     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10161     // Sort values by the total number of values kinds to start the reduction
10162     // from the longest possible reduced values sequences.
10163     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10164       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10165       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10166       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10167            It != E; ++It) {
10168         PossibleRedValsVect.emplace_back();
10169         auto RedValsVect = It->second.takeVector();
10170         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10171           return P1.second < P2.second;
10172         });
10173         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10174           PossibleRedValsVect.back().append(Data.second, Data.first);
10175       }
10176       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10177         return P1.size() > P2.size();
10178       });
10179       ReducedVals.emplace_back();
10180       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10181         ReducedVals.back().append(Data.rbegin(), Data.rend());
10182     }
10183     // Sort the reduced values by number of same/alternate opcode and/or pointer
10184     // operand.
10185     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10186       return P1.size() > P2.size();
10187     });
10188     return true;
10189   }
10190 
10191   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10192   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10193     constexpr int ReductionLimit = 4;
10194     // If there are a sufficient number of reduction values, reduce
10195     // to a nearby power-of-2. We can safely generate oversized
10196     // vectors and rely on the backend to split them to legal sizes.
10197     unsigned NumReducedVals = std::accumulate(
10198         ReducedVals.begin(), ReducedVals.end(), 0,
10199         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10200     if (NumReducedVals < ReductionLimit)
10201       return nullptr;
10202 
10203     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10204 
10205     // Track the reduced values in case if they are replaced by extractelement
10206     // because of the vectorization.
10207     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10208     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10209     // The same extra argument may be used several times, so log each attempt
10210     // to use it.
10211     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10212       assert(Pair.first && "DebugLoc must be set.");
10213       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10214       TrackedVals.try_emplace(Pair.second, Pair.second);
10215     }
10216 
10217     // The compare instruction of a min/max is the insertion point for new
10218     // instructions and may be replaced with a new compare instruction.
10219     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10220       assert(isa<SelectInst>(RdxRootInst) &&
10221              "Expected min/max reduction to have select root instruction");
10222       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10223       assert(isa<Instruction>(ScalarCond) &&
10224              "Expected min/max reduction to have compare condition");
10225       return cast<Instruction>(ScalarCond);
10226     };
10227 
10228     // The reduction root is used as the insertion point for new instructions,
10229     // so set it as externally used to prevent it from being deleted.
10230     ExternallyUsedValues[ReductionRoot];
10231     SmallVector<Value *> IgnoreList;
10232     for (ReductionOpsType &RdxOps : ReductionOps)
10233       for (Value *RdxOp : RdxOps) {
10234         if (!RdxOp)
10235           continue;
10236         IgnoreList.push_back(RdxOp);
10237       }
10238     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10239 
10240     // Need to track reduced vals, they may be changed during vectorization of
10241     // subvectors.
10242     for (ArrayRef<Value *> Candidates : ReducedVals)
10243       for (Value *V : Candidates)
10244         TrackedVals.try_emplace(V, V);
10245 
10246     DenseMap<Value *, unsigned> VectorizedVals;
10247     Value *VectorizedTree = nullptr;
10248     bool CheckForReusedReductionOps = false;
10249     // Try to vectorize elements based on their type.
10250     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10251       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10252       InstructionsState S = getSameOpcode(OrigReducedVals);
10253       SmallVector<Value *> Candidates;
10254       DenseMap<Value *, Value *> TrackedToOrig;
10255       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10256         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10257         // Check if the reduction value was not overriden by the extractelement
10258         // instruction because of the vectorization and exclude it, if it is not
10259         // compatible with other values.
10260         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10261           if (isVectorLikeInstWithConstOps(Inst) &&
10262               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10263             continue;
10264         Candidates.push_back(RdxVal);
10265         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10266       }
10267       bool ShuffledExtracts = false;
10268       // Try to handle shuffled extractelements.
10269       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10270           I + 1 < E) {
10271         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10272         if (NextS.getOpcode() == Instruction::ExtractElement &&
10273             !NextS.isAltShuffle()) {
10274           SmallVector<Value *> CommonCandidates(Candidates);
10275           for (Value *RV : ReducedVals[I + 1]) {
10276             Value *RdxVal = TrackedVals.find(RV)->second;
10277             // Check if the reduction value was not overriden by the
10278             // extractelement instruction because of the vectorization and
10279             // exclude it, if it is not compatible with other values.
10280             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10281               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10282                 continue;
10283             CommonCandidates.push_back(RdxVal);
10284             TrackedToOrig.try_emplace(RdxVal, RV);
10285           }
10286           SmallVector<int> Mask;
10287           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10288             ++I;
10289             Candidates.swap(CommonCandidates);
10290             ShuffledExtracts = true;
10291           }
10292         }
10293       }
10294       unsigned NumReducedVals = Candidates.size();
10295       if (NumReducedVals < ReductionLimit)
10296         continue;
10297 
10298       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10299       unsigned Start = 0;
10300       unsigned Pos = Start;
10301       // Restarts vectorization attempt with lower vector factor.
10302       unsigned PrevReduxWidth = ReduxWidth;
10303       bool CheckForReusedReductionOpsLocal = false;
10304       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10305                                   &CheckForReusedReductionOpsLocal,
10306                                   &PrevReduxWidth, &V,
10307                                   &IgnoreList](bool IgnoreVL = false) {
10308         bool IsAnyRedOpGathered =
10309             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10310               return V.isGathered(RedOp);
10311             });
10312         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10313           // Check if any of the reduction ops are gathered. If so, worth
10314           // trying again with less number of reduction ops.
10315           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10316         }
10317         ++Pos;
10318         if (Pos < NumReducedVals - ReduxWidth + 1)
10319           return IsAnyRedOpGathered;
10320         Pos = Start;
10321         ReduxWidth /= 2;
10322         return IsAnyRedOpGathered;
10323       };
10324       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10325              ReduxWidth >= ReductionLimit) {
10326         // Dependency in tree of the reduction ops - drop this attempt, try
10327         // later.
10328         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10329             Start == 0) {
10330           CheckForReusedReductionOps = true;
10331           break;
10332         }
10333         PrevReduxWidth = ReduxWidth;
10334         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10335         // Beeing analyzed already - skip.
10336         if (V.areAnalyzedReductionVals(VL)) {
10337           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10338           continue;
10339         }
10340         // Early exit if any of the reduction values were deleted during
10341         // previous vectorization attempts.
10342         if (any_of(VL, [&V](Value *RedVal) {
10343               auto *RedValI = dyn_cast<Instruction>(RedVal);
10344               if (!RedValI)
10345                 return false;
10346               return V.isDeleted(RedValI);
10347             }))
10348           break;
10349         V.buildTree(VL, IgnoreList);
10350         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10351           if (!AdjustReducedVals())
10352             V.analyzedReductionVals(VL);
10353           continue;
10354         }
10355         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10356           if (!AdjustReducedVals())
10357             V.analyzedReductionVals(VL);
10358           continue;
10359         }
10360         V.reorderTopToBottom();
10361         // No need to reorder the root node at all.
10362         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10363         // Keep extracted other reduction values, if they are used in the
10364         // vectorization trees.
10365         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10366             ExternallyUsedValues);
10367         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10368           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10369             continue;
10370           for_each(ReducedVals[Cnt],
10371                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10372                      if (isa<Instruction>(V))
10373                        LocalExternallyUsedValues[TrackedVals[V]];
10374                    });
10375         }
10376         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10377           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10378             continue;
10379           if (VectorizedVals.count(Candidates[Cnt]))
10380             continue;
10381           LocalExternallyUsedValues[Candidates[Cnt]];
10382         }
10383         V.buildExternalUses(LocalExternallyUsedValues);
10384 
10385         V.computeMinimumValueSizes();
10386 
10387         // Intersect the fast-math-flags from all reduction operations.
10388         FastMathFlags RdxFMF;
10389         RdxFMF.set();
10390         for (Value *U : IgnoreList)
10391           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10392             RdxFMF &= FPMO->getFastMathFlags();
10393         // Estimate cost.
10394         InstructionCost TreeCost = V.getTreeCost(VL);
10395         InstructionCost ReductionCost =
10396             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10397         InstructionCost Cost = TreeCost + ReductionCost;
10398         if (!Cost.isValid()) {
10399           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10400           return nullptr;
10401         }
10402         if (Cost >= -SLPCostThreshold) {
10403           V.getORE()->emit([&]() {
10404             return OptimizationRemarkMissed(
10405                        SV_NAME, "HorSLPNotBeneficial",
10406                        ReducedValsToOps.find(VL[0])->second.front())
10407                    << "Vectorizing horizontal reduction is possible"
10408                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10409                    << " and threshold "
10410                    << ore::NV("Threshold", -SLPCostThreshold);
10411           });
10412           if (!AdjustReducedVals())
10413             V.analyzedReductionVals(VL);
10414           continue;
10415         }
10416 
10417         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10418                           << Cost << ". (HorRdx)\n");
10419         V.getORE()->emit([&]() {
10420           return OptimizationRemark(
10421                      SV_NAME, "VectorizedHorizontalReduction",
10422                      ReducedValsToOps.find(VL[0])->second.front())
10423                  << "Vectorized horizontal reduction with cost "
10424                  << ore::NV("Cost", Cost) << " and with tree size "
10425                  << ore::NV("TreeSize", V.getTreeSize());
10426         });
10427 
10428         Builder.setFastMathFlags(RdxFMF);
10429 
10430         // Vectorize a tree.
10431         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10432 
10433         // Emit a reduction. If the root is a select (min/max idiom), the insert
10434         // point is the compare condition of that select.
10435         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10436         if (IsCmpSelMinMax)
10437           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10438         else
10439           Builder.SetInsertPoint(RdxRootInst);
10440 
10441         // To prevent poison from leaking across what used to be sequential,
10442         // safe, scalar boolean logic operations, the reduction operand must be
10443         // frozen.
10444         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10445           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10446 
10447         Value *ReducedSubTree =
10448             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10449 
10450         if (!VectorizedTree) {
10451           // Initialize the final value in the reduction.
10452           VectorizedTree = ReducedSubTree;
10453         } else {
10454           // Update the final value in the reduction.
10455           Builder.SetCurrentDebugLocation(
10456               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10457           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10458                                     ReducedSubTree, "op.rdx", ReductionOps);
10459         }
10460         // Count vectorized reduced values to exclude them from final reduction.
10461         for (Value *V : VL)
10462           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10463                 .first->getSecond();
10464         Pos += ReduxWidth;
10465         Start = Pos;
10466         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10467       }
10468     }
10469     if (VectorizedTree) {
10470       // Finish the reduction.
10471       // Need to add extra arguments and not vectorized possible reduction
10472       // values.
10473       SmallPtrSet<Value *, 8> Visited;
10474       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10475         ArrayRef<Value *> Candidates = ReducedVals[I];
10476         for (Value *RdxVal : Candidates) {
10477           if (!Visited.insert(RdxVal).second)
10478             continue;
10479           Value *StableRdxVal = RdxVal;
10480           auto TVIt = TrackedVals.find(RdxVal);
10481           if (TVIt != TrackedVals.end())
10482             StableRdxVal = TVIt->second;
10483           unsigned NumOps = 0;
10484           auto It = VectorizedVals.find(RdxVal);
10485           if (It != VectorizedVals.end())
10486             NumOps = It->second;
10487           for (Instruction *RedOp :
10488                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10489                    .drop_back(NumOps)) {
10490             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10491             ReductionOpsListType Ops;
10492             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10493               Ops.emplace_back().push_back(Sel->getCondition());
10494             Ops.emplace_back().push_back(RedOp);
10495             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10496                                       StableRdxVal, "op.rdx", Ops);
10497           }
10498         }
10499       }
10500       for (auto &Pair : ExternallyUsedValues) {
10501         // Add each externally used value to the final reduction.
10502         for (auto *I : Pair.second) {
10503           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10504           ReductionOpsListType Ops;
10505           if (auto *Sel = dyn_cast<SelectInst>(I))
10506             Ops.emplace_back().push_back(Sel->getCondition());
10507           Ops.emplace_back().push_back(I);
10508           Value *StableRdxVal = Pair.first;
10509           auto TVIt = TrackedVals.find(Pair.first);
10510           if (TVIt != TrackedVals.end())
10511             StableRdxVal = TVIt->second;
10512           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10513                                     StableRdxVal, "op.rdx", Ops);
10514         }
10515       }
10516 
10517       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10518 
10519       // The original scalar reduction is expected to have no remaining
10520       // uses outside the reduction tree itself.  Assert that we got this
10521       // correct, replace internal uses with undef, and mark for eventual
10522       // deletion.
10523 #ifndef NDEBUG
10524       SmallSet<Value *, 4> IgnoreSet;
10525       for (ArrayRef<Value *> RdxOps : ReductionOps)
10526         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10527 #endif
10528       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10529         for (Value *Ignore : RdxOps) {
10530           if (!Ignore)
10531             continue;
10532 #ifndef NDEBUG
10533           for (auto *U : Ignore->users()) {
10534             assert(IgnoreSet.count(U) &&
10535                    "All users must be either in the reduction ops list.");
10536           }
10537 #endif
10538           if (!Ignore->use_empty()) {
10539             Value *Undef = UndefValue::get(Ignore->getType());
10540             Ignore->replaceAllUsesWith(Undef);
10541           }
10542           V.eraseInstruction(cast<Instruction>(Ignore));
10543         }
10544       }
10545     } else if (!CheckForReusedReductionOps) {
10546       for (ReductionOpsType &RdxOps : ReductionOps)
10547         for (Value *RdxOp : RdxOps)
10548           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10549     }
10550     return VectorizedTree;
10551   }
10552 
10553   unsigned numReductionValues() const { return ReducedVals.size(); }
10554 
10555 private:
10556   /// Calculate the cost of a reduction.
10557   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10558                                    Value *FirstReducedVal, unsigned ReduxWidth,
10559                                    FastMathFlags FMF) {
10560     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10561     Type *ScalarTy = FirstReducedVal->getType();
10562     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10563     InstructionCost VectorCost, ScalarCost;
10564     switch (RdxKind) {
10565     case RecurKind::Add:
10566     case RecurKind::Mul:
10567     case RecurKind::Or:
10568     case RecurKind::And:
10569     case RecurKind::Xor:
10570     case RecurKind::FAdd:
10571     case RecurKind::FMul: {
10572       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10573       VectorCost =
10574           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10575       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10576       break;
10577     }
10578     case RecurKind::FMax:
10579     case RecurKind::FMin: {
10580       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10581       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10582       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10583                                                /*IsUnsigned=*/false, CostKind);
10584       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10585       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10586                                            SclCondTy, RdxPred, CostKind) +
10587                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10588                                            SclCondTy, RdxPred, CostKind);
10589       break;
10590     }
10591     case RecurKind::SMax:
10592     case RecurKind::SMin:
10593     case RecurKind::UMax:
10594     case RecurKind::UMin: {
10595       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10596       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10597       bool IsUnsigned =
10598           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10599       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10600                                                CostKind);
10601       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10602       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10603                                            SclCondTy, RdxPred, CostKind) +
10604                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10605                                            SclCondTy, RdxPred, CostKind);
10606       break;
10607     }
10608     default:
10609       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10610     }
10611 
10612     // Scalar cost is repeated for N-1 elements.
10613     ScalarCost *= (ReduxWidth - 1);
10614     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10615                       << " for reduction that starts with " << *FirstReducedVal
10616                       << " (It is a splitting reduction)\n");
10617     return VectorCost - ScalarCost;
10618   }
10619 
10620   /// Emit a horizontal reduction of the vectorized value.
10621   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10622                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10623     assert(VectorizedValue && "Need to have a vectorized tree node");
10624     assert(isPowerOf2_32(ReduxWidth) &&
10625            "We only handle power-of-two reductions for now");
10626     assert(RdxKind != RecurKind::FMulAdd &&
10627            "A call to the llvm.fmuladd intrinsic is not handled yet");
10628 
10629     ++NumVectorInstructions;
10630     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10631   }
10632 };
10633 
10634 } // end anonymous namespace
10635 
10636 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10637   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10638     return cast<FixedVectorType>(IE->getType())->getNumElements();
10639 
10640   unsigned AggregateSize = 1;
10641   auto *IV = cast<InsertValueInst>(InsertInst);
10642   Type *CurrentType = IV->getType();
10643   do {
10644     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10645       for (auto *Elt : ST->elements())
10646         if (Elt != ST->getElementType(0)) // check homogeneity
10647           return None;
10648       AggregateSize *= ST->getNumElements();
10649       CurrentType = ST->getElementType(0);
10650     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10651       AggregateSize *= AT->getNumElements();
10652       CurrentType = AT->getElementType();
10653     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10654       AggregateSize *= VT->getNumElements();
10655       return AggregateSize;
10656     } else if (CurrentType->isSingleValueType()) {
10657       return AggregateSize;
10658     } else {
10659       return None;
10660     }
10661   } while (true);
10662 }
10663 
10664 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10665                                    TargetTransformInfo *TTI,
10666                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10667                                    SmallVectorImpl<Value *> &InsertElts,
10668                                    unsigned OperandOffset) {
10669   do {
10670     Value *InsertedOperand = LastInsertInst->getOperand(1);
10671     Optional<unsigned> OperandIndex =
10672         getInsertIndex(LastInsertInst, OperandOffset);
10673     if (!OperandIndex)
10674       return;
10675     if (isa<InsertElementInst>(InsertedOperand) ||
10676         isa<InsertValueInst>(InsertedOperand)) {
10677       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10678                              BuildVectorOpds, InsertElts, *OperandIndex);
10679 
10680     } else {
10681       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10682       InsertElts[*OperandIndex] = LastInsertInst;
10683     }
10684     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10685   } while (LastInsertInst != nullptr &&
10686            (isa<InsertValueInst>(LastInsertInst) ||
10687             isa<InsertElementInst>(LastInsertInst)) &&
10688            LastInsertInst->hasOneUse());
10689 }
10690 
10691 /// Recognize construction of vectors like
10692 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10693 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10694 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10695 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10696 ///  starting from the last insertelement or insertvalue instruction.
10697 ///
10698 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10699 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10700 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10701 ///
10702 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10703 ///
10704 /// \return true if it matches.
10705 static bool findBuildAggregate(Instruction *LastInsertInst,
10706                                TargetTransformInfo *TTI,
10707                                SmallVectorImpl<Value *> &BuildVectorOpds,
10708                                SmallVectorImpl<Value *> &InsertElts) {
10709 
10710   assert((isa<InsertElementInst>(LastInsertInst) ||
10711           isa<InsertValueInst>(LastInsertInst)) &&
10712          "Expected insertelement or insertvalue instruction!");
10713 
10714   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10715          "Expected empty result vectors!");
10716 
10717   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10718   if (!AggregateSize)
10719     return false;
10720   BuildVectorOpds.resize(*AggregateSize);
10721   InsertElts.resize(*AggregateSize);
10722 
10723   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10724   llvm::erase_value(BuildVectorOpds, nullptr);
10725   llvm::erase_value(InsertElts, nullptr);
10726   if (BuildVectorOpds.size() >= 2)
10727     return true;
10728 
10729   return false;
10730 }
10731 
10732 /// Try and get a reduction value from a phi node.
10733 ///
10734 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10735 /// if they come from either \p ParentBB or a containing loop latch.
10736 ///
10737 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10738 /// if not possible.
10739 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10740                                 BasicBlock *ParentBB, LoopInfo *LI) {
10741   // There are situations where the reduction value is not dominated by the
10742   // reduction phi. Vectorizing such cases has been reported to cause
10743   // miscompiles. See PR25787.
10744   auto DominatedReduxValue = [&](Value *R) {
10745     return isa<Instruction>(R) &&
10746            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10747   };
10748 
10749   Value *Rdx = nullptr;
10750 
10751   // Return the incoming value if it comes from the same BB as the phi node.
10752   if (P->getIncomingBlock(0) == ParentBB) {
10753     Rdx = P->getIncomingValue(0);
10754   } else if (P->getIncomingBlock(1) == ParentBB) {
10755     Rdx = P->getIncomingValue(1);
10756   }
10757 
10758   if (Rdx && DominatedReduxValue(Rdx))
10759     return Rdx;
10760 
10761   // Otherwise, check whether we have a loop latch to look at.
10762   Loop *BBL = LI->getLoopFor(ParentBB);
10763   if (!BBL)
10764     return nullptr;
10765   BasicBlock *BBLatch = BBL->getLoopLatch();
10766   if (!BBLatch)
10767     return nullptr;
10768 
10769   // There is a loop latch, return the incoming value if it comes from
10770   // that. This reduction pattern occasionally turns up.
10771   if (P->getIncomingBlock(0) == BBLatch) {
10772     Rdx = P->getIncomingValue(0);
10773   } else if (P->getIncomingBlock(1) == BBLatch) {
10774     Rdx = P->getIncomingValue(1);
10775   }
10776 
10777   if (Rdx && DominatedReduxValue(Rdx))
10778     return Rdx;
10779 
10780   return nullptr;
10781 }
10782 
10783 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10784   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10785     return true;
10786   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10787     return true;
10788   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10789     return true;
10790   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10791     return true;
10792   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10793     return true;
10794   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10795     return true;
10796   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10797     return true;
10798   return false;
10799 }
10800 
10801 /// Attempt to reduce a horizontal reduction.
10802 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10803 /// with reduction operators \a Root (or one of its operands) in a basic block
10804 /// \a BB, then check if it can be done. If horizontal reduction is not found
10805 /// and root instruction is a binary operation, vectorization of the operands is
10806 /// attempted.
10807 /// \returns true if a horizontal reduction was matched and reduced or operands
10808 /// of one of the binary instruction were vectorized.
10809 /// \returns false if a horizontal reduction was not matched (or not possible)
10810 /// or no vectorization of any binary operation feeding \a Root instruction was
10811 /// performed.
10812 static bool tryToVectorizeHorReductionOrInstOperands(
10813     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10814     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10815     const TargetLibraryInfo &TLI,
10816     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10817   if (!ShouldVectorizeHor)
10818     return false;
10819 
10820   if (!Root)
10821     return false;
10822 
10823   if (Root->getParent() != BB || isa<PHINode>(Root))
10824     return false;
10825   // Start analysis starting from Root instruction. If horizontal reduction is
10826   // found, try to vectorize it. If it is not a horizontal reduction or
10827   // vectorization is not possible or not effective, and currently analyzed
10828   // instruction is a binary operation, try to vectorize the operands, using
10829   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10830   // the same procedure considering each operand as a possible root of the
10831   // horizontal reduction.
10832   // Interrupt the process if the Root instruction itself was vectorized or all
10833   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10834   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10835   // CmpInsts so we can skip extra attempts in
10836   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10837   std::queue<std::pair<Instruction *, unsigned>> Stack;
10838   Stack.emplace(Root, 0);
10839   SmallPtrSet<Value *, 8> VisitedInstrs;
10840   SmallVector<WeakTrackingVH> PostponedInsts;
10841   bool Res = false;
10842   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10843                                                      Value *&B0,
10844                                                      Value *&B1) -> Value * {
10845     if (R.isAnalizedReductionRoot(Inst))
10846       return nullptr;
10847     bool IsBinop = matchRdxBop(Inst, B0, B1);
10848     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10849     if (IsBinop || IsSelect) {
10850       HorizontalReduction HorRdx;
10851       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10852         return HorRdx.tryToReduce(R, TTI);
10853     }
10854     return nullptr;
10855   };
10856   while (!Stack.empty()) {
10857     Instruction *Inst;
10858     unsigned Level;
10859     std::tie(Inst, Level) = Stack.front();
10860     Stack.pop();
10861     // Do not try to analyze instruction that has already been vectorized.
10862     // This may happen when we vectorize instruction operands on a previous
10863     // iteration while stack was populated before that happened.
10864     if (R.isDeleted(Inst))
10865       continue;
10866     Value *B0 = nullptr, *B1 = nullptr;
10867     if (Value *V = TryToReduce(Inst, B0, B1)) {
10868       Res = true;
10869       // Set P to nullptr to avoid re-analysis of phi node in
10870       // matchAssociativeReduction function unless this is the root node.
10871       P = nullptr;
10872       if (auto *I = dyn_cast<Instruction>(V)) {
10873         // Try to find another reduction.
10874         Stack.emplace(I, Level);
10875         continue;
10876       }
10877     } else {
10878       bool IsBinop = B0 && B1;
10879       if (P && IsBinop) {
10880         Inst = dyn_cast<Instruction>(B0);
10881         if (Inst == P)
10882           Inst = dyn_cast<Instruction>(B1);
10883         if (!Inst) {
10884           // Set P to nullptr to avoid re-analysis of phi node in
10885           // matchAssociativeReduction function unless this is the root node.
10886           P = nullptr;
10887           continue;
10888         }
10889       }
10890       // Set P to nullptr to avoid re-analysis of phi node in
10891       // matchAssociativeReduction function unless this is the root node.
10892       P = nullptr;
10893       // Do not try to vectorize CmpInst operands, this is done separately.
10894       // Final attempt for binop args vectorization should happen after the loop
10895       // to try to find reductions.
10896       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
10897         PostponedInsts.push_back(Inst);
10898     }
10899 
10900     // Try to vectorize operands.
10901     // Continue analysis for the instruction from the same basic block only to
10902     // save compile time.
10903     if (++Level < RecursionMaxDepth)
10904       for (auto *Op : Inst->operand_values())
10905         if (VisitedInstrs.insert(Op).second)
10906           if (auto *I = dyn_cast<Instruction>(Op))
10907             // Do not try to vectorize CmpInst operands,  this is done
10908             // separately.
10909             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
10910                 !R.isDeleted(I) && I->getParent() == BB)
10911               Stack.emplace(I, Level);
10912   }
10913   // Try to vectorized binops where reductions were not found.
10914   for (Value *V : PostponedInsts)
10915     if (auto *Inst = dyn_cast<Instruction>(V))
10916       if (!R.isDeleted(Inst))
10917         Res |= Vectorize(Inst, R);
10918   return Res;
10919 }
10920 
10921 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10922                                                  BasicBlock *BB, BoUpSLP &R,
10923                                                  TargetTransformInfo *TTI) {
10924   auto *I = dyn_cast_or_null<Instruction>(V);
10925   if (!I)
10926     return false;
10927 
10928   if (!isa<BinaryOperator>(I))
10929     P = nullptr;
10930   // Try to match and vectorize a horizontal reduction.
10931   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10932     return tryToVectorize(I, R);
10933   };
10934   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10935                                                   *TLI, ExtraVectorization);
10936 }
10937 
10938 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10939                                                  BasicBlock *BB, BoUpSLP &R) {
10940   const DataLayout &DL = BB->getModule()->getDataLayout();
10941   if (!R.canMapToVector(IVI->getType(), DL))
10942     return false;
10943 
10944   SmallVector<Value *, 16> BuildVectorOpds;
10945   SmallVector<Value *, 16> BuildVectorInsts;
10946   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10947     return false;
10948 
10949   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10950   // Aggregate value is unlikely to be processed in vector register.
10951   return tryToVectorizeList(BuildVectorOpds, R);
10952 }
10953 
10954 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10955                                                    BasicBlock *BB, BoUpSLP &R) {
10956   SmallVector<Value *, 16> BuildVectorInsts;
10957   SmallVector<Value *, 16> BuildVectorOpds;
10958   SmallVector<int> Mask;
10959   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10960       (llvm::all_of(
10961            BuildVectorOpds,
10962            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10963        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10964     return false;
10965 
10966   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10967   return tryToVectorizeList(BuildVectorInsts, R);
10968 }
10969 
10970 template <typename T>
10971 static bool
10972 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10973                        function_ref<unsigned(T *)> Limit,
10974                        function_ref<bool(T *, T *)> Comparator,
10975                        function_ref<bool(T *, T *)> AreCompatible,
10976                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10977                        bool LimitForRegisterSize) {
10978   bool Changed = false;
10979   // Sort by type, parent, operands.
10980   stable_sort(Incoming, Comparator);
10981 
10982   // Try to vectorize elements base on their type.
10983   SmallVector<T *> Candidates;
10984   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10985     // Look for the next elements with the same type, parent and operand
10986     // kinds.
10987     auto *SameTypeIt = IncIt;
10988     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10989       ++SameTypeIt;
10990 
10991     // Try to vectorize them.
10992     unsigned NumElts = (SameTypeIt - IncIt);
10993     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10994                       << NumElts << ")\n");
10995     // The vectorization is a 3-state attempt:
10996     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10997     // size of maximal register at first.
10998     // 2. Try to vectorize remaining instructions with the same type, if
10999     // possible. This may result in the better vectorization results rather than
11000     // if we try just to vectorize instructions with the same/alternate opcodes.
11001     // 3. Final attempt to try to vectorize all instructions with the
11002     // same/alternate ops only, this may result in some extra final
11003     // vectorization.
11004     if (NumElts > 1 &&
11005         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11006       // Success start over because instructions might have been changed.
11007       Changed = true;
11008     } else if (NumElts < Limit(*IncIt) &&
11009                (Candidates.empty() ||
11010                 Candidates.front()->getType() == (*IncIt)->getType())) {
11011       Candidates.append(IncIt, std::next(IncIt, NumElts));
11012     }
11013     // Final attempt to vectorize instructions with the same types.
11014     if (Candidates.size() > 1 &&
11015         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11016       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11017         // Success start over because instructions might have been changed.
11018         Changed = true;
11019       } else if (LimitForRegisterSize) {
11020         // Try to vectorize using small vectors.
11021         for (auto *It = Candidates.begin(), *End = Candidates.end();
11022              It != End;) {
11023           auto *SameTypeIt = It;
11024           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11025             ++SameTypeIt;
11026           unsigned NumElts = (SameTypeIt - It);
11027           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11028                                             /*LimitForRegisterSize=*/false))
11029             Changed = true;
11030           It = SameTypeIt;
11031         }
11032       }
11033       Candidates.clear();
11034     }
11035 
11036     // Start over at the next instruction of a different type (or the end).
11037     IncIt = SameTypeIt;
11038   }
11039   return Changed;
11040 }
11041 
11042 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11043 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11044 /// operands. If IsCompatibility is false, function implements strict weak
11045 /// ordering relation between two cmp instructions, returning true if the first
11046 /// instruction is "less" than the second, i.e. its predicate is less than the
11047 /// predicate of the second or the operands IDs are less than the operands IDs
11048 /// of the second cmp instruction.
11049 template <bool IsCompatibility>
11050 static bool compareCmp(Value *V, Value *V2,
11051                        function_ref<bool(Instruction *)> IsDeleted) {
11052   auto *CI1 = cast<CmpInst>(V);
11053   auto *CI2 = cast<CmpInst>(V2);
11054   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11055     return false;
11056   if (CI1->getOperand(0)->getType()->getTypeID() <
11057       CI2->getOperand(0)->getType()->getTypeID())
11058     return !IsCompatibility;
11059   if (CI1->getOperand(0)->getType()->getTypeID() >
11060       CI2->getOperand(0)->getType()->getTypeID())
11061     return false;
11062   CmpInst::Predicate Pred1 = CI1->getPredicate();
11063   CmpInst::Predicate Pred2 = CI2->getPredicate();
11064   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11065   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11066   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11067   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11068   if (BasePred1 < BasePred2)
11069     return !IsCompatibility;
11070   if (BasePred1 > BasePred2)
11071     return false;
11072   // Compare operands.
11073   bool LEPreds = Pred1 <= Pred2;
11074   bool GEPreds = Pred1 >= Pred2;
11075   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11076     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11077     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11078     if (Op1->getValueID() < Op2->getValueID())
11079       return !IsCompatibility;
11080     if (Op1->getValueID() > Op2->getValueID())
11081       return false;
11082     if (auto *I1 = dyn_cast<Instruction>(Op1))
11083       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11084         if (I1->getParent() != I2->getParent())
11085           return false;
11086         InstructionsState S = getSameOpcode({I1, I2});
11087         if (S.getOpcode())
11088           continue;
11089         return false;
11090       }
11091   }
11092   return IsCompatibility;
11093 }
11094 
11095 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11096     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11097     bool AtTerminator) {
11098   bool OpsChanged = false;
11099   SmallVector<Instruction *, 4> PostponedCmps;
11100   for (auto *I : reverse(Instructions)) {
11101     if (R.isDeleted(I))
11102       continue;
11103     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11104       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11105     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11106       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11107     } else if (isa<CmpInst>(I)) {
11108       PostponedCmps.push_back(I);
11109       continue;
11110     }
11111     // Try to find reductions in buildvector sequnces.
11112     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11113   }
11114   if (AtTerminator) {
11115     // Try to find reductions first.
11116     for (Instruction *I : PostponedCmps) {
11117       if (R.isDeleted(I))
11118         continue;
11119       for (Value *Op : I->operands())
11120         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11121     }
11122     // Try to vectorize operands as vector bundles.
11123     for (Instruction *I : PostponedCmps) {
11124       if (R.isDeleted(I))
11125         continue;
11126       OpsChanged |= tryToVectorize(I, R);
11127     }
11128     // Try to vectorize list of compares.
11129     // Sort by type, compare predicate, etc.
11130     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11131       return compareCmp<false>(V, V2,
11132                                [&R](Instruction *I) { return R.isDeleted(I); });
11133     };
11134 
11135     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11136       if (V1 == V2)
11137         return true;
11138       return compareCmp<true>(V1, V2,
11139                               [&R](Instruction *I) { return R.isDeleted(I); });
11140     };
11141     auto Limit = [&R](Value *V) {
11142       unsigned EltSize = R.getVectorElementSize(V);
11143       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11144     };
11145 
11146     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11147     OpsChanged |= tryToVectorizeSequence<Value>(
11148         Vals, Limit, CompareSorter, AreCompatibleCompares,
11149         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11150           // Exclude possible reductions from other blocks.
11151           bool ArePossiblyReducedInOtherBlock =
11152               any_of(Candidates, [](Value *V) {
11153                 return any_of(V->users(), [V](User *U) {
11154                   return isa<SelectInst>(U) &&
11155                          cast<SelectInst>(U)->getParent() !=
11156                              cast<Instruction>(V)->getParent();
11157                 });
11158               });
11159           if (ArePossiblyReducedInOtherBlock)
11160             return false;
11161           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11162         },
11163         /*LimitForRegisterSize=*/true);
11164     Instructions.clear();
11165   } else {
11166     // Insert in reverse order since the PostponedCmps vector was filled in
11167     // reverse order.
11168     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11169   }
11170   return OpsChanged;
11171 }
11172 
11173 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11174   bool Changed = false;
11175   SmallVector<Value *, 4> Incoming;
11176   SmallPtrSet<Value *, 16> VisitedInstrs;
11177   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11178   // node. Allows better to identify the chains that can be vectorized in the
11179   // better way.
11180   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11181   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11182     assert(isValidElementType(V1->getType()) &&
11183            isValidElementType(V2->getType()) &&
11184            "Expected vectorizable types only.");
11185     // It is fine to compare type IDs here, since we expect only vectorizable
11186     // types, like ints, floats and pointers, we don't care about other type.
11187     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11188       return true;
11189     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11190       return false;
11191     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11192     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11193     if (Opcodes1.size() < Opcodes2.size())
11194       return true;
11195     if (Opcodes1.size() > Opcodes2.size())
11196       return false;
11197     Optional<bool> ConstOrder;
11198     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11199       // Undefs are compatible with any other value.
11200       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11201         if (!ConstOrder)
11202           ConstOrder =
11203               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11204         continue;
11205       }
11206       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11207         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11208           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11209           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11210           if (!NodeI1)
11211             return NodeI2 != nullptr;
11212           if (!NodeI2)
11213             return false;
11214           assert((NodeI1 == NodeI2) ==
11215                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11216                  "Different nodes should have different DFS numbers");
11217           if (NodeI1 != NodeI2)
11218             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11219           InstructionsState S = getSameOpcode({I1, I2});
11220           if (S.getOpcode())
11221             continue;
11222           return I1->getOpcode() < I2->getOpcode();
11223         }
11224       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11225         if (!ConstOrder)
11226           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11227         continue;
11228       }
11229       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11230         return true;
11231       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11232         return false;
11233     }
11234     return ConstOrder && *ConstOrder;
11235   };
11236   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11237     if (V1 == V2)
11238       return true;
11239     if (V1->getType() != V2->getType())
11240       return false;
11241     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11242     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11243     if (Opcodes1.size() != Opcodes2.size())
11244       return false;
11245     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11246       // Undefs are compatible with any other value.
11247       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11248         continue;
11249       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11250         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11251           if (I1->getParent() != I2->getParent())
11252             return false;
11253           InstructionsState S = getSameOpcode({I1, I2});
11254           if (S.getOpcode())
11255             continue;
11256           return false;
11257         }
11258       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11259         continue;
11260       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11261         return false;
11262     }
11263     return true;
11264   };
11265   auto Limit = [&R](Value *V) {
11266     unsigned EltSize = R.getVectorElementSize(V);
11267     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11268   };
11269 
11270   bool HaveVectorizedPhiNodes = false;
11271   do {
11272     // Collect the incoming values from the PHIs.
11273     Incoming.clear();
11274     for (Instruction &I : *BB) {
11275       PHINode *P = dyn_cast<PHINode>(&I);
11276       if (!P)
11277         break;
11278 
11279       // No need to analyze deleted, vectorized and non-vectorizable
11280       // instructions.
11281       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11282           isValidElementType(P->getType()))
11283         Incoming.push_back(P);
11284     }
11285 
11286     // Find the corresponding non-phi nodes for better matching when trying to
11287     // build the tree.
11288     for (Value *V : Incoming) {
11289       SmallVectorImpl<Value *> &Opcodes =
11290           PHIToOpcodes.try_emplace(V).first->getSecond();
11291       if (!Opcodes.empty())
11292         continue;
11293       SmallVector<Value *, 4> Nodes(1, V);
11294       SmallPtrSet<Value *, 4> Visited;
11295       while (!Nodes.empty()) {
11296         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11297         if (!Visited.insert(PHI).second)
11298           continue;
11299         for (Value *V : PHI->incoming_values()) {
11300           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11301             Nodes.push_back(PHI1);
11302             continue;
11303           }
11304           Opcodes.emplace_back(V);
11305         }
11306       }
11307     }
11308 
11309     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11310         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11311         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11312           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11313         },
11314         /*LimitForRegisterSize=*/true);
11315     Changed |= HaveVectorizedPhiNodes;
11316     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11317   } while (HaveVectorizedPhiNodes);
11318 
11319   VisitedInstrs.clear();
11320 
11321   SmallVector<Instruction *, 8> PostProcessInstructions;
11322   SmallDenseSet<Instruction *, 4> KeyNodes;
11323   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11324     // Skip instructions with scalable type. The num of elements is unknown at
11325     // compile-time for scalable type.
11326     if (isa<ScalableVectorType>(it->getType()))
11327       continue;
11328 
11329     // Skip instructions marked for the deletion.
11330     if (R.isDeleted(&*it))
11331       continue;
11332     // We may go through BB multiple times so skip the one we have checked.
11333     if (!VisitedInstrs.insert(&*it).second) {
11334       if (it->use_empty() && KeyNodes.contains(&*it) &&
11335           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11336                                       it->isTerminator())) {
11337         // We would like to start over since some instructions are deleted
11338         // and the iterator may become invalid value.
11339         Changed = true;
11340         it = BB->begin();
11341         e = BB->end();
11342       }
11343       continue;
11344     }
11345 
11346     if (isa<DbgInfoIntrinsic>(it))
11347       continue;
11348 
11349     // Try to vectorize reductions that use PHINodes.
11350     if (PHINode *P = dyn_cast<PHINode>(it)) {
11351       // Check that the PHI is a reduction PHI.
11352       if (P->getNumIncomingValues() == 2) {
11353         // Try to match and vectorize a horizontal reduction.
11354         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11355                                      TTI)) {
11356           Changed = true;
11357           it = BB->begin();
11358           e = BB->end();
11359           continue;
11360         }
11361       }
11362       // Try to vectorize the incoming values of the PHI, to catch reductions
11363       // that feed into PHIs.
11364       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11365         // Skip if the incoming block is the current BB for now. Also, bypass
11366         // unreachable IR for efficiency and to avoid crashing.
11367         // TODO: Collect the skipped incoming values and try to vectorize them
11368         // after processing BB.
11369         if (BB == P->getIncomingBlock(I) ||
11370             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11371           continue;
11372 
11373         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11374                                             P->getIncomingBlock(I), R, TTI);
11375       }
11376       continue;
11377     }
11378 
11379     // Ran into an instruction without users, like terminator, or function call
11380     // with ignored return value, store. Ignore unused instructions (basing on
11381     // instruction type, except for CallInst and InvokeInst).
11382     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11383                             isa<InvokeInst>(it))) {
11384       KeyNodes.insert(&*it);
11385       bool OpsChanged = false;
11386       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11387         for (auto *V : it->operand_values()) {
11388           // Try to match and vectorize a horizontal reduction.
11389           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11390         }
11391       }
11392       // Start vectorization of post-process list of instructions from the
11393       // top-tree instructions to try to vectorize as many instructions as
11394       // possible.
11395       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11396                                                 it->isTerminator());
11397       if (OpsChanged) {
11398         // We would like to start over since some instructions are deleted
11399         // and the iterator may become invalid value.
11400         Changed = true;
11401         it = BB->begin();
11402         e = BB->end();
11403         continue;
11404       }
11405     }
11406 
11407     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11408         isa<InsertValueInst>(it))
11409       PostProcessInstructions.push_back(&*it);
11410   }
11411 
11412   return Changed;
11413 }
11414 
11415 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11416   auto Changed = false;
11417   for (auto &Entry : GEPs) {
11418     // If the getelementptr list has fewer than two elements, there's nothing
11419     // to do.
11420     if (Entry.second.size() < 2)
11421       continue;
11422 
11423     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11424                       << Entry.second.size() << ".\n");
11425 
11426     // Process the GEP list in chunks suitable for the target's supported
11427     // vector size. If a vector register can't hold 1 element, we are done. We
11428     // are trying to vectorize the index computations, so the maximum number of
11429     // elements is based on the size of the index expression, rather than the
11430     // size of the GEP itself (the target's pointer size).
11431     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11432     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11433     if (MaxVecRegSize < EltSize)
11434       continue;
11435 
11436     unsigned MaxElts = MaxVecRegSize / EltSize;
11437     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11438       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11439       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11440 
11441       // Initialize a set a candidate getelementptrs. Note that we use a
11442       // SetVector here to preserve program order. If the index computations
11443       // are vectorizable and begin with loads, we want to minimize the chance
11444       // of having to reorder them later.
11445       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11446 
11447       // Some of the candidates may have already been vectorized after we
11448       // initially collected them. If so, they are marked as deleted, so remove
11449       // them from the set of candidates.
11450       Candidates.remove_if(
11451           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11452 
11453       // Remove from the set of candidates all pairs of getelementptrs with
11454       // constant differences. Such getelementptrs are likely not good
11455       // candidates for vectorization in a bottom-up phase since one can be
11456       // computed from the other. We also ensure all candidate getelementptr
11457       // indices are unique.
11458       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11459         auto *GEPI = GEPList[I];
11460         if (!Candidates.count(GEPI))
11461           continue;
11462         auto *SCEVI = SE->getSCEV(GEPList[I]);
11463         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11464           auto *GEPJ = GEPList[J];
11465           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11466           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11467             Candidates.remove(GEPI);
11468             Candidates.remove(GEPJ);
11469           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11470             Candidates.remove(GEPJ);
11471           }
11472         }
11473       }
11474 
11475       // We break out of the above computation as soon as we know there are
11476       // fewer than two candidates remaining.
11477       if (Candidates.size() < 2)
11478         continue;
11479 
11480       // Add the single, non-constant index of each candidate to the bundle. We
11481       // ensured the indices met these constraints when we originally collected
11482       // the getelementptrs.
11483       SmallVector<Value *, 16> Bundle(Candidates.size());
11484       auto BundleIndex = 0u;
11485       for (auto *V : Candidates) {
11486         auto *GEP = cast<GetElementPtrInst>(V);
11487         auto *GEPIdx = GEP->idx_begin()->get();
11488         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11489         Bundle[BundleIndex++] = GEPIdx;
11490       }
11491 
11492       // Try and vectorize the indices. We are currently only interested in
11493       // gather-like cases of the form:
11494       //
11495       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11496       //
11497       // where the loads of "a", the loads of "b", and the subtractions can be
11498       // performed in parallel. It's likely that detecting this pattern in a
11499       // bottom-up phase will be simpler and less costly than building a
11500       // full-blown top-down phase beginning at the consecutive loads.
11501       Changed |= tryToVectorizeList(Bundle, R);
11502     }
11503   }
11504   return Changed;
11505 }
11506 
11507 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11508   bool Changed = false;
11509   // Sort by type, base pointers and values operand. Value operands must be
11510   // compatible (have the same opcode, same parent), otherwise it is
11511   // definitely not profitable to try to vectorize them.
11512   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11513     if (V->getPointerOperandType()->getTypeID() <
11514         V2->getPointerOperandType()->getTypeID())
11515       return true;
11516     if (V->getPointerOperandType()->getTypeID() >
11517         V2->getPointerOperandType()->getTypeID())
11518       return false;
11519     // UndefValues are compatible with all other values.
11520     if (isa<UndefValue>(V->getValueOperand()) ||
11521         isa<UndefValue>(V2->getValueOperand()))
11522       return false;
11523     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11524       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11525         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11526             DT->getNode(I1->getParent());
11527         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11528             DT->getNode(I2->getParent());
11529         assert(NodeI1 && "Should only process reachable instructions");
11530         assert(NodeI2 && "Should only process reachable instructions");
11531         assert((NodeI1 == NodeI2) ==
11532                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11533                "Different nodes should have different DFS numbers");
11534         if (NodeI1 != NodeI2)
11535           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11536         InstructionsState S = getSameOpcode({I1, I2});
11537         if (S.getOpcode())
11538           return false;
11539         return I1->getOpcode() < I2->getOpcode();
11540       }
11541     if (isa<Constant>(V->getValueOperand()) &&
11542         isa<Constant>(V2->getValueOperand()))
11543       return false;
11544     return V->getValueOperand()->getValueID() <
11545            V2->getValueOperand()->getValueID();
11546   };
11547 
11548   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11549     if (V1 == V2)
11550       return true;
11551     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11552       return false;
11553     // Undefs are compatible with any other value.
11554     if (isa<UndefValue>(V1->getValueOperand()) ||
11555         isa<UndefValue>(V2->getValueOperand()))
11556       return true;
11557     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11558       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11559         if (I1->getParent() != I2->getParent())
11560           return false;
11561         InstructionsState S = getSameOpcode({I1, I2});
11562         return S.getOpcode() > 0;
11563       }
11564     if (isa<Constant>(V1->getValueOperand()) &&
11565         isa<Constant>(V2->getValueOperand()))
11566       return true;
11567     return V1->getValueOperand()->getValueID() ==
11568            V2->getValueOperand()->getValueID();
11569   };
11570   auto Limit = [&R, this](StoreInst *SI) {
11571     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11572     return R.getMinVF(EltSize);
11573   };
11574 
11575   // Attempt to sort and vectorize each of the store-groups.
11576   for (auto &Pair : Stores) {
11577     if (Pair.second.size() < 2)
11578       continue;
11579 
11580     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11581                       << Pair.second.size() << ".\n");
11582 
11583     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11584       continue;
11585 
11586     Changed |= tryToVectorizeSequence<StoreInst>(
11587         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11588         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11589           return vectorizeStores(Candidates, R);
11590         },
11591         /*LimitForRegisterSize=*/false);
11592   }
11593   return Changed;
11594 }
11595 
11596 char SLPVectorizer::ID = 0;
11597 
11598 static const char lv_name[] = "SLP Vectorizer";
11599 
11600 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11601 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11602 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11603 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11604 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11605 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11606 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11607 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11608 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11609 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11610 
11611 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11612