1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(const Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   const auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  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   /// \param Limit Lower limit of the cost, considered to be good enough score.
2020   Optional<int>
2021   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2022                    int Limit = LookAheadHeuristics::ScoreFail) {
2023     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2024                                   RootLookAheadMaxDepth);
2025     int BestScore = Limit;
2026     Optional<int> Index = None;
2027     for (int I : seq<int>(0, Candidates.size())) {
2028       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2029                                                Candidates[I].second,
2030                                                /*U1=*/nullptr, /*U2=*/nullptr,
2031                                                /*Level=*/1, None);
2032       if (Score > BestScore) {
2033         BestScore = Score;
2034         Index = I;
2035       }
2036     }
2037     return Index;
2038   }
2039 
2040   /// Checks if the instruction is marked for deletion.
2041   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2042 
2043   /// Removes an instruction from its block and eventually deletes it.
2044   /// It's like Instruction::eraseFromParent() except that the actual deletion
2045   /// is delayed until BoUpSLP is destructed.
2046   void eraseInstruction(Instruction *I) {
2047     DeletedInstructions.insert(I);
2048   }
2049 
2050   /// Checks if the instruction was already analyzed for being possible
2051   /// reduction root.
2052   bool isAnalyzedReductionRoot(Instruction *I) const {
2053     return AnalyzedReductionsRoots.count(I);
2054   }
2055   /// Register given instruction as already analyzed for being possible
2056   /// reduction root.
2057   void analyzedReductionRoot(Instruction *I) {
2058     AnalyzedReductionsRoots.insert(I);
2059   }
2060   /// Checks if the provided list of reduced values was checked already for
2061   /// vectorization.
2062   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2063     return AnalyzedReductionVals.contains(hash_value(VL));
2064   }
2065   /// Adds the list of reduced values to list of already checked values for the
2066   /// vectorization.
2067   void analyzedReductionVals(ArrayRef<Value *> VL) {
2068     AnalyzedReductionVals.insert(hash_value(VL));
2069   }
2070   /// Clear the list of the analyzed reduction root instructions.
2071   void clearReductionData() {
2072     AnalyzedReductionsRoots.clear();
2073     AnalyzedReductionVals.clear();
2074   }
2075   /// Checks if the given value is gathered in one of the nodes.
2076   bool isGathered(Value *V) const {
2077     return MustGather.contains(V);
2078   }
2079 
2080   ~BoUpSLP();
2081 
2082 private:
2083   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2084   /// reordering (i.e. the operands can be reordered because they have only one
2085   /// user and reordarable).
2086   /// \param ReorderableGathers List of all gather nodes that require reordering
2087   /// (e.g., gather of extractlements or partially vectorizable loads).
2088   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2089   /// reordering, subset of \p NonVectorized.
2090   bool
2091   canReorderOperands(TreeEntry *UserTE,
2092                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2093                      ArrayRef<TreeEntry *> ReorderableGathers,
2094                      SmallVectorImpl<TreeEntry *> &GatherOps);
2095 
2096   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2097   /// if any. If it is not vectorized (gather node), returns nullptr.
2098   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2099     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2100     TreeEntry *TE = nullptr;
2101     const auto *It = find_if(VL, [this, &TE](Value *V) {
2102       TE = getTreeEntry(V);
2103       return TE;
2104     });
2105     if (It != VL.end() && TE->isSame(VL))
2106       return TE;
2107     return nullptr;
2108   }
2109 
2110   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2111   /// if any. If it is not vectorized (gather node), returns nullptr.
2112   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2113                                         unsigned OpIdx) const {
2114     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2115         const_cast<TreeEntry *>(UserTE), OpIdx);
2116   }
2117 
2118   /// Checks if all users of \p I are the part of the vectorization tree.
2119   bool areAllUsersVectorized(Instruction *I,
2120                              ArrayRef<Value *> VectorizedVals) const;
2121 
2122   /// \returns the cost of the vectorizable entry.
2123   InstructionCost getEntryCost(const TreeEntry *E,
2124                                ArrayRef<Value *> VectorizedVals);
2125 
2126   /// This is the recursive part of buildTree.
2127   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2128                      const EdgeInfo &EI);
2129 
2130   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2131   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2132   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2133   /// returns false, setting \p CurrentOrder to either an empty vector or a
2134   /// non-identity permutation that allows to reuse extract instructions.
2135   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2136                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2137 
2138   /// Vectorize a single entry in the tree.
2139   Value *vectorizeTree(TreeEntry *E);
2140 
2141   /// Vectorize a single entry in the tree, starting in \p VL.
2142   Value *vectorizeTree(ArrayRef<Value *> VL);
2143 
2144   /// Create a new vector from a list of scalar values.  Produces a sequence
2145   /// which exploits values reused across lanes, and arranges the inserts
2146   /// for ease of later optimization.
2147   Value *createBuildVector(ArrayRef<Value *> VL);
2148 
2149   /// \returns the scalarization cost for this type. Scalarization in this
2150   /// context means the creation of vectors from a group of scalars. If \p
2151   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2152   /// vector elements.
2153   InstructionCost getGatherCost(FixedVectorType *Ty,
2154                                 const APInt &ShuffledIndices,
2155                                 bool NeedToShuffle) const;
2156 
2157   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2158   /// tree entries.
2159   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2160   /// previous tree entries. \p Mask is filled with the shuffle mask.
2161   Optional<TargetTransformInfo::ShuffleKind>
2162   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2163                         SmallVectorImpl<const TreeEntry *> &Entries);
2164 
2165   /// \returns the scalarization cost for this list of values. Assuming that
2166   /// this subtree gets vectorized, we may need to extract the values from the
2167   /// roots. This method calculates the cost of extracting the values.
2168   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2169 
2170   /// Set the Builder insert point to one after the last instruction in
2171   /// the bundle
2172   void setInsertPointAfterBundle(const TreeEntry *E);
2173 
2174   /// \returns a vector from a collection of scalars in \p VL.
2175   Value *gather(ArrayRef<Value *> VL);
2176 
2177   /// \returns whether the VectorizableTree is fully vectorizable and will
2178   /// be beneficial even the tree height is tiny.
2179   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2180 
2181   /// Reorder commutative or alt operands to get better probability of
2182   /// generating vectorized code.
2183   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2184                                              SmallVectorImpl<Value *> &Left,
2185                                              SmallVectorImpl<Value *> &Right,
2186                                              const DataLayout &DL,
2187                                              ScalarEvolution &SE,
2188                                              const BoUpSLP &R);
2189 
2190   /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2191   /// users of \p TE and collects the stores. It returns the map from the store
2192   /// pointers to the collected stores.
2193   DenseMap<Value *, SmallVector<StoreInst *, 4>>
2194   collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2195 
2196   /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2197   /// stores in \p StoresVec can for a vector instruction. If so it returns true
2198   /// and populates \p ReorderIndices with the shuffle indices of the the stores
2199   /// when compared to the sorted vector.
2200   bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2201                      OrdersType &ReorderIndices) const;
2202 
2203   /// Iterates through the users of \p TE, looking for scalar stores that can be
2204   /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2205   /// their order and builds an order index vector for each store bundle. It
2206   /// returns all these order vectors found.
2207   /// We run this after the tree has formed, otherwise we may come across user
2208   /// instructions that are not yet in the tree.
2209   SmallVector<OrdersType, 1>
2210   findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2211 
2212   struct TreeEntry {
2213     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2214     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2215 
2216     /// \returns true if the scalars in VL are equal to this entry.
2217     bool isSame(ArrayRef<Value *> VL) const {
2218       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2219         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2220           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2221         return VL.size() == Mask.size() &&
2222                std::equal(VL.begin(), VL.end(), Mask.begin(),
2223                           [Scalars](Value *V, int Idx) {
2224                             return (isa<UndefValue>(V) &&
2225                                     Idx == UndefMaskElem) ||
2226                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2227                           });
2228       };
2229       if (!ReorderIndices.empty()) {
2230         // TODO: implement matching if the nodes are just reordered, still can
2231         // treat the vector as the same if the list of scalars matches VL
2232         // directly, without reordering.
2233         SmallVector<int> Mask;
2234         inversePermutation(ReorderIndices, Mask);
2235         if (VL.size() == Scalars.size())
2236           return IsSame(Scalars, Mask);
2237         if (VL.size() == ReuseShuffleIndices.size()) {
2238           ::addMask(Mask, ReuseShuffleIndices);
2239           return IsSame(Scalars, Mask);
2240         }
2241         return false;
2242       }
2243       return IsSame(Scalars, ReuseShuffleIndices);
2244     }
2245 
2246     /// \returns true if current entry has same operands as \p TE.
2247     bool hasEqualOperands(const TreeEntry &TE) const {
2248       if (TE.getNumOperands() != getNumOperands())
2249         return false;
2250       SmallBitVector Used(getNumOperands());
2251       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2252         unsigned PrevCount = Used.count();
2253         for (unsigned K = 0; K < E; ++K) {
2254           if (Used.test(K))
2255             continue;
2256           if (getOperand(K) == TE.getOperand(I)) {
2257             Used.set(K);
2258             break;
2259           }
2260         }
2261         // Check if we actually found the matching operand.
2262         if (PrevCount == Used.count())
2263           return false;
2264       }
2265       return true;
2266     }
2267 
2268     /// \return Final vectorization factor for the node. Defined by the total
2269     /// number of vectorized scalars, including those, used several times in the
2270     /// entry and counted in the \a ReuseShuffleIndices, if any.
2271     unsigned getVectorFactor() const {
2272       if (!ReuseShuffleIndices.empty())
2273         return ReuseShuffleIndices.size();
2274       return Scalars.size();
2275     };
2276 
2277     /// A vector of scalars.
2278     ValueList Scalars;
2279 
2280     /// The Scalars are vectorized into this value. It is initialized to Null.
2281     Value *VectorizedValue = nullptr;
2282 
2283     /// Do we need to gather this sequence or vectorize it
2284     /// (either with vector instruction or with scatter/gather
2285     /// intrinsics for store/load)?
2286     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2287     EntryState State;
2288 
2289     /// Does this sequence require some shuffling?
2290     SmallVector<int, 4> ReuseShuffleIndices;
2291 
2292     /// Does this entry require reordering?
2293     SmallVector<unsigned, 4> ReorderIndices;
2294 
2295     /// Points back to the VectorizableTree.
2296     ///
2297     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2298     /// to be a pointer and needs to be able to initialize the child iterator.
2299     /// Thus we need a reference back to the container to translate the indices
2300     /// to entries.
2301     VecTreeTy &Container;
2302 
2303     /// The TreeEntry index containing the user of this entry.  We can actually
2304     /// have multiple users so the data structure is not truly a tree.
2305     SmallVector<EdgeInfo, 1> UserTreeIndices;
2306 
2307     /// The index of this treeEntry in VectorizableTree.
2308     int Idx = -1;
2309 
2310   private:
2311     /// The operands of each instruction in each lane Operands[op_index][lane].
2312     /// Note: This helps avoid the replication of the code that performs the
2313     /// reordering of operands during buildTree_rec() and vectorizeTree().
2314     SmallVector<ValueList, 2> Operands;
2315 
2316     /// The main/alternate instruction.
2317     Instruction *MainOp = nullptr;
2318     Instruction *AltOp = nullptr;
2319 
2320   public:
2321     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2322     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2323       if (Operands.size() < OpIdx + 1)
2324         Operands.resize(OpIdx + 1);
2325       assert(Operands[OpIdx].empty() && "Already resized?");
2326       assert(OpVL.size() <= Scalars.size() &&
2327              "Number of operands is greater than the number of scalars.");
2328       Operands[OpIdx].resize(OpVL.size());
2329       copy(OpVL, Operands[OpIdx].begin());
2330     }
2331 
2332     /// Set the operands of this bundle in their original order.
2333     void setOperandsInOrder() {
2334       assert(Operands.empty() && "Already initialized?");
2335       auto *I0 = cast<Instruction>(Scalars[0]);
2336       Operands.resize(I0->getNumOperands());
2337       unsigned NumLanes = Scalars.size();
2338       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2339            OpIdx != NumOperands; ++OpIdx) {
2340         Operands[OpIdx].resize(NumLanes);
2341         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2342           auto *I = cast<Instruction>(Scalars[Lane]);
2343           assert(I->getNumOperands() == NumOperands &&
2344                  "Expected same number of operands");
2345           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2346         }
2347       }
2348     }
2349 
2350     /// Reorders operands of the node to the given mask \p Mask.
2351     void reorderOperands(ArrayRef<int> Mask) {
2352       for (ValueList &Operand : Operands)
2353         reorderScalars(Operand, Mask);
2354     }
2355 
2356     /// \returns the \p OpIdx operand of this TreeEntry.
2357     ValueList &getOperand(unsigned OpIdx) {
2358       assert(OpIdx < Operands.size() && "Off bounds");
2359       return Operands[OpIdx];
2360     }
2361 
2362     /// \returns the \p OpIdx operand of this TreeEntry.
2363     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2364       assert(OpIdx < Operands.size() && "Off bounds");
2365       return Operands[OpIdx];
2366     }
2367 
2368     /// \returns the number of operands.
2369     unsigned getNumOperands() const { return Operands.size(); }
2370 
2371     /// \return the single \p OpIdx operand.
2372     Value *getSingleOperand(unsigned OpIdx) const {
2373       assert(OpIdx < Operands.size() && "Off bounds");
2374       assert(!Operands[OpIdx].empty() && "No operand available");
2375       return Operands[OpIdx][0];
2376     }
2377 
2378     /// Some of the instructions in the list have alternate opcodes.
2379     bool isAltShuffle() const { return MainOp != AltOp; }
2380 
2381     bool isOpcodeOrAlt(Instruction *I) const {
2382       unsigned CheckedOpcode = I->getOpcode();
2383       return (getOpcode() == CheckedOpcode ||
2384               getAltOpcode() == CheckedOpcode);
2385     }
2386 
2387     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2388     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2389     /// \p OpValue.
2390     Value *isOneOf(Value *Op) const {
2391       auto *I = dyn_cast<Instruction>(Op);
2392       if (I && isOpcodeOrAlt(I))
2393         return Op;
2394       return MainOp;
2395     }
2396 
2397     void setOperations(const InstructionsState &S) {
2398       MainOp = S.MainOp;
2399       AltOp = S.AltOp;
2400     }
2401 
2402     Instruction *getMainOp() const {
2403       return MainOp;
2404     }
2405 
2406     Instruction *getAltOp() const {
2407       return AltOp;
2408     }
2409 
2410     /// The main/alternate opcodes for the list of instructions.
2411     unsigned getOpcode() const {
2412       return MainOp ? MainOp->getOpcode() : 0;
2413     }
2414 
2415     unsigned getAltOpcode() const {
2416       return AltOp ? AltOp->getOpcode() : 0;
2417     }
2418 
2419     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2420     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2421     int findLaneForValue(Value *V) const {
2422       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2423       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2424       if (!ReorderIndices.empty())
2425         FoundLane = ReorderIndices[FoundLane];
2426       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2427       if (!ReuseShuffleIndices.empty()) {
2428         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2429                                   find(ReuseShuffleIndices, FoundLane));
2430       }
2431       return FoundLane;
2432     }
2433 
2434 #ifndef NDEBUG
2435     /// Debug printer.
2436     LLVM_DUMP_METHOD void dump() const {
2437       dbgs() << Idx << ".\n";
2438       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2439         dbgs() << "Operand " << OpI << ":\n";
2440         for (const Value *V : Operands[OpI])
2441           dbgs().indent(2) << *V << "\n";
2442       }
2443       dbgs() << "Scalars: \n";
2444       for (Value *V : Scalars)
2445         dbgs().indent(2) << *V << "\n";
2446       dbgs() << "State: ";
2447       switch (State) {
2448       case Vectorize:
2449         dbgs() << "Vectorize\n";
2450         break;
2451       case ScatterVectorize:
2452         dbgs() << "ScatterVectorize\n";
2453         break;
2454       case NeedToGather:
2455         dbgs() << "NeedToGather\n";
2456         break;
2457       }
2458       dbgs() << "MainOp: ";
2459       if (MainOp)
2460         dbgs() << *MainOp << "\n";
2461       else
2462         dbgs() << "NULL\n";
2463       dbgs() << "AltOp: ";
2464       if (AltOp)
2465         dbgs() << *AltOp << "\n";
2466       else
2467         dbgs() << "NULL\n";
2468       dbgs() << "VectorizedValue: ";
2469       if (VectorizedValue)
2470         dbgs() << *VectorizedValue << "\n";
2471       else
2472         dbgs() << "NULL\n";
2473       dbgs() << "ReuseShuffleIndices: ";
2474       if (ReuseShuffleIndices.empty())
2475         dbgs() << "Empty";
2476       else
2477         for (int ReuseIdx : ReuseShuffleIndices)
2478           dbgs() << ReuseIdx << ", ";
2479       dbgs() << "\n";
2480       dbgs() << "ReorderIndices: ";
2481       for (unsigned ReorderIdx : ReorderIndices)
2482         dbgs() << ReorderIdx << ", ";
2483       dbgs() << "\n";
2484       dbgs() << "UserTreeIndices: ";
2485       for (const auto &EInfo : UserTreeIndices)
2486         dbgs() << EInfo << ", ";
2487       dbgs() << "\n";
2488     }
2489 #endif
2490   };
2491 
2492 #ifndef NDEBUG
2493   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2494                      InstructionCost VecCost,
2495                      InstructionCost ScalarCost) const {
2496     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2497     dbgs() << "SLP: Costs:\n";
2498     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2499     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2500     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2501     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2502                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2503   }
2504 #endif
2505 
2506   /// Create a new VectorizableTree entry.
2507   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2508                           const InstructionsState &S,
2509                           const EdgeInfo &UserTreeIdx,
2510                           ArrayRef<int> ReuseShuffleIndices = None,
2511                           ArrayRef<unsigned> ReorderIndices = None) {
2512     TreeEntry::EntryState EntryState =
2513         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2514     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2515                         ReuseShuffleIndices, ReorderIndices);
2516   }
2517 
2518   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2519                           TreeEntry::EntryState EntryState,
2520                           Optional<ScheduleData *> Bundle,
2521                           const InstructionsState &S,
2522                           const EdgeInfo &UserTreeIdx,
2523                           ArrayRef<int> ReuseShuffleIndices = None,
2524                           ArrayRef<unsigned> ReorderIndices = None) {
2525     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2526             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2527            "Need to vectorize gather entry?");
2528     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2529     TreeEntry *Last = VectorizableTree.back().get();
2530     Last->Idx = VectorizableTree.size() - 1;
2531     Last->State = EntryState;
2532     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2533                                      ReuseShuffleIndices.end());
2534     if (ReorderIndices.empty()) {
2535       Last->Scalars.assign(VL.begin(), VL.end());
2536       Last->setOperations(S);
2537     } else {
2538       // Reorder scalars and build final mask.
2539       Last->Scalars.assign(VL.size(), nullptr);
2540       transform(ReorderIndices, Last->Scalars.begin(),
2541                 [VL](unsigned Idx) -> Value * {
2542                   if (Idx >= VL.size())
2543                     return UndefValue::get(VL.front()->getType());
2544                   return VL[Idx];
2545                 });
2546       InstructionsState S = getSameOpcode(Last->Scalars);
2547       Last->setOperations(S);
2548       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2549     }
2550     if (Last->State != TreeEntry::NeedToGather) {
2551       for (Value *V : VL) {
2552         assert(!getTreeEntry(V) && "Scalar already in tree!");
2553         ScalarToTreeEntry[V] = Last;
2554       }
2555       // Update the scheduler bundle to point to this TreeEntry.
2556       ScheduleData *BundleMember = Bundle.getValue();
2557       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2558               isVectorLikeInstWithConstOps(S.MainOp) ||
2559               doesNotNeedToSchedule(VL)) &&
2560              "Bundle and VL out of sync");
2561       if (BundleMember) {
2562         for (Value *V : VL) {
2563           if (doesNotNeedToBeScheduled(V))
2564             continue;
2565           assert(BundleMember && "Unexpected end of bundle.");
2566           BundleMember->TE = Last;
2567           BundleMember = BundleMember->NextInBundle;
2568         }
2569       }
2570       assert(!BundleMember && "Bundle and VL out of sync");
2571     } else {
2572       MustGather.insert(VL.begin(), VL.end());
2573     }
2574 
2575     if (UserTreeIdx.UserTE)
2576       Last->UserTreeIndices.push_back(UserTreeIdx);
2577 
2578     return Last;
2579   }
2580 
2581   /// -- Vectorization State --
2582   /// Holds all of the tree entries.
2583   TreeEntry::VecTreeTy VectorizableTree;
2584 
2585 #ifndef NDEBUG
2586   /// Debug printer.
2587   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2588     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2589       VectorizableTree[Id]->dump();
2590       dbgs() << "\n";
2591     }
2592   }
2593 #endif
2594 
2595   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2596 
2597   const TreeEntry *getTreeEntry(Value *V) const {
2598     return ScalarToTreeEntry.lookup(V);
2599   }
2600 
2601   /// Maps a specific scalar to its tree entry.
2602   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2603 
2604   /// Maps a value to the proposed vectorizable size.
2605   SmallDenseMap<Value *, unsigned> InstrElementSize;
2606 
2607   /// A list of scalars that we found that we need to keep as scalars.
2608   ValueSet MustGather;
2609 
2610   /// This POD struct describes one external user in the vectorized tree.
2611   struct ExternalUser {
2612     ExternalUser(Value *S, llvm::User *U, int L)
2613         : Scalar(S), User(U), Lane(L) {}
2614 
2615     // Which scalar in our function.
2616     Value *Scalar;
2617 
2618     // Which user that uses the scalar.
2619     llvm::User *User;
2620 
2621     // Which lane does the scalar belong to.
2622     int Lane;
2623   };
2624   using UserList = SmallVector<ExternalUser, 16>;
2625 
2626   /// Checks if two instructions may access the same memory.
2627   ///
2628   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2629   /// is invariant in the calling loop.
2630   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2631                  Instruction *Inst2) {
2632     // First check if the result is already in the cache.
2633     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2634     Optional<bool> &result = AliasCache[key];
2635     if (result.hasValue()) {
2636       return result.getValue();
2637     }
2638     bool aliased = true;
2639     if (Loc1.Ptr && isSimple(Inst1))
2640       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2641     // Store the result in the cache.
2642     result = aliased;
2643     return aliased;
2644   }
2645 
2646   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2647 
2648   /// Cache for alias results.
2649   /// TODO: consider moving this to the AliasAnalysis itself.
2650   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2651 
2652   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2653   // globally through SLP because we don't perform any action which
2654   // invalidates capture results.
2655   BatchAAResults BatchAA;
2656 
2657   /// Temporary store for deleted instructions. Instructions will be deleted
2658   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2659   /// ensure that there are no incorrect collisions in the AliasCache, which
2660   /// can happen if a new instruction is allocated at the same address as a
2661   /// previously deleted instruction.
2662   DenseSet<Instruction *> DeletedInstructions;
2663 
2664   /// Set of the instruction, being analyzed already for reductions.
2665   SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
2666 
2667   /// Set of hashes for the list of reduction values already being analyzed.
2668   DenseSet<size_t> AnalyzedReductionVals;
2669 
2670   /// A list of values that need to extracted out of the tree.
2671   /// This list holds pairs of (Internal Scalar : External User). External User
2672   /// can be nullptr, it means that this Internal Scalar will be used later,
2673   /// after vectorization.
2674   UserList ExternalUses;
2675 
2676   /// Values used only by @llvm.assume calls.
2677   SmallPtrSet<const Value *, 32> EphValues;
2678 
2679   /// Holds all of the instructions that we gathered.
2680   SetVector<Instruction *> GatherShuffleSeq;
2681 
2682   /// A list of blocks that we are going to CSE.
2683   SetVector<BasicBlock *> CSEBlocks;
2684 
2685   /// Contains all scheduling relevant data for an instruction.
2686   /// A ScheduleData either represents a single instruction or a member of an
2687   /// instruction bundle (= a group of instructions which is combined into a
2688   /// vector instruction).
2689   struct ScheduleData {
2690     // The initial value for the dependency counters. It means that the
2691     // dependencies are not calculated yet.
2692     enum { InvalidDeps = -1 };
2693 
2694     ScheduleData() = default;
2695 
2696     void init(int BlockSchedulingRegionID, Value *OpVal) {
2697       FirstInBundle = this;
2698       NextInBundle = nullptr;
2699       NextLoadStore = nullptr;
2700       IsScheduled = false;
2701       SchedulingRegionID = BlockSchedulingRegionID;
2702       clearDependencies();
2703       OpValue = OpVal;
2704       TE = nullptr;
2705     }
2706 
2707     /// Verify basic self consistency properties
2708     void verify() {
2709       if (hasValidDependencies()) {
2710         assert(UnscheduledDeps <= Dependencies && "invariant");
2711       } else {
2712         assert(UnscheduledDeps == Dependencies && "invariant");
2713       }
2714 
2715       if (IsScheduled) {
2716         assert(isSchedulingEntity() &&
2717                 "unexpected scheduled state");
2718         for (const ScheduleData *BundleMember = this; BundleMember;
2719              BundleMember = BundleMember->NextInBundle) {
2720           assert(BundleMember->hasValidDependencies() &&
2721                  BundleMember->UnscheduledDeps == 0 &&
2722                  "unexpected scheduled state");
2723           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2724                  "only bundle is marked scheduled");
2725         }
2726       }
2727 
2728       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2729              "all bundle members must be in same basic block");
2730     }
2731 
2732     /// Returns true if the dependency information has been calculated.
2733     /// Note that depenendency validity can vary between instructions within
2734     /// a single bundle.
2735     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2736 
2737     /// Returns true for single instructions and for bundle representatives
2738     /// (= the head of a bundle).
2739     bool isSchedulingEntity() const { return FirstInBundle == this; }
2740 
2741     /// Returns true if it represents an instruction bundle and not only a
2742     /// single instruction.
2743     bool isPartOfBundle() const {
2744       return NextInBundle != nullptr || FirstInBundle != this || TE;
2745     }
2746 
2747     /// Returns true if it is ready for scheduling, i.e. it has no more
2748     /// unscheduled depending instructions/bundles.
2749     bool isReady() const {
2750       assert(isSchedulingEntity() &&
2751              "can't consider non-scheduling entity for ready list");
2752       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2753     }
2754 
2755     /// Modifies the number of unscheduled dependencies for this instruction,
2756     /// and returns the number of remaining dependencies for the containing
2757     /// bundle.
2758     int incrementUnscheduledDeps(int Incr) {
2759       assert(hasValidDependencies() &&
2760              "increment of unscheduled deps would be meaningless");
2761       UnscheduledDeps += Incr;
2762       return FirstInBundle->unscheduledDepsInBundle();
2763     }
2764 
2765     /// Sets the number of unscheduled dependencies to the number of
2766     /// dependencies.
2767     void resetUnscheduledDeps() {
2768       UnscheduledDeps = Dependencies;
2769     }
2770 
2771     /// Clears all dependency information.
2772     void clearDependencies() {
2773       Dependencies = InvalidDeps;
2774       resetUnscheduledDeps();
2775       MemoryDependencies.clear();
2776       ControlDependencies.clear();
2777     }
2778 
2779     int unscheduledDepsInBundle() const {
2780       assert(isSchedulingEntity() && "only meaningful on the bundle");
2781       int Sum = 0;
2782       for (const ScheduleData *BundleMember = this; BundleMember;
2783            BundleMember = BundleMember->NextInBundle) {
2784         if (BundleMember->UnscheduledDeps == InvalidDeps)
2785           return InvalidDeps;
2786         Sum += BundleMember->UnscheduledDeps;
2787       }
2788       return Sum;
2789     }
2790 
2791     void dump(raw_ostream &os) const {
2792       if (!isSchedulingEntity()) {
2793         os << "/ " << *Inst;
2794       } else if (NextInBundle) {
2795         os << '[' << *Inst;
2796         ScheduleData *SD = NextInBundle;
2797         while (SD) {
2798           os << ';' << *SD->Inst;
2799           SD = SD->NextInBundle;
2800         }
2801         os << ']';
2802       } else {
2803         os << *Inst;
2804       }
2805     }
2806 
2807     Instruction *Inst = nullptr;
2808 
2809     /// Opcode of the current instruction in the schedule data.
2810     Value *OpValue = nullptr;
2811 
2812     /// The TreeEntry that this instruction corresponds to.
2813     TreeEntry *TE = nullptr;
2814 
2815     /// Points to the head in an instruction bundle (and always to this for
2816     /// single instructions).
2817     ScheduleData *FirstInBundle = nullptr;
2818 
2819     /// Single linked list of all instructions in a bundle. Null if it is a
2820     /// single instruction.
2821     ScheduleData *NextInBundle = nullptr;
2822 
2823     /// Single linked list of all memory instructions (e.g. load, store, call)
2824     /// in the block - until the end of the scheduling region.
2825     ScheduleData *NextLoadStore = nullptr;
2826 
2827     /// The dependent memory instructions.
2828     /// This list is derived on demand in calculateDependencies().
2829     SmallVector<ScheduleData *, 4> MemoryDependencies;
2830 
2831     /// List of instructions which this instruction could be control dependent
2832     /// on.  Allowing such nodes to be scheduled below this one could introduce
2833     /// a runtime fault which didn't exist in the original program.
2834     /// ex: this is a load or udiv following a readonly call which inf loops
2835     SmallVector<ScheduleData *, 4> ControlDependencies;
2836 
2837     /// This ScheduleData is in the current scheduling region if this matches
2838     /// the current SchedulingRegionID of BlockScheduling.
2839     int SchedulingRegionID = 0;
2840 
2841     /// Used for getting a "good" final ordering of instructions.
2842     int SchedulingPriority = 0;
2843 
2844     /// The number of dependencies. Constitutes of the number of users of the
2845     /// instruction plus the number of dependent memory instructions (if any).
2846     /// This value is calculated on demand.
2847     /// If InvalidDeps, the number of dependencies is not calculated yet.
2848     int Dependencies = InvalidDeps;
2849 
2850     /// The number of dependencies minus the number of dependencies of scheduled
2851     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2852     /// for scheduling.
2853     /// Note that this is negative as long as Dependencies is not calculated.
2854     int UnscheduledDeps = InvalidDeps;
2855 
2856     /// True if this instruction is scheduled (or considered as scheduled in the
2857     /// dry-run).
2858     bool IsScheduled = false;
2859   };
2860 
2861 #ifndef NDEBUG
2862   friend inline raw_ostream &operator<<(raw_ostream &os,
2863                                         const BoUpSLP::ScheduleData &SD) {
2864     SD.dump(os);
2865     return os;
2866   }
2867 #endif
2868 
2869   friend struct GraphTraits<BoUpSLP *>;
2870   friend struct DOTGraphTraits<BoUpSLP *>;
2871 
2872   /// Contains all scheduling data for a basic block.
2873   /// It does not schedules instructions, which are not memory read/write
2874   /// instructions and their operands are either constants, or arguments, or
2875   /// phis, or instructions from others blocks, or their users are phis or from
2876   /// the other blocks. The resulting vector instructions can be placed at the
2877   /// beginning of the basic block without scheduling (if operands does not need
2878   /// to be scheduled) or at the end of the block (if users are outside of the
2879   /// block). It allows to save some compile time and memory used by the
2880   /// compiler.
2881   /// ScheduleData is assigned for each instruction in between the boundaries of
2882   /// the tree entry, even for those, which are not part of the graph. It is
2883   /// required to correctly follow the dependencies between the instructions and
2884   /// their correct scheduling. The ScheduleData is not allocated for the
2885   /// instructions, which do not require scheduling, like phis, nodes with
2886   /// extractelements/insertelements only or nodes with instructions, with
2887   /// uses/operands outside of the block.
2888   struct BlockScheduling {
2889     BlockScheduling(BasicBlock *BB)
2890         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2891 
2892     void clear() {
2893       ReadyInsts.clear();
2894       ScheduleStart = nullptr;
2895       ScheduleEnd = nullptr;
2896       FirstLoadStoreInRegion = nullptr;
2897       LastLoadStoreInRegion = nullptr;
2898       RegionHasStackSave = false;
2899 
2900       // Reduce the maximum schedule region size by the size of the
2901       // previous scheduling run.
2902       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2903       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2904         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2905       ScheduleRegionSize = 0;
2906 
2907       // Make a new scheduling region, i.e. all existing ScheduleData is not
2908       // in the new region yet.
2909       ++SchedulingRegionID;
2910     }
2911 
2912     ScheduleData *getScheduleData(Instruction *I) {
2913       if (BB != I->getParent())
2914         // Avoid lookup if can't possibly be in map.
2915         return nullptr;
2916       ScheduleData *SD = ScheduleDataMap.lookup(I);
2917       if (SD && isInSchedulingRegion(SD))
2918         return SD;
2919       return nullptr;
2920     }
2921 
2922     ScheduleData *getScheduleData(Value *V) {
2923       if (auto *I = dyn_cast<Instruction>(V))
2924         return getScheduleData(I);
2925       return nullptr;
2926     }
2927 
2928     ScheduleData *getScheduleData(Value *V, Value *Key) {
2929       if (V == Key)
2930         return getScheduleData(V);
2931       auto I = ExtraScheduleDataMap.find(V);
2932       if (I != ExtraScheduleDataMap.end()) {
2933         ScheduleData *SD = I->second.lookup(Key);
2934         if (SD && isInSchedulingRegion(SD))
2935           return SD;
2936       }
2937       return nullptr;
2938     }
2939 
2940     bool isInSchedulingRegion(ScheduleData *SD) const {
2941       return SD->SchedulingRegionID == SchedulingRegionID;
2942     }
2943 
2944     /// Marks an instruction as scheduled and puts all dependent ready
2945     /// instructions into the ready-list.
2946     template <typename ReadyListType>
2947     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2948       SD->IsScheduled = true;
2949       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2950 
2951       for (ScheduleData *BundleMember = SD; BundleMember;
2952            BundleMember = BundleMember->NextInBundle) {
2953         if (BundleMember->Inst != BundleMember->OpValue)
2954           continue;
2955 
2956         // Handle the def-use chain dependencies.
2957 
2958         // Decrement the unscheduled counter and insert to ready list if ready.
2959         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2960           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2961             if (OpDef && OpDef->hasValidDependencies() &&
2962                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2963               // There are no more unscheduled dependencies after
2964               // decrementing, so we can put the dependent instruction
2965               // into the ready list.
2966               ScheduleData *DepBundle = OpDef->FirstInBundle;
2967               assert(!DepBundle->IsScheduled &&
2968                      "already scheduled bundle gets ready");
2969               ReadyList.insert(DepBundle);
2970               LLVM_DEBUG(dbgs()
2971                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2972             }
2973           });
2974         };
2975 
2976         // If BundleMember is a vector bundle, its operands may have been
2977         // reordered during buildTree(). We therefore need to get its operands
2978         // through the TreeEntry.
2979         if (TreeEntry *TE = BundleMember->TE) {
2980           // Need to search for the lane since the tree entry can be reordered.
2981           int Lane = std::distance(TE->Scalars.begin(),
2982                                    find(TE->Scalars, BundleMember->Inst));
2983           assert(Lane >= 0 && "Lane not set");
2984 
2985           // Since vectorization tree is being built recursively this assertion
2986           // ensures that the tree entry has all operands set before reaching
2987           // this code. Couple of exceptions known at the moment are extracts
2988           // where their second (immediate) operand is not added. Since
2989           // immediates do not affect scheduler behavior this is considered
2990           // okay.
2991           auto *In = BundleMember->Inst;
2992           assert(In &&
2993                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2994                   In->getNumOperands() == TE->getNumOperands()) &&
2995                  "Missed TreeEntry operands?");
2996           (void)In; // fake use to avoid build failure when assertions disabled
2997 
2998           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2999                OpIdx != NumOperands; ++OpIdx)
3000             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3001               DecrUnsched(I);
3002         } else {
3003           // If BundleMember is a stand-alone instruction, no operand reordering
3004           // has taken place, so we directly access its operands.
3005           for (Use &U : BundleMember->Inst->operands())
3006             if (auto *I = dyn_cast<Instruction>(U.get()))
3007               DecrUnsched(I);
3008         }
3009         // Handle the memory dependencies.
3010         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3011           if (MemoryDepSD->hasValidDependencies() &&
3012               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3013             // There are no more unscheduled dependencies after decrementing,
3014             // so we can put the dependent instruction into the ready list.
3015             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3016             assert(!DepBundle->IsScheduled &&
3017                    "already scheduled bundle gets ready");
3018             ReadyList.insert(DepBundle);
3019             LLVM_DEBUG(dbgs()
3020                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
3021           }
3022         }
3023         // Handle the control dependencies.
3024         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3025           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3026             // There are no more unscheduled dependencies after decrementing,
3027             // so we can put the dependent instruction into the ready list.
3028             ScheduleData *DepBundle = DepSD->FirstInBundle;
3029             assert(!DepBundle->IsScheduled &&
3030                    "already scheduled bundle gets ready");
3031             ReadyList.insert(DepBundle);
3032             LLVM_DEBUG(dbgs()
3033                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3034           }
3035         }
3036 
3037       }
3038     }
3039 
3040     /// Verify basic self consistency properties of the data structure.
3041     void verify() {
3042       if (!ScheduleStart)
3043         return;
3044 
3045       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3046              ScheduleStart->comesBefore(ScheduleEnd) &&
3047              "Not a valid scheduling region?");
3048 
3049       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3050         auto *SD = getScheduleData(I);
3051         if (!SD)
3052           continue;
3053         assert(isInSchedulingRegion(SD) &&
3054                "primary schedule data not in window?");
3055         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3056                "entire bundle in window!");
3057         (void)SD;
3058         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3059       }
3060 
3061       for (auto *SD : ReadyInsts) {
3062         assert(SD->isSchedulingEntity() && SD->isReady() &&
3063                "item in ready list not ready?");
3064         (void)SD;
3065       }
3066     }
3067 
3068     void doForAllOpcodes(Value *V,
3069                          function_ref<void(ScheduleData *SD)> Action) {
3070       if (ScheduleData *SD = getScheduleData(V))
3071         Action(SD);
3072       auto I = ExtraScheduleDataMap.find(V);
3073       if (I != ExtraScheduleDataMap.end())
3074         for (auto &P : I->second)
3075           if (isInSchedulingRegion(P.second))
3076             Action(P.second);
3077     }
3078 
3079     /// Put all instructions into the ReadyList which are ready for scheduling.
3080     template <typename ReadyListType>
3081     void initialFillReadyList(ReadyListType &ReadyList) {
3082       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3083         doForAllOpcodes(I, [&](ScheduleData *SD) {
3084           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3085               SD->isReady()) {
3086             ReadyList.insert(SD);
3087             LLVM_DEBUG(dbgs()
3088                        << "SLP:    initially in ready list: " << *SD << "\n");
3089           }
3090         });
3091       }
3092     }
3093 
3094     /// Build a bundle from the ScheduleData nodes corresponding to the
3095     /// scalar instruction for each lane.
3096     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3097 
3098     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3099     /// cyclic dependencies. This is only a dry-run, no instructions are
3100     /// actually moved at this stage.
3101     /// \returns the scheduling bundle. The returned Optional value is non-None
3102     /// if \p VL is allowed to be scheduled.
3103     Optional<ScheduleData *>
3104     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3105                       const InstructionsState &S);
3106 
3107     /// Un-bundles a group of instructions.
3108     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3109 
3110     /// Allocates schedule data chunk.
3111     ScheduleData *allocateScheduleDataChunks();
3112 
3113     /// Extends the scheduling region so that V is inside the region.
3114     /// \returns true if the region size is within the limit.
3115     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3116 
3117     /// Initialize the ScheduleData structures for new instructions in the
3118     /// scheduling region.
3119     void initScheduleData(Instruction *FromI, Instruction *ToI,
3120                           ScheduleData *PrevLoadStore,
3121                           ScheduleData *NextLoadStore);
3122 
3123     /// Updates the dependency information of a bundle and of all instructions/
3124     /// bundles which depend on the original bundle.
3125     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3126                                BoUpSLP *SLP);
3127 
3128     /// Sets all instruction in the scheduling region to un-scheduled.
3129     void resetSchedule();
3130 
3131     BasicBlock *BB;
3132 
3133     /// Simple memory allocation for ScheduleData.
3134     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3135 
3136     /// The size of a ScheduleData array in ScheduleDataChunks.
3137     int ChunkSize;
3138 
3139     /// The allocator position in the current chunk, which is the last entry
3140     /// of ScheduleDataChunks.
3141     int ChunkPos;
3142 
3143     /// Attaches ScheduleData to Instruction.
3144     /// Note that the mapping survives during all vectorization iterations, i.e.
3145     /// ScheduleData structures are recycled.
3146     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3147 
3148     /// Attaches ScheduleData to Instruction with the leading key.
3149     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3150         ExtraScheduleDataMap;
3151 
3152     /// The ready-list for scheduling (only used for the dry-run).
3153     SetVector<ScheduleData *> ReadyInsts;
3154 
3155     /// The first instruction of the scheduling region.
3156     Instruction *ScheduleStart = nullptr;
3157 
3158     /// The first instruction _after_ the scheduling region.
3159     Instruction *ScheduleEnd = nullptr;
3160 
3161     /// The first memory accessing instruction in the scheduling region
3162     /// (can be null).
3163     ScheduleData *FirstLoadStoreInRegion = nullptr;
3164 
3165     /// The last memory accessing instruction in the scheduling region
3166     /// (can be null).
3167     ScheduleData *LastLoadStoreInRegion = nullptr;
3168 
3169     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3170     /// region?  Used to optimize the dependence calculation for the
3171     /// common case where there isn't.
3172     bool RegionHasStackSave = false;
3173 
3174     /// The current size of the scheduling region.
3175     int ScheduleRegionSize = 0;
3176 
3177     /// The maximum size allowed for the scheduling region.
3178     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3179 
3180     /// The ID of the scheduling region. For a new vectorization iteration this
3181     /// is incremented which "removes" all ScheduleData from the region.
3182     /// Make sure that the initial SchedulingRegionID is greater than the
3183     /// initial SchedulingRegionID in ScheduleData (which is 0).
3184     int SchedulingRegionID = 1;
3185   };
3186 
3187   /// Attaches the BlockScheduling structures to basic blocks.
3188   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3189 
3190   /// Performs the "real" scheduling. Done before vectorization is actually
3191   /// performed in a basic block.
3192   void scheduleBlock(BlockScheduling *BS);
3193 
3194   /// List of users to ignore during scheduling and that don't need extracting.
3195   SmallPtrSet<Value *, 4> UserIgnoreList;
3196 
3197   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3198   /// sorted SmallVectors of unsigned.
3199   struct OrdersTypeDenseMapInfo {
3200     static OrdersType getEmptyKey() {
3201       OrdersType V;
3202       V.push_back(~1U);
3203       return V;
3204     }
3205 
3206     static OrdersType getTombstoneKey() {
3207       OrdersType V;
3208       V.push_back(~2U);
3209       return V;
3210     }
3211 
3212     static unsigned getHashValue(const OrdersType &V) {
3213       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3214     }
3215 
3216     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3217       return LHS == RHS;
3218     }
3219   };
3220 
3221   // Analysis and block reference.
3222   Function *F;
3223   ScalarEvolution *SE;
3224   TargetTransformInfo *TTI;
3225   TargetLibraryInfo *TLI;
3226   LoopInfo *LI;
3227   DominatorTree *DT;
3228   AssumptionCache *AC;
3229   DemandedBits *DB;
3230   const DataLayout *DL;
3231   OptimizationRemarkEmitter *ORE;
3232 
3233   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3234   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3235 
3236   /// Instruction builder to construct the vectorized tree.
3237   IRBuilder<> Builder;
3238 
3239   /// A map of scalar integer values to the smallest bit width with which they
3240   /// can legally be represented. The values map to (width, signed) pairs,
3241   /// where "width" indicates the minimum bit width and "signed" is True if the
3242   /// value must be signed-extended, rather than zero-extended, back to its
3243   /// original width.
3244   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3245 };
3246 
3247 } // end namespace slpvectorizer
3248 
3249 template <> struct GraphTraits<BoUpSLP *> {
3250   using TreeEntry = BoUpSLP::TreeEntry;
3251 
3252   /// NodeRef has to be a pointer per the GraphWriter.
3253   using NodeRef = TreeEntry *;
3254 
3255   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3256 
3257   /// Add the VectorizableTree to the index iterator to be able to return
3258   /// TreeEntry pointers.
3259   struct ChildIteratorType
3260       : public iterator_adaptor_base<
3261             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3262     ContainerTy &VectorizableTree;
3263 
3264     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3265                       ContainerTy &VT)
3266         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3267 
3268     NodeRef operator*() { return I->UserTE; }
3269   };
3270 
3271   static NodeRef getEntryNode(BoUpSLP &R) {
3272     return R.VectorizableTree[0].get();
3273   }
3274 
3275   static ChildIteratorType child_begin(NodeRef N) {
3276     return {N->UserTreeIndices.begin(), N->Container};
3277   }
3278 
3279   static ChildIteratorType child_end(NodeRef N) {
3280     return {N->UserTreeIndices.end(), N->Container};
3281   }
3282 
3283   /// For the node iterator we just need to turn the TreeEntry iterator into a
3284   /// TreeEntry* iterator so that it dereferences to NodeRef.
3285   class nodes_iterator {
3286     using ItTy = ContainerTy::iterator;
3287     ItTy It;
3288 
3289   public:
3290     nodes_iterator(const ItTy &It2) : It(It2) {}
3291     NodeRef operator*() { return It->get(); }
3292     nodes_iterator operator++() {
3293       ++It;
3294       return *this;
3295     }
3296     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3297   };
3298 
3299   static nodes_iterator nodes_begin(BoUpSLP *R) {
3300     return nodes_iterator(R->VectorizableTree.begin());
3301   }
3302 
3303   static nodes_iterator nodes_end(BoUpSLP *R) {
3304     return nodes_iterator(R->VectorizableTree.end());
3305   }
3306 
3307   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3308 };
3309 
3310 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3311   using TreeEntry = BoUpSLP::TreeEntry;
3312 
3313   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3314 
3315   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3316     std::string Str;
3317     raw_string_ostream OS(Str);
3318     if (isSplat(Entry->Scalars))
3319       OS << "<splat> ";
3320     for (auto V : Entry->Scalars) {
3321       OS << *V;
3322       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3323             return EU.Scalar == V;
3324           }))
3325         OS << " <extract>";
3326       OS << "\n";
3327     }
3328     return Str;
3329   }
3330 
3331   static std::string getNodeAttributes(const TreeEntry *Entry,
3332                                        const BoUpSLP *) {
3333     if (Entry->State == TreeEntry::NeedToGather)
3334       return "color=red";
3335     return "";
3336   }
3337 };
3338 
3339 } // end namespace llvm
3340 
3341 BoUpSLP::~BoUpSLP() {
3342   SmallVector<WeakTrackingVH> DeadInsts;
3343   for (auto *I : DeletedInstructions) {
3344     for (Use &U : I->operands()) {
3345       auto *Op = dyn_cast<Instruction>(U.get());
3346       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3347           wouldInstructionBeTriviallyDead(Op, TLI))
3348         DeadInsts.emplace_back(Op);
3349     }
3350     I->dropAllReferences();
3351   }
3352   for (auto *I : DeletedInstructions) {
3353     assert(I->use_empty() &&
3354            "trying to erase instruction with users.");
3355     I->eraseFromParent();
3356   }
3357 
3358   // Cleanup any dead scalar code feeding the vectorized instructions
3359   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3360 
3361 #ifdef EXPENSIVE_CHECKS
3362   // If we could guarantee that this call is not extremely slow, we could
3363   // remove the ifdef limitation (see PR47712).
3364   assert(!verifyFunction(*F, &dbgs()));
3365 #endif
3366 }
3367 
3368 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3369 /// contains original mask for the scalars reused in the node. Procedure
3370 /// transform this mask in accordance with the given \p Mask.
3371 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3372   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3373          "Expected non-empty mask.");
3374   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3375   Prev.swap(Reuses);
3376   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3377     if (Mask[I] != UndefMaskElem)
3378       Reuses[Mask[I]] = Prev[I];
3379 }
3380 
3381 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3382 /// the original order of the scalars. Procedure transforms the provided order
3383 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3384 /// identity order, \p Order is cleared.
3385 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3386   assert(!Mask.empty() && "Expected non-empty mask.");
3387   SmallVector<int> MaskOrder;
3388   if (Order.empty()) {
3389     MaskOrder.resize(Mask.size());
3390     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3391   } else {
3392     inversePermutation(Order, MaskOrder);
3393   }
3394   reorderReuses(MaskOrder, Mask);
3395   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3396     Order.clear();
3397     return;
3398   }
3399   Order.assign(Mask.size(), Mask.size());
3400   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3401     if (MaskOrder[I] != UndefMaskElem)
3402       Order[MaskOrder[I]] = I;
3403   fixupOrderingIndices(Order);
3404 }
3405 
3406 Optional<BoUpSLP::OrdersType>
3407 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3408   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3409   unsigned NumScalars = TE.Scalars.size();
3410   OrdersType CurrentOrder(NumScalars, NumScalars);
3411   SmallVector<int> Positions;
3412   SmallBitVector UsedPositions(NumScalars);
3413   const TreeEntry *STE = nullptr;
3414   // Try to find all gathered scalars that are gets vectorized in other
3415   // vectorize node. Here we can have only one single tree vector node to
3416   // correctly identify order of the gathered scalars.
3417   for (unsigned I = 0; I < NumScalars; ++I) {
3418     Value *V = TE.Scalars[I];
3419     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3420       continue;
3421     if (const auto *LocalSTE = getTreeEntry(V)) {
3422       if (!STE)
3423         STE = LocalSTE;
3424       else if (STE != LocalSTE)
3425         // Take the order only from the single vector node.
3426         return None;
3427       unsigned Lane =
3428           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3429       if (Lane >= NumScalars)
3430         return None;
3431       if (CurrentOrder[Lane] != NumScalars) {
3432         if (Lane != I)
3433           continue;
3434         UsedPositions.reset(CurrentOrder[Lane]);
3435       }
3436       // The partial identity (where only some elements of the gather node are
3437       // in the identity order) is good.
3438       CurrentOrder[Lane] = I;
3439       UsedPositions.set(I);
3440     }
3441   }
3442   // Need to keep the order if we have a vector entry and at least 2 scalars or
3443   // the vectorized entry has just 2 scalars.
3444   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3445     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3446       for (unsigned I = 0; I < NumScalars; ++I)
3447         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3448           return false;
3449       return true;
3450     };
3451     if (IsIdentityOrder(CurrentOrder)) {
3452       CurrentOrder.clear();
3453       return CurrentOrder;
3454     }
3455     auto *It = CurrentOrder.begin();
3456     for (unsigned I = 0; I < NumScalars;) {
3457       if (UsedPositions.test(I)) {
3458         ++I;
3459         continue;
3460       }
3461       if (*It == NumScalars) {
3462         *It = I;
3463         ++I;
3464       }
3465       ++It;
3466     }
3467     return CurrentOrder;
3468   }
3469   return None;
3470 }
3471 
3472 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
3473                             const DataLayout &DL, ScalarEvolution &SE,
3474                             SmallVectorImpl<unsigned> &SortedIndices) {
3475   assert(llvm::all_of(
3476              VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3477          "Expected list of pointer operands.");
3478   // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3479   // Ptr into, sort and return the sorted indices with values next to one
3480   // another.
3481   MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
3482   Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3483 
3484   unsigned Cnt = 1;
3485   for (Value *Ptr : VL.drop_front()) {
3486     bool Found = any_of(Bases, [&](auto &Base) {
3487       Optional<int> Diff =
3488           getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3489                           /*StrictCheck=*/true);
3490       if (!Diff)
3491         return false;
3492 
3493       Base.second.emplace_back(Ptr, *Diff, Cnt++);
3494       return true;
3495     });
3496 
3497     if (!Found) {
3498       // If we haven't found enough to usefully cluster, return early.
3499       if (Bases.size() > VL.size() / 2 - 1)
3500         return false;
3501 
3502       // Not found already - add a new Base
3503       Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3504     }
3505   }
3506 
3507   // For each of the bases sort the pointers by Offset and check if any of the
3508   // base become consecutively allocated.
3509   bool AnyConsecutive = false;
3510   for (auto &Base : Bases) {
3511     auto &Vec = Base.second;
3512     if (Vec.size() > 1) {
3513       llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3514                                 const std::tuple<Value *, int, unsigned> &Y) {
3515         return std::get<1>(X) < std::get<1>(Y);
3516       });
3517       int InitialOffset = std::get<1>(Vec[0]);
3518       AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3519         return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3520       });
3521     }
3522   }
3523 
3524   // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3525   SortedIndices.clear();
3526   if (!AnyConsecutive)
3527     return false;
3528 
3529   for (auto &Base : Bases) {
3530     for (auto &T : Base.second)
3531       SortedIndices.push_back(std::get<2>(T));
3532   }
3533 
3534   assert(SortedIndices.size() == VL.size() &&
3535          "Expected SortedIndices to be the size of VL");
3536   return true;
3537 }
3538 
3539 Optional<BoUpSLP::OrdersType>
3540 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3541   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3542   Type *ScalarTy = TE.Scalars[0]->getType();
3543 
3544   SmallVector<Value *> Ptrs;
3545   Ptrs.reserve(TE.Scalars.size());
3546   for (Value *V : TE.Scalars) {
3547     auto *L = dyn_cast<LoadInst>(V);
3548     if (!L || !L->isSimple())
3549       return None;
3550     Ptrs.push_back(L->getPointerOperand());
3551   }
3552 
3553   BoUpSLP::OrdersType Order;
3554   if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3555     return Order;
3556   return None;
3557 }
3558 
3559 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3560                                                          bool TopToBottom) {
3561   // No need to reorder if need to shuffle reuses, still need to shuffle the
3562   // node.
3563   if (!TE.ReuseShuffleIndices.empty())
3564     return None;
3565   if (TE.State == TreeEntry::Vectorize &&
3566       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3567        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3568       !TE.isAltShuffle())
3569     return TE.ReorderIndices;
3570   if (TE.State == TreeEntry::NeedToGather) {
3571     // TODO: add analysis of other gather nodes with extractelement
3572     // instructions and other values/instructions, not only undefs.
3573     if (((TE.getOpcode() == Instruction::ExtractElement &&
3574           !TE.isAltShuffle()) ||
3575          (all_of(TE.Scalars,
3576                  [](Value *V) {
3577                    return isa<UndefValue, ExtractElementInst>(V);
3578                  }) &&
3579           any_of(TE.Scalars,
3580                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3581         all_of(TE.Scalars,
3582                [](Value *V) {
3583                  auto *EE = dyn_cast<ExtractElementInst>(V);
3584                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3585                }) &&
3586         allSameType(TE.Scalars)) {
3587       // Check that gather of extractelements can be represented as
3588       // just a shuffle of a single vector.
3589       OrdersType CurrentOrder;
3590       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3591       if (Reuse || !CurrentOrder.empty()) {
3592         if (!CurrentOrder.empty())
3593           fixupOrderingIndices(CurrentOrder);
3594         return CurrentOrder;
3595       }
3596     }
3597     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3598       return CurrentOrder;
3599     if (TE.Scalars.size() >= 4)
3600       if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
3601         return Order;
3602   }
3603   return None;
3604 }
3605 
3606 void BoUpSLP::reorderTopToBottom() {
3607   // Maps VF to the graph nodes.
3608   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3609   // ExtractElement gather nodes which can be vectorized and need to handle
3610   // their ordering.
3611   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3612 
3613   // Maps a TreeEntry to the reorder indices of external users.
3614   DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
3615       ExternalUserReorderMap;
3616   // Find all reorderable nodes with the given VF.
3617   // Currently the are vectorized stores,loads,extracts + some gathering of
3618   // extracts.
3619   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders,
3620                               &ExternalUserReorderMap](
3621                                  const std::unique_ptr<TreeEntry> &TE) {
3622     // Look for external users that will probably be vectorized.
3623     SmallVector<OrdersType, 1> ExternalUserReorderIndices =
3624         findExternalStoreUsersReorderIndices(TE.get());
3625     if (!ExternalUserReorderIndices.empty()) {
3626       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3627       ExternalUserReorderMap.try_emplace(TE.get(),
3628                                          std::move(ExternalUserReorderIndices));
3629     }
3630 
3631     if (Optional<OrdersType> CurrentOrder =
3632             getReorderingData(*TE, /*TopToBottom=*/true)) {
3633       // Do not include ordering for nodes used in the alt opcode vectorization,
3634       // better to reorder them during bottom-to-top stage. If follow the order
3635       // here, it causes reordering of the whole graph though actually it is
3636       // profitable just to reorder the subgraph that starts from the alternate
3637       // opcode vectorization node. Such nodes already end-up with the shuffle
3638       // instruction and it is just enough to change this shuffle rather than
3639       // rotate the scalars for the whole graph.
3640       unsigned Cnt = 0;
3641       const TreeEntry *UserTE = TE.get();
3642       while (UserTE && Cnt < RecursionMaxDepth) {
3643         if (UserTE->UserTreeIndices.size() != 1)
3644           break;
3645         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3646               return EI.UserTE->State == TreeEntry::Vectorize &&
3647                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3648             }))
3649           return;
3650         if (UserTE->UserTreeIndices.empty())
3651           UserTE = nullptr;
3652         else
3653           UserTE = UserTE->UserTreeIndices.back().UserTE;
3654         ++Cnt;
3655       }
3656       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3657       if (TE->State != TreeEntry::Vectorize)
3658         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3659     }
3660   });
3661 
3662   // Reorder the graph nodes according to their vectorization factor.
3663   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3664        VF /= 2) {
3665     auto It = VFToOrderedEntries.find(VF);
3666     if (It == VFToOrderedEntries.end())
3667       continue;
3668     // Try to find the most profitable order. We just are looking for the most
3669     // used order and reorder scalar elements in the nodes according to this
3670     // mostly used order.
3671     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3672     // All operands are reordered and used only in this node - propagate the
3673     // most used order to the user node.
3674     MapVector<OrdersType, unsigned,
3675               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3676         OrdersUses;
3677     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3678     for (const TreeEntry *OpTE : OrderedEntries) {
3679       // No need to reorder this nodes, still need to extend and to use shuffle,
3680       // just need to merge reordering shuffle and the reuse shuffle.
3681       if (!OpTE->ReuseShuffleIndices.empty())
3682         continue;
3683       // Count number of orders uses.
3684       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3685         if (OpTE->State == TreeEntry::NeedToGather) {
3686           auto It = GathersToOrders.find(OpTE);
3687           if (It != GathersToOrders.end())
3688             return It->second;
3689         }
3690         return OpTE->ReorderIndices;
3691       }();
3692       // First consider the order of the external scalar users.
3693       auto It = ExternalUserReorderMap.find(OpTE);
3694       if (It != ExternalUserReorderMap.end()) {
3695         const auto &ExternalUserReorderIndices = It->second;
3696         for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
3697           ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
3698         // No other useful reorder data in this entry.
3699         if (Order.empty())
3700           continue;
3701       }
3702       // Stores actually store the mask, not the order, need to invert.
3703       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3704           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3705         SmallVector<int> Mask;
3706         inversePermutation(Order, Mask);
3707         unsigned E = Order.size();
3708         OrdersType CurrentOrder(E, E);
3709         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3710           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3711         });
3712         fixupOrderingIndices(CurrentOrder);
3713         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3714       } else {
3715         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3716       }
3717     }
3718     // Set order of the user node.
3719     if (OrdersUses.empty())
3720       continue;
3721     // Choose the most used order.
3722     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3723     unsigned Cnt = OrdersUses.front().second;
3724     for (const auto &Pair : drop_begin(OrdersUses)) {
3725       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3726         BestOrder = Pair.first;
3727         Cnt = Pair.second;
3728       }
3729     }
3730     // Set order of the user node.
3731     if (BestOrder.empty())
3732       continue;
3733     SmallVector<int> Mask;
3734     inversePermutation(BestOrder, Mask);
3735     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3736     unsigned E = BestOrder.size();
3737     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3738       return I < E ? static_cast<int>(I) : UndefMaskElem;
3739     });
3740     // Do an actual reordering, if profitable.
3741     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3742       // Just do the reordering for the nodes with the given VF.
3743       if (TE->Scalars.size() != VF) {
3744         if (TE->ReuseShuffleIndices.size() == VF) {
3745           // Need to reorder the reuses masks of the operands with smaller VF to
3746           // be able to find the match between the graph nodes and scalar
3747           // operands of the given node during vectorization/cost estimation.
3748           assert(all_of(TE->UserTreeIndices,
3749                         [VF, &TE](const EdgeInfo &EI) {
3750                           return EI.UserTE->Scalars.size() == VF ||
3751                                  EI.UserTE->Scalars.size() ==
3752                                      TE->Scalars.size();
3753                         }) &&
3754                  "All users must be of VF size.");
3755           // Update ordering of the operands with the smaller VF than the given
3756           // one.
3757           reorderReuses(TE->ReuseShuffleIndices, Mask);
3758         }
3759         continue;
3760       }
3761       if (TE->State == TreeEntry::Vectorize &&
3762           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3763               InsertElementInst>(TE->getMainOp()) &&
3764           !TE->isAltShuffle()) {
3765         // Build correct orders for extract{element,value}, loads and
3766         // stores.
3767         reorderOrder(TE->ReorderIndices, Mask);
3768         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3769           TE->reorderOperands(Mask);
3770       } else {
3771         // Reorder the node and its operands.
3772         TE->reorderOperands(Mask);
3773         assert(TE->ReorderIndices.empty() &&
3774                "Expected empty reorder sequence.");
3775         reorderScalars(TE->Scalars, Mask);
3776       }
3777       if (!TE->ReuseShuffleIndices.empty()) {
3778         // Apply reversed order to keep the original ordering of the reused
3779         // elements to avoid extra reorder indices shuffling.
3780         OrdersType CurrentOrder;
3781         reorderOrder(CurrentOrder, MaskOrder);
3782         SmallVector<int> NewReuses;
3783         inversePermutation(CurrentOrder, NewReuses);
3784         addMask(NewReuses, TE->ReuseShuffleIndices);
3785         TE->ReuseShuffleIndices.swap(NewReuses);
3786       }
3787     }
3788   }
3789 }
3790 
3791 bool BoUpSLP::canReorderOperands(
3792     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3793     ArrayRef<TreeEntry *> ReorderableGathers,
3794     SmallVectorImpl<TreeEntry *> &GatherOps) {
3795   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3796     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3797           return OpData.first == I &&
3798                  OpData.second->State == TreeEntry::Vectorize;
3799         }))
3800       continue;
3801     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3802       // Do not reorder if operand node is used by many user nodes.
3803       if (any_of(TE->UserTreeIndices,
3804                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3805         return false;
3806       // Add the node to the list of the ordered nodes with the identity
3807       // order.
3808       Edges.emplace_back(I, TE);
3809       continue;
3810     }
3811     ArrayRef<Value *> VL = UserTE->getOperand(I);
3812     TreeEntry *Gather = nullptr;
3813     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3814           assert(TE->State != TreeEntry::Vectorize &&
3815                  "Only non-vectorized nodes are expected.");
3816           if (TE->isSame(VL)) {
3817             Gather = TE;
3818             return true;
3819           }
3820           return false;
3821         }) > 1)
3822       return false;
3823     if (Gather)
3824       GatherOps.push_back(Gather);
3825   }
3826   return true;
3827 }
3828 
3829 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3830   SetVector<TreeEntry *> OrderedEntries;
3831   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3832   // Find all reorderable leaf nodes with the given VF.
3833   // Currently the are vectorized loads,extracts without alternate operands +
3834   // some gathering of extracts.
3835   SmallVector<TreeEntry *> NonVectorized;
3836   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3837                               &NonVectorized](
3838                                  const std::unique_ptr<TreeEntry> &TE) {
3839     if (TE->State != TreeEntry::Vectorize)
3840       NonVectorized.push_back(TE.get());
3841     if (Optional<OrdersType> CurrentOrder =
3842             getReorderingData(*TE, /*TopToBottom=*/false)) {
3843       OrderedEntries.insert(TE.get());
3844       if (TE->State != TreeEntry::Vectorize)
3845         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3846     }
3847   });
3848 
3849   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3850   // I.e., if the node has operands, that are reordered, try to make at least
3851   // one operand order in the natural order and reorder others + reorder the
3852   // user node itself.
3853   SmallPtrSet<const TreeEntry *, 4> Visited;
3854   while (!OrderedEntries.empty()) {
3855     // 1. Filter out only reordered nodes.
3856     // 2. If the entry has multiple uses - skip it and jump to the next node.
3857     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3858     SmallVector<TreeEntry *> Filtered;
3859     for (TreeEntry *TE : OrderedEntries) {
3860       if (!(TE->State == TreeEntry::Vectorize ||
3861             (TE->State == TreeEntry::NeedToGather &&
3862              GathersToOrders.count(TE))) ||
3863           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3864           !all_of(drop_begin(TE->UserTreeIndices),
3865                   [TE](const EdgeInfo &EI) {
3866                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3867                   }) ||
3868           !Visited.insert(TE).second) {
3869         Filtered.push_back(TE);
3870         continue;
3871       }
3872       // Build a map between user nodes and their operands order to speedup
3873       // search. The graph currently does not provide this dependency directly.
3874       for (EdgeInfo &EI : TE->UserTreeIndices) {
3875         TreeEntry *UserTE = EI.UserTE;
3876         auto It = Users.find(UserTE);
3877         if (It == Users.end())
3878           It = Users.insert({UserTE, {}}).first;
3879         It->second.emplace_back(EI.EdgeIdx, TE);
3880       }
3881     }
3882     // Erase filtered entries.
3883     for_each(Filtered,
3884              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3885     for (auto &Data : Users) {
3886       // Check that operands are used only in the User node.
3887       SmallVector<TreeEntry *> GatherOps;
3888       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3889                               GatherOps)) {
3890         for_each(Data.second,
3891                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3892                    OrderedEntries.remove(Op.second);
3893                  });
3894         continue;
3895       }
3896       // All operands are reordered and used only in this node - propagate the
3897       // most used order to the user node.
3898       MapVector<OrdersType, unsigned,
3899                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3900           OrdersUses;
3901       // Do the analysis for each tree entry only once, otherwise the order of
3902       // the same node my be considered several times, though might be not
3903       // profitable.
3904       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3905       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3906       for (const auto &Op : Data.second) {
3907         TreeEntry *OpTE = Op.second;
3908         if (!VisitedOps.insert(OpTE).second)
3909           continue;
3910         if (!OpTE->ReuseShuffleIndices.empty() ||
3911             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3912           continue;
3913         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3914           if (OpTE->State == TreeEntry::NeedToGather)
3915             return GathersToOrders.find(OpTE)->second;
3916           return OpTE->ReorderIndices;
3917         }();
3918         unsigned NumOps = count_if(
3919             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3920               return P.second == OpTE;
3921             });
3922         // Stores actually store the mask, not the order, need to invert.
3923         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3924             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3925           SmallVector<int> Mask;
3926           inversePermutation(Order, Mask);
3927           unsigned E = Order.size();
3928           OrdersType CurrentOrder(E, E);
3929           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3930             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3931           });
3932           fixupOrderingIndices(CurrentOrder);
3933           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3934               NumOps;
3935         } else {
3936           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3937         }
3938         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3939         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3940                                             const TreeEntry *TE) {
3941           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3942               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3943               (IgnoreReorder && TE->Idx == 0))
3944             return true;
3945           if (TE->State == TreeEntry::NeedToGather) {
3946             auto It = GathersToOrders.find(TE);
3947             if (It != GathersToOrders.end())
3948               return !It->second.empty();
3949             return true;
3950           }
3951           return false;
3952         };
3953         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3954           TreeEntry *UserTE = EI.UserTE;
3955           if (!VisitedUsers.insert(UserTE).second)
3956             continue;
3957           // May reorder user node if it requires reordering, has reused
3958           // scalars, is an alternate op vectorize node or its op nodes require
3959           // reordering.
3960           if (AllowsReordering(UserTE))
3961             continue;
3962           // Check if users allow reordering.
3963           // Currently look up just 1 level of operands to avoid increase of
3964           // the compile time.
3965           // Profitable to reorder if definitely more operands allow
3966           // reordering rather than those with natural order.
3967           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3968           if (static_cast<unsigned>(count_if(
3969                   Ops, [UserTE, &AllowsReordering](
3970                            const std::pair<unsigned, TreeEntry *> &Op) {
3971                     return AllowsReordering(Op.second) &&
3972                            all_of(Op.second->UserTreeIndices,
3973                                   [UserTE](const EdgeInfo &EI) {
3974                                     return EI.UserTE == UserTE;
3975                                   });
3976                   })) <= Ops.size() / 2)
3977             ++Res.first->second;
3978         }
3979       }
3980       // If no orders - skip current nodes and jump to the next one, if any.
3981       if (OrdersUses.empty()) {
3982         for_each(Data.second,
3983                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3984                    OrderedEntries.remove(Op.second);
3985                  });
3986         continue;
3987       }
3988       // Choose the best order.
3989       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3990       unsigned Cnt = OrdersUses.front().second;
3991       for (const auto &Pair : drop_begin(OrdersUses)) {
3992         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3993           BestOrder = Pair.first;
3994           Cnt = Pair.second;
3995         }
3996       }
3997       // Set order of the user node (reordering of operands and user nodes).
3998       if (BestOrder.empty()) {
3999         for_each(Data.second,
4000                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4001                    OrderedEntries.remove(Op.second);
4002                  });
4003         continue;
4004       }
4005       // Erase operands from OrderedEntries list and adjust their orders.
4006       VisitedOps.clear();
4007       SmallVector<int> Mask;
4008       inversePermutation(BestOrder, Mask);
4009       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4010       unsigned E = BestOrder.size();
4011       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4012         return I < E ? static_cast<int>(I) : UndefMaskElem;
4013       });
4014       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4015         TreeEntry *TE = Op.second;
4016         OrderedEntries.remove(TE);
4017         if (!VisitedOps.insert(TE).second)
4018           continue;
4019         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4020           // Just reorder reuses indices.
4021           reorderReuses(TE->ReuseShuffleIndices, Mask);
4022           continue;
4023         }
4024         // Gathers are processed separately.
4025         if (TE->State != TreeEntry::Vectorize)
4026           continue;
4027         assert((BestOrder.size() == TE->ReorderIndices.size() ||
4028                 TE->ReorderIndices.empty()) &&
4029                "Non-matching sizes of user/operand entries.");
4030         reorderOrder(TE->ReorderIndices, Mask);
4031       }
4032       // For gathers just need to reorder its scalars.
4033       for (TreeEntry *Gather : GatherOps) {
4034         assert(Gather->ReorderIndices.empty() &&
4035                "Unexpected reordering of gathers.");
4036         if (!Gather->ReuseShuffleIndices.empty()) {
4037           // Just reorder reuses indices.
4038           reorderReuses(Gather->ReuseShuffleIndices, Mask);
4039           continue;
4040         }
4041         reorderScalars(Gather->Scalars, Mask);
4042         OrderedEntries.remove(Gather);
4043       }
4044       // Reorder operands of the user node and set the ordering for the user
4045       // node itself.
4046       if (Data.first->State != TreeEntry::Vectorize ||
4047           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4048               Data.first->getMainOp()) ||
4049           Data.first->isAltShuffle())
4050         Data.first->reorderOperands(Mask);
4051       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4052           Data.first->isAltShuffle()) {
4053         reorderScalars(Data.first->Scalars, Mask);
4054         reorderOrder(Data.first->ReorderIndices, MaskOrder);
4055         if (Data.first->ReuseShuffleIndices.empty() &&
4056             !Data.first->ReorderIndices.empty() &&
4057             !Data.first->isAltShuffle()) {
4058           // Insert user node to the list to try to sink reordering deeper in
4059           // the graph.
4060           OrderedEntries.insert(Data.first);
4061         }
4062       } else {
4063         reorderOrder(Data.first->ReorderIndices, Mask);
4064       }
4065     }
4066   }
4067   // If the reordering is unnecessary, just remove the reorder.
4068   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4069       VectorizableTree.front()->ReuseShuffleIndices.empty())
4070     VectorizableTree.front()->ReorderIndices.clear();
4071 }
4072 
4073 void BoUpSLP::buildExternalUses(
4074     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4075   // Collect the values that we need to extract from the tree.
4076   for (auto &TEPtr : VectorizableTree) {
4077     TreeEntry *Entry = TEPtr.get();
4078 
4079     // No need to handle users of gathered values.
4080     if (Entry->State == TreeEntry::NeedToGather)
4081       continue;
4082 
4083     // For each lane:
4084     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4085       Value *Scalar = Entry->Scalars[Lane];
4086       int FoundLane = Entry->findLaneForValue(Scalar);
4087 
4088       // Check if the scalar is externally used as an extra arg.
4089       auto ExtI = ExternallyUsedValues.find(Scalar);
4090       if (ExtI != ExternallyUsedValues.end()) {
4091         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4092                           << Lane << " from " << *Scalar << ".\n");
4093         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4094       }
4095       for (User *U : Scalar->users()) {
4096         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4097 
4098         Instruction *UserInst = dyn_cast<Instruction>(U);
4099         if (!UserInst)
4100           continue;
4101 
4102         if (isDeleted(UserInst))
4103           continue;
4104 
4105         // Skip in-tree scalars that become vectors
4106         if (TreeEntry *UseEntry = getTreeEntry(U)) {
4107           Value *UseScalar = UseEntry->Scalars[0];
4108           // Some in-tree scalars will remain as scalar in vectorized
4109           // instructions. If that is the case, the one in Lane 0 will
4110           // be used.
4111           if (UseScalar != U ||
4112               UseEntry->State == TreeEntry::ScatterVectorize ||
4113               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4114             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4115                               << ".\n");
4116             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4117             continue;
4118           }
4119         }
4120 
4121         // Ignore users in the user ignore list.
4122         if (UserIgnoreList.contains(UserInst))
4123           continue;
4124 
4125         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4126                           << Lane << " from " << *Scalar << ".\n");
4127         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4128       }
4129     }
4130   }
4131 }
4132 
4133 DenseMap<Value *, SmallVector<StoreInst *, 4>>
4134 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4135   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
4136   for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4137     Value *V = TE->Scalars[Lane];
4138     // To save compilation time we don't visit if we have too many users.
4139     static constexpr unsigned UsersLimit = 4;
4140     if (V->hasNUsesOrMore(UsersLimit))
4141       break;
4142 
4143     // Collect stores per pointer object.
4144     for (User *U : V->users()) {
4145       auto *SI = dyn_cast<StoreInst>(U);
4146       if (SI == nullptr || !SI->isSimple() ||
4147           !isValidElementType(SI->getValueOperand()->getType()))
4148         continue;
4149       // Skip entry if already
4150       if (getTreeEntry(U))
4151         continue;
4152 
4153       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4154       auto &StoresVec = PtrToStoresMap[Ptr];
4155       // For now just keep one store per pointer object per lane.
4156       // TODO: Extend this to support multiple stores per pointer per lane
4157       if (StoresVec.size() > Lane)
4158         continue;
4159       // Skip if in different BBs.
4160       if (!StoresVec.empty() &&
4161           SI->getParent() != StoresVec.back()->getParent())
4162         continue;
4163       // Make sure that the stores are of the same type.
4164       if (!StoresVec.empty() &&
4165           SI->getValueOperand()->getType() !=
4166               StoresVec.back()->getValueOperand()->getType())
4167         continue;
4168       StoresVec.push_back(SI);
4169     }
4170   }
4171   return PtrToStoresMap;
4172 }
4173 
4174 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4175                             OrdersType &ReorderIndices) const {
4176   // We check whether the stores in StoreVec can form a vector by sorting them
4177   // and checking whether they are consecutive.
4178 
4179   // To avoid calling getPointersDiff() while sorting we create a vector of
4180   // pairs {store, offset from first} and sort this instead.
4181   SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4182   StoreInst *S0 = StoresVec[0];
4183   StoreOffsetVec[0] = {S0, 0};
4184   Type *S0Ty = S0->getValueOperand()->getType();
4185   Value *S0Ptr = S0->getPointerOperand();
4186   for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4187     StoreInst *SI = StoresVec[Idx];
4188     Optional<int> Diff =
4189         getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4190                         SI->getPointerOperand(), *DL, *SE,
4191                         /*StrictCheck=*/true);
4192     // We failed to compare the pointers so just abandon this StoresVec.
4193     if (!Diff)
4194       return false;
4195     StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4196   }
4197 
4198   // Sort the vector based on the pointers. We create a copy because we may
4199   // need the original later for calculating the reorder (shuffle) indices.
4200   stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4201                                  const std::pair<StoreInst *, int> &Pair2) {
4202     int Offset1 = Pair1.second;
4203     int Offset2 = Pair2.second;
4204     return Offset1 < Offset2;
4205   });
4206 
4207   // Check if the stores are consecutive by checking if their difference is 1.
4208   for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4209     if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4210       return false;
4211 
4212   // Calculate the shuffle indices according to their offset against the sorted
4213   // StoreOffsetVec.
4214   ReorderIndices.reserve(StoresVec.size());
4215   for (StoreInst *SI : StoresVec) {
4216     unsigned Idx = find_if(StoreOffsetVec,
4217                            [SI](const std::pair<StoreInst *, int> &Pair) {
4218                              return Pair.first == SI;
4219                            }) -
4220                    StoreOffsetVec.begin();
4221     ReorderIndices.push_back(Idx);
4222   }
4223   // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4224   // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4225   // same convention here.
4226   auto IsIdentityOrder = [](const OrdersType &Order) {
4227     for (unsigned Idx : seq<unsigned>(0, Order.size()))
4228       if (Idx != Order[Idx])
4229         return false;
4230     return true;
4231   };
4232   if (IsIdentityOrder(ReorderIndices))
4233     ReorderIndices.clear();
4234 
4235   return true;
4236 }
4237 
4238 #ifndef NDEBUG
4239 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
4240   for (unsigned Idx : Order)
4241     dbgs() << Idx << ", ";
4242   dbgs() << "\n";
4243 }
4244 #endif
4245 
4246 SmallVector<BoUpSLP::OrdersType, 1>
4247 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4248   unsigned NumLanes = TE->Scalars.size();
4249 
4250   DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
4251       collectUserStores(TE);
4252 
4253   // Holds the reorder indices for each candidate store vector that is a user of
4254   // the current TreeEntry.
4255   SmallVector<OrdersType, 1> ExternalReorderIndices;
4256 
4257   // Now inspect the stores collected per pointer and look for vectorization
4258   // candidates. For each candidate calculate the reorder index vector and push
4259   // it into `ExternalReorderIndices`
4260   for (const auto &Pair : PtrToStoresMap) {
4261     auto &StoresVec = Pair.second;
4262     // If we have fewer than NumLanes stores, then we can't form a vector.
4263     if (StoresVec.size() != NumLanes)
4264       continue;
4265 
4266     // If the stores are not consecutive then abandon this StoresVec.
4267     OrdersType ReorderIndices;
4268     if (!CanFormVector(StoresVec, ReorderIndices))
4269       continue;
4270 
4271     // We now know that the scalars in StoresVec can form a vector instruction,
4272     // so set the reorder indices.
4273     ExternalReorderIndices.push_back(ReorderIndices);
4274   }
4275   return ExternalReorderIndices;
4276 }
4277 
4278 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
4279                         ArrayRef<Value *> UserIgnoreLst) {
4280   deleteTree();
4281   UserIgnoreList.clear();
4282   UserIgnoreList.insert(UserIgnoreLst.begin(), UserIgnoreLst.end());
4283   if (!allSameType(Roots))
4284     return;
4285   buildTree_rec(Roots, 0, EdgeInfo());
4286 }
4287 
4288 namespace {
4289 /// Tracks the state we can represent the loads in the given sequence.
4290 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4291 } // anonymous namespace
4292 
4293 /// Checks if the given array of loads can be represented as a vectorized,
4294 /// scatter or just simple gather.
4295 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4296                                     const TargetTransformInfo &TTI,
4297                                     const DataLayout &DL, ScalarEvolution &SE,
4298                                     SmallVectorImpl<unsigned> &Order,
4299                                     SmallVectorImpl<Value *> &PointerOps) {
4300   // Check that a vectorized load would load the same memory as a scalar
4301   // load. For example, we don't want to vectorize loads that are smaller
4302   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4303   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4304   // from such a struct, we read/write packed bits disagreeing with the
4305   // unvectorized version.
4306   Type *ScalarTy = VL0->getType();
4307 
4308   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4309     return LoadsState::Gather;
4310 
4311   // Make sure all loads in the bundle are simple - we can't vectorize
4312   // atomic or volatile loads.
4313   PointerOps.clear();
4314   PointerOps.resize(VL.size());
4315   auto *POIter = PointerOps.begin();
4316   for (Value *V : VL) {
4317     auto *L = cast<LoadInst>(V);
4318     if (!L->isSimple())
4319       return LoadsState::Gather;
4320     *POIter = L->getPointerOperand();
4321     ++POIter;
4322   }
4323 
4324   Order.clear();
4325   // Check the order of pointer operands.
4326   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4327     Value *Ptr0;
4328     Value *PtrN;
4329     if (Order.empty()) {
4330       Ptr0 = PointerOps.front();
4331       PtrN = PointerOps.back();
4332     } else {
4333       Ptr0 = PointerOps[Order.front()];
4334       PtrN = PointerOps[Order.back()];
4335     }
4336     Optional<int> Diff =
4337         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4338     // Check that the sorted loads are consecutive.
4339     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4340       return LoadsState::Vectorize;
4341     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4342     for (Value *V : VL)
4343       CommonAlignment =
4344           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4345     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4346                                 CommonAlignment))
4347       return LoadsState::ScatterVectorize;
4348   }
4349 
4350   return LoadsState::Gather;
4351 }
4352 
4353 /// \return true if the specified list of values has only one instruction that
4354 /// requires scheduling, false otherwise.
4355 #ifndef NDEBUG
4356 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4357   Value *NeedsScheduling = nullptr;
4358   for (Value *V : VL) {
4359     if (doesNotNeedToBeScheduled(V))
4360       continue;
4361     if (!NeedsScheduling) {
4362       NeedsScheduling = V;
4363       continue;
4364     }
4365     return false;
4366   }
4367   return NeedsScheduling;
4368 }
4369 #endif
4370 
4371 /// Generates key/subkey pair for the given value to provide effective sorting
4372 /// of the values and better detection of the vectorizable values sequences. The
4373 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4374 /// and in values subgroups (subkeys).
4375 static std::pair<size_t, size_t> generateKeySubkey(
4376     Value *V, const TargetLibraryInfo *TLI,
4377     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4378     bool AllowAlternate) {
4379   hash_code Key = hash_value(V->getValueID() + 2);
4380   hash_code SubKey = hash_value(0);
4381   // Sort the loads by the distance between the pointers.
4382   if (auto *LI = dyn_cast<LoadInst>(V)) {
4383     Key = hash_combine(hash_value(Instruction::Load), Key);
4384     if (LI->isSimple())
4385       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4386     else
4387       SubKey = hash_value(LI);
4388   } else if (isVectorLikeInstWithConstOps(V)) {
4389     // Sort extracts by the vector operands.
4390     if (isa<ExtractElementInst, UndefValue>(V))
4391       Key = hash_value(Value::UndefValueVal + 1);
4392     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4393       if (!isUndefVector(EI->getVectorOperand()) &&
4394           !isa<UndefValue>(EI->getIndexOperand()))
4395         SubKey = hash_value(EI->getVectorOperand());
4396     }
4397   } else if (auto *I = dyn_cast<Instruction>(V)) {
4398     // Sort other instructions just by the opcodes except for CMPInst.
4399     // For CMP also sort by the predicate kind.
4400     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4401         isValidForAlternation(I->getOpcode())) {
4402       if (AllowAlternate)
4403         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4404       else
4405         Key = hash_combine(hash_value(I->getOpcode()), Key);
4406       SubKey = hash_combine(
4407           hash_value(I->getOpcode()), hash_value(I->getType()),
4408           hash_value(isa<BinaryOperator>(I)
4409                          ? I->getType()
4410                          : cast<CastInst>(I)->getOperand(0)->getType()));
4411     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4412       CmpInst::Predicate Pred = CI->getPredicate();
4413       if (CI->isCommutative())
4414         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4415       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4416       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4417                             hash_value(SwapPred),
4418                             hash_value(CI->getOperand(0)->getType()));
4419     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4420       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4421       if (isTriviallyVectorizable(ID))
4422         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4423       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4424         SubKey = hash_combine(hash_value(I->getOpcode()),
4425                               hash_value(Call->getCalledFunction()));
4426       else
4427         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4428       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4429         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4430                               hash_value(Op.Tag), SubKey);
4431     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4432       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4433         SubKey = hash_value(Gep->getPointerOperand());
4434       else
4435         SubKey = hash_value(Gep);
4436     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4437                !isa<ConstantInt>(I->getOperand(1))) {
4438       // Do not try to vectorize instructions with potentially high cost.
4439       SubKey = hash_value(I);
4440     } else {
4441       SubKey = hash_value(I->getOpcode());
4442     }
4443     Key = hash_combine(hash_value(I->getParent()), Key);
4444   }
4445   return std::make_pair(Key, SubKey);
4446 }
4447 
4448 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4449                             const EdgeInfo &UserTreeIdx) {
4450   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4451 
4452   SmallVector<int> ReuseShuffleIndicies;
4453   SmallVector<Value *> UniqueValues;
4454   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4455                                 &UserTreeIdx,
4456                                 this](const InstructionsState &S) {
4457     // Check that every instruction appears once in this bundle.
4458     DenseMap<Value *, unsigned> UniquePositions;
4459     for (Value *V : VL) {
4460       if (isConstant(V)) {
4461         ReuseShuffleIndicies.emplace_back(
4462             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4463         UniqueValues.emplace_back(V);
4464         continue;
4465       }
4466       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4467       ReuseShuffleIndicies.emplace_back(Res.first->second);
4468       if (Res.second)
4469         UniqueValues.emplace_back(V);
4470     }
4471     size_t NumUniqueScalarValues = UniqueValues.size();
4472     if (NumUniqueScalarValues == VL.size()) {
4473       ReuseShuffleIndicies.clear();
4474     } else {
4475       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4476       if (NumUniqueScalarValues <= 1 ||
4477           (UniquePositions.size() == 1 && all_of(UniqueValues,
4478                                                  [](Value *V) {
4479                                                    return isa<UndefValue>(V) ||
4480                                                           !isConstant(V);
4481                                                  })) ||
4482           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4483         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4484         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4485         return false;
4486       }
4487       VL = UniqueValues;
4488     }
4489     return true;
4490   };
4491 
4492   InstructionsState S = getSameOpcode(VL);
4493   if (Depth == RecursionMaxDepth) {
4494     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4495     if (TryToFindDuplicates(S))
4496       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4497                    ReuseShuffleIndicies);
4498     return;
4499   }
4500 
4501   // Don't handle scalable vectors
4502   if (S.getOpcode() == Instruction::ExtractElement &&
4503       isa<ScalableVectorType>(
4504           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4505     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4506     if (TryToFindDuplicates(S))
4507       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4508                    ReuseShuffleIndicies);
4509     return;
4510   }
4511 
4512   // Don't handle vectors.
4513   if (S.OpValue->getType()->isVectorTy() &&
4514       !isa<InsertElementInst>(S.OpValue)) {
4515     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4516     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4517     return;
4518   }
4519 
4520   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4521     if (SI->getValueOperand()->getType()->isVectorTy()) {
4522       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4523       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4524       return;
4525     }
4526 
4527   // If all of the operands are identical or constant we have a simple solution.
4528   // If we deal with insert/extract instructions, they all must have constant
4529   // indices, otherwise we should gather them, not try to vectorize.
4530   // If alternate op node with 2 elements with gathered operands - do not
4531   // vectorize.
4532   auto &&NotProfitableForVectorization = [&S, this,
4533                                           Depth](ArrayRef<Value *> VL) {
4534     if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
4535       return false;
4536     if (VectorizableTree.size() < MinTreeSize)
4537       return false;
4538     if (Depth >= RecursionMaxDepth - 1)
4539       return true;
4540     // Check if all operands are extracts, part of vector node or can build a
4541     // regular vectorize node.
4542     SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
4543     for (Value *V : VL) {
4544       auto *I = cast<Instruction>(V);
4545       InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
4546         return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
4547       }));
4548     }
4549     bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
4550     if ((IsCommutative &&
4551          std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
4552         (!IsCommutative &&
4553          all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
4554       return true;
4555     assert(VL.size() == 2 && "Expected only 2 alternate op instructions.");
4556     SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates;
4557     auto *I1 = cast<Instruction>(VL.front());
4558     auto *I2 = cast<Instruction>(VL.back());
4559     for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4560       Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4561                                              I2->getOperand(Op));
4562     if (count_if(
4563             Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4564               return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4565             }) >= S.MainOp->getNumOperands() / 2)
4566       return false;
4567     if (S.MainOp->getNumOperands() > 2)
4568       return true;
4569     if (IsCommutative) {
4570       // Check permuted operands.
4571       Candidates.clear();
4572       for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
4573         Candidates.emplace_back().emplace_back(I1->getOperand(Op),
4574                                                I2->getOperand((Op + 1) % E));
4575       if (any_of(
4576               Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
4577                 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
4578               }))
4579         return false;
4580     }
4581     return true;
4582   };
4583   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4584       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4585        !all_of(VL, isVectorLikeInstWithConstOps)) ||
4586       NotProfitableForVectorization(VL)) {
4587     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n");
4588     if (TryToFindDuplicates(S))
4589       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4590                    ReuseShuffleIndicies);
4591     return;
4592   }
4593 
4594   // We now know that this is a vector of instructions of the same type from
4595   // the same block.
4596 
4597   // Don't vectorize ephemeral values.
4598   for (Value *V : VL) {
4599     if (EphValues.count(V)) {
4600       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4601                         << ") is ephemeral.\n");
4602       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4603       return;
4604     }
4605   }
4606 
4607   // Check if this is a duplicate of another entry.
4608   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4609     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4610     if (!E->isSame(VL)) {
4611       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4612       if (TryToFindDuplicates(S))
4613         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4614                      ReuseShuffleIndicies);
4615       return;
4616     }
4617     // Record the reuse of the tree node.  FIXME, currently this is only used to
4618     // properly draw the graph rather than for the actual vectorization.
4619     E->UserTreeIndices.push_back(UserTreeIdx);
4620     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4621                       << ".\n");
4622     return;
4623   }
4624 
4625   // Check that none of the instructions in the bundle are already in the tree.
4626   for (Value *V : VL) {
4627     auto *I = dyn_cast<Instruction>(V);
4628     if (!I)
4629       continue;
4630     if (getTreeEntry(I)) {
4631       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4632                         << ") is already in tree.\n");
4633       if (TryToFindDuplicates(S))
4634         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4635                      ReuseShuffleIndicies);
4636       return;
4637     }
4638   }
4639 
4640   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4641   for (Value *V : VL) {
4642     if (UserIgnoreList.contains(V)) {
4643       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4644       if (TryToFindDuplicates(S))
4645         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4646                      ReuseShuffleIndicies);
4647       return;
4648     }
4649   }
4650 
4651   // Check that all of the users of the scalars that we want to vectorize are
4652   // schedulable.
4653   auto *VL0 = cast<Instruction>(S.OpValue);
4654   BasicBlock *BB = VL0->getParent();
4655 
4656   if (!DT->isReachableFromEntry(BB)) {
4657     // Don't go into unreachable blocks. They may contain instructions with
4658     // dependency cycles which confuse the final scheduling.
4659     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4660     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4661     return;
4662   }
4663 
4664   // Check that every instruction appears once in this bundle.
4665   if (!TryToFindDuplicates(S))
4666     return;
4667 
4668   auto &BSRef = BlocksSchedules[BB];
4669   if (!BSRef)
4670     BSRef = std::make_unique<BlockScheduling>(BB);
4671 
4672   BlockScheduling &BS = *BSRef;
4673 
4674   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4675 #ifdef EXPENSIVE_CHECKS
4676   // Make sure we didn't break any internal invariants
4677   BS.verify();
4678 #endif
4679   if (!Bundle) {
4680     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4681     assert((!BS.getScheduleData(VL0) ||
4682             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4683            "tryScheduleBundle should cancelScheduling on failure");
4684     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4685                  ReuseShuffleIndicies);
4686     return;
4687   }
4688   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4689 
4690   unsigned ShuffleOrOp = S.isAltShuffle() ?
4691                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4692   switch (ShuffleOrOp) {
4693     case Instruction::PHI: {
4694       auto *PH = cast<PHINode>(VL0);
4695 
4696       // Check for terminator values (e.g. invoke).
4697       for (Value *V : VL)
4698         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4699           Instruction *Term = dyn_cast<Instruction>(Incoming);
4700           if (Term && Term->isTerminator()) {
4701             LLVM_DEBUG(dbgs()
4702                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4703             BS.cancelScheduling(VL, VL0);
4704             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4705                          ReuseShuffleIndicies);
4706             return;
4707           }
4708         }
4709 
4710       TreeEntry *TE =
4711           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4712       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4713 
4714       // Keeps the reordered operands to avoid code duplication.
4715       SmallVector<ValueList, 2> OperandsVec;
4716       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4717         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4718           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4719           TE->setOperand(I, Operands);
4720           OperandsVec.push_back(Operands);
4721           continue;
4722         }
4723         ValueList Operands;
4724         // Prepare the operand vector.
4725         for (Value *V : VL)
4726           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4727               PH->getIncomingBlock(I)));
4728         TE->setOperand(I, Operands);
4729         OperandsVec.push_back(Operands);
4730       }
4731       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4732         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4733       return;
4734     }
4735     case Instruction::ExtractValue:
4736     case Instruction::ExtractElement: {
4737       OrdersType CurrentOrder;
4738       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4739       if (Reuse) {
4740         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4741         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4742                      ReuseShuffleIndicies);
4743         // This is a special case, as it does not gather, but at the same time
4744         // we are not extending buildTree_rec() towards the operands.
4745         ValueList Op0;
4746         Op0.assign(VL.size(), VL0->getOperand(0));
4747         VectorizableTree.back()->setOperand(0, Op0);
4748         return;
4749       }
4750       if (!CurrentOrder.empty()) {
4751         LLVM_DEBUG({
4752           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4753                     "with order";
4754           for (unsigned Idx : CurrentOrder)
4755             dbgs() << " " << Idx;
4756           dbgs() << "\n";
4757         });
4758         fixupOrderingIndices(CurrentOrder);
4759         // Insert new order with initial value 0, if it does not exist,
4760         // otherwise return the iterator to the existing one.
4761         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4762                      ReuseShuffleIndicies, CurrentOrder);
4763         // This is a special case, as it does not gather, but at the same time
4764         // we are not extending buildTree_rec() towards the operands.
4765         ValueList Op0;
4766         Op0.assign(VL.size(), VL0->getOperand(0));
4767         VectorizableTree.back()->setOperand(0, Op0);
4768         return;
4769       }
4770       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4771       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4772                    ReuseShuffleIndicies);
4773       BS.cancelScheduling(VL, VL0);
4774       return;
4775     }
4776     case Instruction::InsertElement: {
4777       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4778 
4779       // Check that we have a buildvector and not a shuffle of 2 or more
4780       // different vectors.
4781       ValueSet SourceVectors;
4782       for (Value *V : VL) {
4783         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4784         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4785       }
4786 
4787       if (count_if(VL, [&SourceVectors](Value *V) {
4788             return !SourceVectors.contains(V);
4789           }) >= 2) {
4790         // Found 2nd source vector - cancel.
4791         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4792                              "different source vectors.\n");
4793         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4794         BS.cancelScheduling(VL, VL0);
4795         return;
4796       }
4797 
4798       auto OrdCompare = [](const std::pair<int, int> &P1,
4799                            const std::pair<int, int> &P2) {
4800         return P1.first > P2.first;
4801       };
4802       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4803                     decltype(OrdCompare)>
4804           Indices(OrdCompare);
4805       for (int I = 0, E = VL.size(); I < E; ++I) {
4806         unsigned Idx = *getInsertIndex(VL[I]);
4807         Indices.emplace(Idx, I);
4808       }
4809       OrdersType CurrentOrder(VL.size(), VL.size());
4810       bool IsIdentity = true;
4811       for (int I = 0, E = VL.size(); I < E; ++I) {
4812         CurrentOrder[Indices.top().second] = I;
4813         IsIdentity &= Indices.top().second == I;
4814         Indices.pop();
4815       }
4816       if (IsIdentity)
4817         CurrentOrder.clear();
4818       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4819                                    None, CurrentOrder);
4820       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4821 
4822       constexpr int NumOps = 2;
4823       ValueList VectorOperands[NumOps];
4824       for (int I = 0; I < NumOps; ++I) {
4825         for (Value *V : VL)
4826           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4827 
4828         TE->setOperand(I, VectorOperands[I]);
4829       }
4830       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4831       return;
4832     }
4833     case Instruction::Load: {
4834       // Check that a vectorized load would load the same memory as a scalar
4835       // load. For example, we don't want to vectorize loads that are smaller
4836       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4837       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4838       // from such a struct, we read/write packed bits disagreeing with the
4839       // unvectorized version.
4840       SmallVector<Value *> PointerOps;
4841       OrdersType CurrentOrder;
4842       TreeEntry *TE = nullptr;
4843       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4844                                 PointerOps)) {
4845       case LoadsState::Vectorize:
4846         if (CurrentOrder.empty()) {
4847           // Original loads are consecutive and does not require reordering.
4848           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4849                             ReuseShuffleIndicies);
4850           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4851         } else {
4852           fixupOrderingIndices(CurrentOrder);
4853           // Need to reorder.
4854           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4855                             ReuseShuffleIndicies, CurrentOrder);
4856           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4857         }
4858         TE->setOperandsInOrder();
4859         break;
4860       case LoadsState::ScatterVectorize:
4861         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4862         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4863                           UserTreeIdx, ReuseShuffleIndicies);
4864         TE->setOperandsInOrder();
4865         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4866         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4867         break;
4868       case LoadsState::Gather:
4869         BS.cancelScheduling(VL, VL0);
4870         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4871                      ReuseShuffleIndicies);
4872 #ifndef NDEBUG
4873         Type *ScalarTy = VL0->getType();
4874         if (DL->getTypeSizeInBits(ScalarTy) !=
4875             DL->getTypeAllocSizeInBits(ScalarTy))
4876           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4877         else if (any_of(VL, [](Value *V) {
4878                    return !cast<LoadInst>(V)->isSimple();
4879                  }))
4880           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4881         else
4882           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4883 #endif // NDEBUG
4884         break;
4885       }
4886       return;
4887     }
4888     case Instruction::ZExt:
4889     case Instruction::SExt:
4890     case Instruction::FPToUI:
4891     case Instruction::FPToSI:
4892     case Instruction::FPExt:
4893     case Instruction::PtrToInt:
4894     case Instruction::IntToPtr:
4895     case Instruction::SIToFP:
4896     case Instruction::UIToFP:
4897     case Instruction::Trunc:
4898     case Instruction::FPTrunc:
4899     case Instruction::BitCast: {
4900       Type *SrcTy = VL0->getOperand(0)->getType();
4901       for (Value *V : VL) {
4902         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4903         if (Ty != SrcTy || !isValidElementType(Ty)) {
4904           BS.cancelScheduling(VL, VL0);
4905           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4906                        ReuseShuffleIndicies);
4907           LLVM_DEBUG(dbgs()
4908                      << "SLP: Gathering casts with different src types.\n");
4909           return;
4910         }
4911       }
4912       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4913                                    ReuseShuffleIndicies);
4914       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4915 
4916       TE->setOperandsInOrder();
4917       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4918         ValueList Operands;
4919         // Prepare the operand vector.
4920         for (Value *V : VL)
4921           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4922 
4923         buildTree_rec(Operands, Depth + 1, {TE, i});
4924       }
4925       return;
4926     }
4927     case Instruction::ICmp:
4928     case Instruction::FCmp: {
4929       // Check that all of the compares have the same predicate.
4930       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4931       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4932       Type *ComparedTy = VL0->getOperand(0)->getType();
4933       for (Value *V : VL) {
4934         CmpInst *Cmp = cast<CmpInst>(V);
4935         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4936             Cmp->getOperand(0)->getType() != ComparedTy) {
4937           BS.cancelScheduling(VL, VL0);
4938           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4939                        ReuseShuffleIndicies);
4940           LLVM_DEBUG(dbgs()
4941                      << "SLP: Gathering cmp with different predicate.\n");
4942           return;
4943         }
4944       }
4945 
4946       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4947                                    ReuseShuffleIndicies);
4948       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4949 
4950       ValueList Left, Right;
4951       if (cast<CmpInst>(VL0)->isCommutative()) {
4952         // Commutative predicate - collect + sort operands of the instructions
4953         // so that each side is more likely to have the same opcode.
4954         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4955         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4956       } else {
4957         // Collect operands - commute if it uses the swapped predicate.
4958         for (Value *V : VL) {
4959           auto *Cmp = cast<CmpInst>(V);
4960           Value *LHS = Cmp->getOperand(0);
4961           Value *RHS = Cmp->getOperand(1);
4962           if (Cmp->getPredicate() != P0)
4963             std::swap(LHS, RHS);
4964           Left.push_back(LHS);
4965           Right.push_back(RHS);
4966         }
4967       }
4968       TE->setOperand(0, Left);
4969       TE->setOperand(1, Right);
4970       buildTree_rec(Left, Depth + 1, {TE, 0});
4971       buildTree_rec(Right, Depth + 1, {TE, 1});
4972       return;
4973     }
4974     case Instruction::Select:
4975     case Instruction::FNeg:
4976     case Instruction::Add:
4977     case Instruction::FAdd:
4978     case Instruction::Sub:
4979     case Instruction::FSub:
4980     case Instruction::Mul:
4981     case Instruction::FMul:
4982     case Instruction::UDiv:
4983     case Instruction::SDiv:
4984     case Instruction::FDiv:
4985     case Instruction::URem:
4986     case Instruction::SRem:
4987     case Instruction::FRem:
4988     case Instruction::Shl:
4989     case Instruction::LShr:
4990     case Instruction::AShr:
4991     case Instruction::And:
4992     case Instruction::Or:
4993     case Instruction::Xor: {
4994       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4995                                    ReuseShuffleIndicies);
4996       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4997 
4998       // Sort operands of the instructions so that each side is more likely to
4999       // have the same opcode.
5000       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
5001         ValueList Left, Right;
5002         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5003         TE->setOperand(0, Left);
5004         TE->setOperand(1, Right);
5005         buildTree_rec(Left, Depth + 1, {TE, 0});
5006         buildTree_rec(Right, Depth + 1, {TE, 1});
5007         return;
5008       }
5009 
5010       TE->setOperandsInOrder();
5011       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5012         ValueList Operands;
5013         // Prepare the operand vector.
5014         for (Value *V : VL)
5015           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5016 
5017         buildTree_rec(Operands, Depth + 1, {TE, i});
5018       }
5019       return;
5020     }
5021     case Instruction::GetElementPtr: {
5022       // We don't combine GEPs with complicated (nested) indexing.
5023       for (Value *V : VL) {
5024         if (cast<Instruction>(V)->getNumOperands() != 2) {
5025           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
5026           BS.cancelScheduling(VL, VL0);
5027           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5028                        ReuseShuffleIndicies);
5029           return;
5030         }
5031       }
5032 
5033       // We can't combine several GEPs into one vector if they operate on
5034       // different types.
5035       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
5036       for (Value *V : VL) {
5037         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
5038         if (Ty0 != CurTy) {
5039           LLVM_DEBUG(dbgs()
5040                      << "SLP: not-vectorizable GEP (different types).\n");
5041           BS.cancelScheduling(VL, VL0);
5042           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5043                        ReuseShuffleIndicies);
5044           return;
5045         }
5046       }
5047 
5048       // We don't combine GEPs with non-constant indexes.
5049       Type *Ty1 = VL0->getOperand(1)->getType();
5050       for (Value *V : VL) {
5051         auto Op = cast<Instruction>(V)->getOperand(1);
5052         if (!isa<ConstantInt>(Op) ||
5053             (Op->getType() != Ty1 &&
5054              Op->getType()->getScalarSizeInBits() >
5055                  DL->getIndexSizeInBits(
5056                      V->getType()->getPointerAddressSpace()))) {
5057           LLVM_DEBUG(dbgs()
5058                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
5059           BS.cancelScheduling(VL, VL0);
5060           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5061                        ReuseShuffleIndicies);
5062           return;
5063         }
5064       }
5065 
5066       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5067                                    ReuseShuffleIndicies);
5068       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
5069       SmallVector<ValueList, 2> Operands(2);
5070       // Prepare the operand vector for pointer operands.
5071       for (Value *V : VL)
5072         Operands.front().push_back(
5073             cast<GetElementPtrInst>(V)->getPointerOperand());
5074       TE->setOperand(0, Operands.front());
5075       // Need to cast all indices to the same type before vectorization to
5076       // avoid crash.
5077       // Required to be able to find correct matches between different gather
5078       // nodes and reuse the vectorized values rather than trying to gather them
5079       // again.
5080       int IndexIdx = 1;
5081       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
5082       Type *Ty = all_of(VL,
5083                         [VL0Ty, IndexIdx](Value *V) {
5084                           return VL0Ty == cast<GetElementPtrInst>(V)
5085                                               ->getOperand(IndexIdx)
5086                                               ->getType();
5087                         })
5088                      ? VL0Ty
5089                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
5090                                             ->getPointerOperandType()
5091                                             ->getScalarType());
5092       // Prepare the operand vector.
5093       for (Value *V : VL) {
5094         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
5095         auto *CI = cast<ConstantInt>(Op);
5096         Operands.back().push_back(ConstantExpr::getIntegerCast(
5097             CI, Ty, CI->getValue().isSignBitSet()));
5098       }
5099       TE->setOperand(IndexIdx, Operands.back());
5100 
5101       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
5102         buildTree_rec(Operands[I], Depth + 1, {TE, I});
5103       return;
5104     }
5105     case Instruction::Store: {
5106       // Check if the stores are consecutive or if we need to swizzle them.
5107       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
5108       // Avoid types that are padded when being allocated as scalars, while
5109       // being packed together in a vector (such as i1).
5110       if (DL->getTypeSizeInBits(ScalarTy) !=
5111           DL->getTypeAllocSizeInBits(ScalarTy)) {
5112         BS.cancelScheduling(VL, VL0);
5113         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5114                      ReuseShuffleIndicies);
5115         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
5116         return;
5117       }
5118       // Make sure all stores in the bundle are simple - we can't vectorize
5119       // atomic or volatile stores.
5120       SmallVector<Value *, 4> PointerOps(VL.size());
5121       ValueList Operands(VL.size());
5122       auto POIter = PointerOps.begin();
5123       auto OIter = Operands.begin();
5124       for (Value *V : VL) {
5125         auto *SI = cast<StoreInst>(V);
5126         if (!SI->isSimple()) {
5127           BS.cancelScheduling(VL, VL0);
5128           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5129                        ReuseShuffleIndicies);
5130           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
5131           return;
5132         }
5133         *POIter = SI->getPointerOperand();
5134         *OIter = SI->getValueOperand();
5135         ++POIter;
5136         ++OIter;
5137       }
5138 
5139       OrdersType CurrentOrder;
5140       // Check the order of pointer operands.
5141       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
5142         Value *Ptr0;
5143         Value *PtrN;
5144         if (CurrentOrder.empty()) {
5145           Ptr0 = PointerOps.front();
5146           PtrN = PointerOps.back();
5147         } else {
5148           Ptr0 = PointerOps[CurrentOrder.front()];
5149           PtrN = PointerOps[CurrentOrder.back()];
5150         }
5151         Optional<int> Dist =
5152             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
5153         // Check that the sorted pointer operands are consecutive.
5154         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
5155           if (CurrentOrder.empty()) {
5156             // Original stores are consecutive and does not require reordering.
5157             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
5158                                          UserTreeIdx, ReuseShuffleIndicies);
5159             TE->setOperandsInOrder();
5160             buildTree_rec(Operands, Depth + 1, {TE, 0});
5161             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
5162           } else {
5163             fixupOrderingIndices(CurrentOrder);
5164             TreeEntry *TE =
5165                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5166                              ReuseShuffleIndicies, CurrentOrder);
5167             TE->setOperandsInOrder();
5168             buildTree_rec(Operands, Depth + 1, {TE, 0});
5169             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
5170           }
5171           return;
5172         }
5173       }
5174 
5175       BS.cancelScheduling(VL, VL0);
5176       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5177                    ReuseShuffleIndicies);
5178       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
5179       return;
5180     }
5181     case Instruction::Call: {
5182       // Check if the calls are all to the same vectorizable intrinsic or
5183       // library function.
5184       CallInst *CI = cast<CallInst>(VL0);
5185       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5186 
5187       VFShape Shape = VFShape::get(
5188           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
5189           false /*HasGlobalPred*/);
5190       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5191 
5192       if (!VecFunc && !isTriviallyVectorizable(ID)) {
5193         BS.cancelScheduling(VL, VL0);
5194         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5195                      ReuseShuffleIndicies);
5196         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
5197         return;
5198       }
5199       Function *F = CI->getCalledFunction();
5200       unsigned NumArgs = CI->arg_size();
5201       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
5202       for (unsigned j = 0; j != NumArgs; ++j)
5203         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
5204           ScalarArgs[j] = CI->getArgOperand(j);
5205       for (Value *V : VL) {
5206         CallInst *CI2 = dyn_cast<CallInst>(V);
5207         if (!CI2 || CI2->getCalledFunction() != F ||
5208             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
5209             (VecFunc &&
5210              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
5211             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
5212           BS.cancelScheduling(VL, VL0);
5213           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5214                        ReuseShuffleIndicies);
5215           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
5216                             << "\n");
5217           return;
5218         }
5219         // Some intrinsics have scalar arguments and should be same in order for
5220         // them to be vectorized.
5221         for (unsigned j = 0; j != NumArgs; ++j) {
5222           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
5223             Value *A1J = CI2->getArgOperand(j);
5224             if (ScalarArgs[j] != A1J) {
5225               BS.cancelScheduling(VL, VL0);
5226               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5227                            ReuseShuffleIndicies);
5228               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
5229                                 << " argument " << ScalarArgs[j] << "!=" << A1J
5230                                 << "\n");
5231               return;
5232             }
5233           }
5234         }
5235         // Verify that the bundle operands are identical between the two calls.
5236         if (CI->hasOperandBundles() &&
5237             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
5238                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
5239                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
5240           BS.cancelScheduling(VL, VL0);
5241           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5242                        ReuseShuffleIndicies);
5243           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
5244                             << *CI << "!=" << *V << '\n');
5245           return;
5246         }
5247       }
5248 
5249       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5250                                    ReuseShuffleIndicies);
5251       TE->setOperandsInOrder();
5252       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
5253         // For scalar operands no need to to create an entry since no need to
5254         // vectorize it.
5255         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
5256           continue;
5257         ValueList Operands;
5258         // Prepare the operand vector.
5259         for (Value *V : VL) {
5260           auto *CI2 = cast<CallInst>(V);
5261           Operands.push_back(CI2->getArgOperand(i));
5262         }
5263         buildTree_rec(Operands, Depth + 1, {TE, i});
5264       }
5265       return;
5266     }
5267     case Instruction::ShuffleVector: {
5268       // If this is not an alternate sequence of opcode like add-sub
5269       // then do not vectorize this instruction.
5270       if (!S.isAltShuffle()) {
5271         BS.cancelScheduling(VL, VL0);
5272         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5273                      ReuseShuffleIndicies);
5274         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
5275         return;
5276       }
5277       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
5278                                    ReuseShuffleIndicies);
5279       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
5280 
5281       // Reorder operands if reordering would enable vectorization.
5282       auto *CI = dyn_cast<CmpInst>(VL0);
5283       if (isa<BinaryOperator>(VL0) || CI) {
5284         ValueList Left, Right;
5285         if (!CI || all_of(VL, [](Value *V) {
5286               return cast<CmpInst>(V)->isCommutative();
5287             })) {
5288           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
5289         } else {
5290           CmpInst::Predicate P0 = CI->getPredicate();
5291           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
5292           assert(P0 != AltP0 &&
5293                  "Expected different main/alternate predicates.");
5294           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5295           Value *BaseOp0 = VL0->getOperand(0);
5296           Value *BaseOp1 = VL0->getOperand(1);
5297           // Collect operands - commute if it uses the swapped predicate or
5298           // alternate operation.
5299           for (Value *V : VL) {
5300             auto *Cmp = cast<CmpInst>(V);
5301             Value *LHS = Cmp->getOperand(0);
5302             Value *RHS = Cmp->getOperand(1);
5303             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
5304             if (P0 == AltP0Swapped) {
5305               if (CI != Cmp && S.AltOp != Cmp &&
5306                   ((P0 == CurrentPred &&
5307                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
5308                    (AltP0 == CurrentPred &&
5309                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
5310                 std::swap(LHS, RHS);
5311             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
5312               std::swap(LHS, RHS);
5313             }
5314             Left.push_back(LHS);
5315             Right.push_back(RHS);
5316           }
5317         }
5318         TE->setOperand(0, Left);
5319         TE->setOperand(1, Right);
5320         buildTree_rec(Left, Depth + 1, {TE, 0});
5321         buildTree_rec(Right, Depth + 1, {TE, 1});
5322         return;
5323       }
5324 
5325       TE->setOperandsInOrder();
5326       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
5327         ValueList Operands;
5328         // Prepare the operand vector.
5329         for (Value *V : VL)
5330           Operands.push_back(cast<Instruction>(V)->getOperand(i));
5331 
5332         buildTree_rec(Operands, Depth + 1, {TE, i});
5333       }
5334       return;
5335     }
5336     default:
5337       BS.cancelScheduling(VL, VL0);
5338       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
5339                    ReuseShuffleIndicies);
5340       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
5341       return;
5342   }
5343 }
5344 
5345 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5346   unsigned N = 1;
5347   Type *EltTy = T;
5348 
5349   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5350          isa<VectorType>(EltTy)) {
5351     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5352       // Check that struct is homogeneous.
5353       for (const auto *Ty : ST->elements())
5354         if (Ty != *ST->element_begin())
5355           return 0;
5356       N *= ST->getNumElements();
5357       EltTy = *ST->element_begin();
5358     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5359       N *= AT->getNumElements();
5360       EltTy = AT->getElementType();
5361     } else {
5362       auto *VT = cast<FixedVectorType>(EltTy);
5363       N *= VT->getNumElements();
5364       EltTy = VT->getElementType();
5365     }
5366   }
5367 
5368   if (!isValidElementType(EltTy))
5369     return 0;
5370   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5371   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5372     return 0;
5373   return N;
5374 }
5375 
5376 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5377                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5378   const auto *It = find_if(VL, [](Value *V) {
5379     return isa<ExtractElementInst, ExtractValueInst>(V);
5380   });
5381   assert(It != VL.end() && "Expected at least one extract instruction.");
5382   auto *E0 = cast<Instruction>(*It);
5383   assert(all_of(VL,
5384                 [](Value *V) {
5385                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5386                       V);
5387                 }) &&
5388          "Invalid opcode");
5389   // Check if all of the extracts come from the same vector and from the
5390   // correct offset.
5391   Value *Vec = E0->getOperand(0);
5392 
5393   CurrentOrder.clear();
5394 
5395   // We have to extract from a vector/aggregate with the same number of elements.
5396   unsigned NElts;
5397   if (E0->getOpcode() == Instruction::ExtractValue) {
5398     const DataLayout &DL = E0->getModule()->getDataLayout();
5399     NElts = canMapToVector(Vec->getType(), DL);
5400     if (!NElts)
5401       return false;
5402     // Check if load can be rewritten as load of vector.
5403     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5404     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5405       return false;
5406   } else {
5407     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5408   }
5409 
5410   if (NElts != VL.size())
5411     return false;
5412 
5413   // Check that all of the indices extract from the correct offset.
5414   bool ShouldKeepOrder = true;
5415   unsigned E = VL.size();
5416   // Assign to all items the initial value E + 1 so we can check if the extract
5417   // instruction index was used already.
5418   // Also, later we can check that all the indices are used and we have a
5419   // consecutive access in the extract instructions, by checking that no
5420   // element of CurrentOrder still has value E + 1.
5421   CurrentOrder.assign(E, E);
5422   unsigned I = 0;
5423   for (; I < E; ++I) {
5424     auto *Inst = dyn_cast<Instruction>(VL[I]);
5425     if (!Inst)
5426       continue;
5427     if (Inst->getOperand(0) != Vec)
5428       break;
5429     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5430       if (isa<UndefValue>(EE->getIndexOperand()))
5431         continue;
5432     Optional<unsigned> Idx = getExtractIndex(Inst);
5433     if (!Idx)
5434       break;
5435     const unsigned ExtIdx = *Idx;
5436     if (ExtIdx != I) {
5437       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5438         break;
5439       ShouldKeepOrder = false;
5440       CurrentOrder[ExtIdx] = I;
5441     } else {
5442       if (CurrentOrder[I] != E)
5443         break;
5444       CurrentOrder[I] = I;
5445     }
5446   }
5447   if (I < E) {
5448     CurrentOrder.clear();
5449     return false;
5450   }
5451   if (ShouldKeepOrder)
5452     CurrentOrder.clear();
5453 
5454   return ShouldKeepOrder;
5455 }
5456 
5457 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5458                                     ArrayRef<Value *> VectorizedVals) const {
5459   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5460          all_of(I->users(), [this](User *U) {
5461            return ScalarToTreeEntry.count(U) > 0 ||
5462                   isVectorLikeInstWithConstOps(U) ||
5463                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5464          });
5465 }
5466 
5467 static std::pair<InstructionCost, InstructionCost>
5468 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5469                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5470   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5471 
5472   // Calculate the cost of the scalar and vector calls.
5473   SmallVector<Type *, 4> VecTys;
5474   for (Use &Arg : CI->args())
5475     VecTys.push_back(
5476         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5477   FastMathFlags FMF;
5478   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5479     FMF = FPCI->getFastMathFlags();
5480   SmallVector<const Value *> Arguments(CI->args());
5481   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5482                                     dyn_cast<IntrinsicInst>(CI));
5483   auto IntrinsicCost =
5484     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5485 
5486   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5487                                      VecTy->getNumElements())),
5488                             false /*HasGlobalPred*/);
5489   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5490   auto LibCost = IntrinsicCost;
5491   if (!CI->isNoBuiltin() && VecFunc) {
5492     // Calculate the cost of the vector library call.
5493     // If the corresponding vector call is cheaper, return its cost.
5494     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5495                                     TTI::TCK_RecipThroughput);
5496   }
5497   return {IntrinsicCost, LibCost};
5498 }
5499 
5500 /// Compute the cost of creating a vector of type \p VecTy containing the
5501 /// extracted values from \p VL.
5502 static InstructionCost
5503 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5504                    TargetTransformInfo::ShuffleKind ShuffleKind,
5505                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5506   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5507 
5508   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5509       VecTy->getNumElements() < NumOfParts)
5510     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5511 
5512   bool AllConsecutive = true;
5513   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5514   unsigned Idx = -1;
5515   InstructionCost Cost = 0;
5516 
5517   // Process extracts in blocks of EltsPerVector to check if the source vector
5518   // operand can be re-used directly. If not, add the cost of creating a shuffle
5519   // to extract the values into a vector register.
5520   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5521   for (auto *V : VL) {
5522     ++Idx;
5523 
5524     // Need to exclude undefs from analysis.
5525     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5526       continue;
5527 
5528     // Reached the start of a new vector registers.
5529     if (Idx % EltsPerVector == 0) {
5530       RegMask.assign(EltsPerVector, UndefMaskElem);
5531       AllConsecutive = true;
5532       continue;
5533     }
5534 
5535     // Check all extracts for a vector register on the target directly
5536     // extract values in order.
5537     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5538     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5539       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5540       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5541                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5542       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5543     }
5544 
5545     if (AllConsecutive)
5546       continue;
5547 
5548     // Skip all indices, except for the last index per vector block.
5549     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5550       continue;
5551 
5552     // If we have a series of extracts which are not consecutive and hence
5553     // cannot re-use the source vector register directly, compute the shuffle
5554     // cost to extract the vector with EltsPerVector elements.
5555     Cost += TTI.getShuffleCost(
5556         TargetTransformInfo::SK_PermuteSingleSrc,
5557         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5558   }
5559   return Cost;
5560 }
5561 
5562 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5563 /// operations operands.
5564 static void
5565 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5566                       ArrayRef<int> ReusesIndices,
5567                       const function_ref<bool(Instruction *)> IsAltOp,
5568                       SmallVectorImpl<int> &Mask,
5569                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5570                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5571   unsigned Sz = VL.size();
5572   Mask.assign(Sz, UndefMaskElem);
5573   SmallVector<int> OrderMask;
5574   if (!ReorderIndices.empty())
5575     inversePermutation(ReorderIndices, OrderMask);
5576   for (unsigned I = 0; I < Sz; ++I) {
5577     unsigned Idx = I;
5578     if (!ReorderIndices.empty())
5579       Idx = OrderMask[I];
5580     auto *OpInst = cast<Instruction>(VL[Idx]);
5581     if (IsAltOp(OpInst)) {
5582       Mask[I] = Sz + Idx;
5583       if (AltScalars)
5584         AltScalars->push_back(OpInst);
5585     } else {
5586       Mask[I] = Idx;
5587       if (OpScalars)
5588         OpScalars->push_back(OpInst);
5589     }
5590   }
5591   if (!ReusesIndices.empty()) {
5592     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5593     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5594       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5595     });
5596     Mask.swap(NewMask);
5597   }
5598 }
5599 
5600 /// Checks if the specified instruction \p I is an alternate operation for the
5601 /// given \p MainOp and \p AltOp instructions.
5602 static bool isAlternateInstruction(const Instruction *I,
5603                                    const Instruction *MainOp,
5604                                    const Instruction *AltOp) {
5605   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5606     auto *AltCI0 = cast<CmpInst>(AltOp);
5607     auto *CI = cast<CmpInst>(I);
5608     CmpInst::Predicate P0 = CI0->getPredicate();
5609     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5610     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5611     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5612     CmpInst::Predicate CurrentPred = CI->getPredicate();
5613     if (P0 == AltP0Swapped)
5614       return I == AltCI0 ||
5615              (I != MainOp &&
5616               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5617                                    CI->getOperand(0), CI->getOperand(1)));
5618     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5619   }
5620   return I->getOpcode() == AltOp->getOpcode();
5621 }
5622 
5623 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5624                                       ArrayRef<Value *> VectorizedVals) {
5625   ArrayRef<Value*> VL = E->Scalars;
5626 
5627   Type *ScalarTy = VL[0]->getType();
5628   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5629     ScalarTy = SI->getValueOperand()->getType();
5630   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5631     ScalarTy = CI->getOperand(0)->getType();
5632   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5633     ScalarTy = IE->getOperand(1)->getType();
5634   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5635   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5636 
5637   // If we have computed a smaller type for the expression, update VecTy so
5638   // that the costs will be accurate.
5639   if (MinBWs.count(VL[0]))
5640     VecTy = FixedVectorType::get(
5641         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5642   unsigned EntryVF = E->getVectorFactor();
5643   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5644 
5645   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5646   // FIXME: it tries to fix a problem with MSVC buildbots.
5647   TargetTransformInfo &TTIRef = *TTI;
5648   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5649                                VectorizedVals, E](InstructionCost &Cost) {
5650     DenseMap<Value *, int> ExtractVectorsTys;
5651     SmallPtrSet<Value *, 4> CheckedExtracts;
5652     for (auto *V : VL) {
5653       if (isa<UndefValue>(V))
5654         continue;
5655       // If all users of instruction are going to be vectorized and this
5656       // instruction itself is not going to be vectorized, consider this
5657       // instruction as dead and remove its cost from the final cost of the
5658       // vectorized tree.
5659       // Also, avoid adjusting the cost for extractelements with multiple uses
5660       // in different graph entries.
5661       const TreeEntry *VE = getTreeEntry(V);
5662       if (!CheckedExtracts.insert(V).second ||
5663           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5664           (VE && VE != E))
5665         continue;
5666       auto *EE = cast<ExtractElementInst>(V);
5667       Optional<unsigned> EEIdx = getExtractIndex(EE);
5668       if (!EEIdx)
5669         continue;
5670       unsigned Idx = *EEIdx;
5671       if (TTIRef.getNumberOfParts(VecTy) !=
5672           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5673         auto It =
5674             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5675         It->getSecond() = std::min<int>(It->second, Idx);
5676       }
5677       // Take credit for instruction that will become dead.
5678       if (EE->hasOneUse()) {
5679         Instruction *Ext = EE->user_back();
5680         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5681             all_of(Ext->users(),
5682                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5683           // Use getExtractWithExtendCost() to calculate the cost of
5684           // extractelement/ext pair.
5685           Cost -=
5686               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5687                                               EE->getVectorOperandType(), Idx);
5688           // Add back the cost of s|zext which is subtracted separately.
5689           Cost += TTIRef.getCastInstrCost(
5690               Ext->getOpcode(), Ext->getType(), EE->getType(),
5691               TTI::getCastContextHint(Ext), CostKind, Ext);
5692           continue;
5693         }
5694       }
5695       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5696                                         EE->getVectorOperandType(), Idx);
5697     }
5698     // Add a cost for subvector extracts/inserts if required.
5699     for (const auto &Data : ExtractVectorsTys) {
5700       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5701       unsigned NumElts = VecTy->getNumElements();
5702       if (Data.second % NumElts == 0)
5703         continue;
5704       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5705         unsigned Idx = (Data.second / NumElts) * NumElts;
5706         unsigned EENumElts = EEVTy->getNumElements();
5707         if (Idx + NumElts <= EENumElts) {
5708           Cost +=
5709               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5710                                     EEVTy, None, Idx, VecTy);
5711         } else {
5712           // Need to round up the subvector type vectorization factor to avoid a
5713           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5714           // <= EENumElts.
5715           auto *SubVT =
5716               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5717           Cost +=
5718               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5719                                     EEVTy, None, Idx, SubVT);
5720         }
5721       } else {
5722         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5723                                       VecTy, None, 0, EEVTy);
5724       }
5725     }
5726   };
5727   if (E->State == TreeEntry::NeedToGather) {
5728     if (allConstant(VL))
5729       return 0;
5730     if (isa<InsertElementInst>(VL[0]))
5731       return InstructionCost::getInvalid();
5732     SmallVector<int> Mask;
5733     SmallVector<const TreeEntry *> Entries;
5734     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5735         isGatherShuffledEntry(E, Mask, Entries);
5736     if (Shuffle.hasValue()) {
5737       InstructionCost GatherCost = 0;
5738       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5739         // Perfect match in the graph, will reuse the previously vectorized
5740         // node. Cost is 0.
5741         LLVM_DEBUG(
5742             dbgs()
5743             << "SLP: perfect diamond match for gather bundle that starts with "
5744             << *VL.front() << ".\n");
5745         if (NeedToShuffleReuses)
5746           GatherCost =
5747               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5748                                   FinalVecTy, E->ReuseShuffleIndices);
5749       } else {
5750         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5751                           << " entries for bundle that starts with "
5752                           << *VL.front() << ".\n");
5753         // Detected that instead of gather we can emit a shuffle of single/two
5754         // previously vectorized nodes. Add the cost of the permutation rather
5755         // than gather.
5756         ::addMask(Mask, E->ReuseShuffleIndices);
5757         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5758       }
5759       return GatherCost;
5760     }
5761     if ((E->getOpcode() == Instruction::ExtractElement ||
5762          all_of(E->Scalars,
5763                 [](Value *V) {
5764                   return isa<ExtractElementInst, UndefValue>(V);
5765                 })) &&
5766         allSameType(VL)) {
5767       // Check that gather of extractelements can be represented as just a
5768       // shuffle of a single/two vectors the scalars are extracted from.
5769       SmallVector<int> Mask;
5770       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5771           isFixedVectorShuffle(VL, Mask);
5772       if (ShuffleKind.hasValue()) {
5773         // Found the bunch of extractelement instructions that must be gathered
5774         // into a vector and can be represented as a permutation elements in a
5775         // single input vector or of 2 input vectors.
5776         InstructionCost Cost =
5777             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5778         AdjustExtractsCost(Cost);
5779         if (NeedToShuffleReuses)
5780           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5781                                       FinalVecTy, E->ReuseShuffleIndices);
5782         return Cost;
5783       }
5784     }
5785     if (isSplat(VL)) {
5786       // Found the broadcasting of the single scalar, calculate the cost as the
5787       // broadcast.
5788       assert(VecTy == FinalVecTy &&
5789              "No reused scalars expected for broadcast.");
5790       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5791                                  /*Mask=*/None, /*Index=*/0,
5792                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5793     }
5794     InstructionCost ReuseShuffleCost = 0;
5795     if (NeedToShuffleReuses)
5796       ReuseShuffleCost = TTI->getShuffleCost(
5797           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5798     // Improve gather cost for gather of loads, if we can group some of the
5799     // loads into vector loads.
5800     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5801         !E->isAltShuffle()) {
5802       BoUpSLP::ValueSet VectorizedLoads;
5803       unsigned StartIdx = 0;
5804       unsigned VF = VL.size() / 2;
5805       unsigned VectorizedCnt = 0;
5806       unsigned ScatterVectorizeCnt = 0;
5807       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5808       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5809         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5810              Cnt += VF) {
5811           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5812           if (!VectorizedLoads.count(Slice.front()) &&
5813               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5814             SmallVector<Value *> PointerOps;
5815             OrdersType CurrentOrder;
5816             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5817                                               *SE, CurrentOrder, PointerOps);
5818             switch (LS) {
5819             case LoadsState::Vectorize:
5820             case LoadsState::ScatterVectorize:
5821               // Mark the vectorized loads so that we don't vectorize them
5822               // again.
5823               if (LS == LoadsState::Vectorize)
5824                 ++VectorizedCnt;
5825               else
5826                 ++ScatterVectorizeCnt;
5827               VectorizedLoads.insert(Slice.begin(), Slice.end());
5828               // If we vectorized initial block, no need to try to vectorize it
5829               // again.
5830               if (Cnt == StartIdx)
5831                 StartIdx += VF;
5832               break;
5833             case LoadsState::Gather:
5834               break;
5835             }
5836           }
5837         }
5838         // Check if the whole array was vectorized already - exit.
5839         if (StartIdx >= VL.size())
5840           break;
5841         // Found vectorizable parts - exit.
5842         if (!VectorizedLoads.empty())
5843           break;
5844       }
5845       if (!VectorizedLoads.empty()) {
5846         InstructionCost GatherCost = 0;
5847         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5848         bool NeedInsertSubvectorAnalysis =
5849             !NumParts || (VL.size() / VF) > NumParts;
5850         // Get the cost for gathered loads.
5851         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5852           if (VectorizedLoads.contains(VL[I]))
5853             continue;
5854           GatherCost += getGatherCost(VL.slice(I, VF));
5855         }
5856         // The cost for vectorized loads.
5857         InstructionCost ScalarsCost = 0;
5858         for (Value *V : VectorizedLoads) {
5859           auto *LI = cast<LoadInst>(V);
5860           ScalarsCost += TTI->getMemoryOpCost(
5861               Instruction::Load, LI->getType(), LI->getAlign(),
5862               LI->getPointerAddressSpace(), CostKind, LI);
5863         }
5864         auto *LI = cast<LoadInst>(E->getMainOp());
5865         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5866         Align Alignment = LI->getAlign();
5867         GatherCost +=
5868             VectorizedCnt *
5869             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5870                                  LI->getPointerAddressSpace(), CostKind, LI);
5871         GatherCost += ScatterVectorizeCnt *
5872                       TTI->getGatherScatterOpCost(
5873                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5874                           /*VariableMask=*/false, Alignment, CostKind, LI);
5875         if (NeedInsertSubvectorAnalysis) {
5876           // Add the cost for the subvectors insert.
5877           for (int I = VF, E = VL.size(); I < E; I += VF)
5878             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5879                                               None, I, LoadTy);
5880         }
5881         return ReuseShuffleCost + GatherCost - ScalarsCost;
5882       }
5883     }
5884     return ReuseShuffleCost + getGatherCost(VL);
5885   }
5886   InstructionCost CommonCost = 0;
5887   SmallVector<int> Mask;
5888   if (!E->ReorderIndices.empty()) {
5889     SmallVector<int> NewMask;
5890     if (E->getOpcode() == Instruction::Store) {
5891       // For stores the order is actually a mask.
5892       NewMask.resize(E->ReorderIndices.size());
5893       copy(E->ReorderIndices, NewMask.begin());
5894     } else {
5895       inversePermutation(E->ReorderIndices, NewMask);
5896     }
5897     ::addMask(Mask, NewMask);
5898   }
5899   if (NeedToShuffleReuses)
5900     ::addMask(Mask, E->ReuseShuffleIndices);
5901   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5902     CommonCost =
5903         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5904   assert((E->State == TreeEntry::Vectorize ||
5905           E->State == TreeEntry::ScatterVectorize) &&
5906          "Unhandled state");
5907   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5908   Instruction *VL0 = E->getMainOp();
5909   unsigned ShuffleOrOp =
5910       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5911   switch (ShuffleOrOp) {
5912     case Instruction::PHI:
5913       return 0;
5914 
5915     case Instruction::ExtractValue:
5916     case Instruction::ExtractElement: {
5917       // The common cost of removal ExtractElement/ExtractValue instructions +
5918       // the cost of shuffles, if required to resuffle the original vector.
5919       if (NeedToShuffleReuses) {
5920         unsigned Idx = 0;
5921         for (unsigned I : E->ReuseShuffleIndices) {
5922           if (ShuffleOrOp == Instruction::ExtractElement) {
5923             auto *EE = cast<ExtractElementInst>(VL[I]);
5924             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5925                                                   EE->getVectorOperandType(),
5926                                                   *getExtractIndex(EE));
5927           } else {
5928             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5929                                                   VecTy, Idx);
5930             ++Idx;
5931           }
5932         }
5933         Idx = EntryVF;
5934         for (Value *V : VL) {
5935           if (ShuffleOrOp == Instruction::ExtractElement) {
5936             auto *EE = cast<ExtractElementInst>(V);
5937             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5938                                                   EE->getVectorOperandType(),
5939                                                   *getExtractIndex(EE));
5940           } else {
5941             --Idx;
5942             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5943                                                   VecTy, Idx);
5944           }
5945         }
5946       }
5947       if (ShuffleOrOp == Instruction::ExtractValue) {
5948         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5949           auto *EI = cast<Instruction>(VL[I]);
5950           // Take credit for instruction that will become dead.
5951           if (EI->hasOneUse()) {
5952             Instruction *Ext = EI->user_back();
5953             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5954                 all_of(Ext->users(),
5955                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5956               // Use getExtractWithExtendCost() to calculate the cost of
5957               // extractelement/ext pair.
5958               CommonCost -= TTI->getExtractWithExtendCost(
5959                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5960               // Add back the cost of s|zext which is subtracted separately.
5961               CommonCost += TTI->getCastInstrCost(
5962                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5963                   TTI::getCastContextHint(Ext), CostKind, Ext);
5964               continue;
5965             }
5966           }
5967           CommonCost -=
5968               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5969         }
5970       } else {
5971         AdjustExtractsCost(CommonCost);
5972       }
5973       return CommonCost;
5974     }
5975     case Instruction::InsertElement: {
5976       assert(E->ReuseShuffleIndices.empty() &&
5977              "Unique insertelements only are expected.");
5978       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5979 
5980       unsigned const NumElts = SrcVecTy->getNumElements();
5981       unsigned const NumScalars = VL.size();
5982       APInt DemandedElts = APInt::getZero(NumElts);
5983       // TODO: Add support for Instruction::InsertValue.
5984       SmallVector<int> Mask;
5985       if (!E->ReorderIndices.empty()) {
5986         inversePermutation(E->ReorderIndices, Mask);
5987         Mask.append(NumElts - NumScalars, UndefMaskElem);
5988       } else {
5989         Mask.assign(NumElts, UndefMaskElem);
5990         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5991       }
5992       unsigned Offset = *getInsertIndex(VL0);
5993       bool IsIdentity = true;
5994       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5995       Mask.swap(PrevMask);
5996       for (unsigned I = 0; I < NumScalars; ++I) {
5997         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5998         DemandedElts.setBit(InsertIdx);
5999         IsIdentity &= InsertIdx - Offset == I;
6000         Mask[InsertIdx - Offset] = I;
6001       }
6002       assert(Offset < NumElts && "Failed to find vector index offset");
6003 
6004       InstructionCost Cost = 0;
6005       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
6006                                             /*Insert*/ true, /*Extract*/ false);
6007 
6008       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
6009         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
6010         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
6011         Cost += TTI->getShuffleCost(
6012             TargetTransformInfo::SK_PermuteSingleSrc,
6013             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
6014       } else if (!IsIdentity) {
6015         auto *FirstInsert =
6016             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6017               return !is_contained(E->Scalars,
6018                                    cast<Instruction>(V)->getOperand(0));
6019             }));
6020         if (isUndefVector(FirstInsert->getOperand(0))) {
6021           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
6022         } else {
6023           SmallVector<int> InsertMask(NumElts);
6024           std::iota(InsertMask.begin(), InsertMask.end(), 0);
6025           for (unsigned I = 0; I < NumElts; I++) {
6026             if (Mask[I] != UndefMaskElem)
6027               InsertMask[Offset + I] = NumElts + I;
6028           }
6029           Cost +=
6030               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
6031         }
6032       }
6033 
6034       return Cost;
6035     }
6036     case Instruction::ZExt:
6037     case Instruction::SExt:
6038     case Instruction::FPToUI:
6039     case Instruction::FPToSI:
6040     case Instruction::FPExt:
6041     case Instruction::PtrToInt:
6042     case Instruction::IntToPtr:
6043     case Instruction::SIToFP:
6044     case Instruction::UIToFP:
6045     case Instruction::Trunc:
6046     case Instruction::FPTrunc:
6047     case Instruction::BitCast: {
6048       Type *SrcTy = VL0->getOperand(0)->getType();
6049       InstructionCost ScalarEltCost =
6050           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
6051                                 TTI::getCastContextHint(VL0), CostKind, VL0);
6052       if (NeedToShuffleReuses) {
6053         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6054       }
6055 
6056       // Calculate the cost of this instruction.
6057       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
6058 
6059       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
6060       InstructionCost VecCost = 0;
6061       // Check if the values are candidates to demote.
6062       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
6063         VecCost = CommonCost + TTI->getCastInstrCost(
6064                                    E->getOpcode(), VecTy, SrcVecTy,
6065                                    TTI::getCastContextHint(VL0), CostKind, VL0);
6066       }
6067       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6068       return VecCost - ScalarCost;
6069     }
6070     case Instruction::FCmp:
6071     case Instruction::ICmp:
6072     case Instruction::Select: {
6073       // Calculate the cost of this instruction.
6074       InstructionCost ScalarEltCost =
6075           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6076                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
6077       if (NeedToShuffleReuses) {
6078         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6079       }
6080       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
6081       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6082 
6083       // Check if all entries in VL are either compares or selects with compares
6084       // as condition that have the same predicates.
6085       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
6086       bool First = true;
6087       for (auto *V : VL) {
6088         CmpInst::Predicate CurrentPred;
6089         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
6090         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
6091              !match(V, MatchCmp)) ||
6092             (!First && VecPred != CurrentPred)) {
6093           VecPred = CmpInst::BAD_ICMP_PREDICATE;
6094           break;
6095         }
6096         First = false;
6097         VecPred = CurrentPred;
6098       }
6099 
6100       InstructionCost VecCost = TTI->getCmpSelInstrCost(
6101           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
6102       // Check if it is possible and profitable to use min/max for selects in
6103       // VL.
6104       //
6105       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
6106       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
6107         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
6108                                           {VecTy, VecTy});
6109         InstructionCost IntrinsicCost =
6110             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6111         // If the selects are the only uses of the compares, they will be dead
6112         // and we can adjust the cost by removing their cost.
6113         if (IntrinsicAndUse.second)
6114           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
6115                                                    MaskTy, VecPred, CostKind);
6116         VecCost = std::min(VecCost, IntrinsicCost);
6117       }
6118       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6119       return CommonCost + VecCost - ScalarCost;
6120     }
6121     case Instruction::FNeg:
6122     case Instruction::Add:
6123     case Instruction::FAdd:
6124     case Instruction::Sub:
6125     case Instruction::FSub:
6126     case Instruction::Mul:
6127     case Instruction::FMul:
6128     case Instruction::UDiv:
6129     case Instruction::SDiv:
6130     case Instruction::FDiv:
6131     case Instruction::URem:
6132     case Instruction::SRem:
6133     case Instruction::FRem:
6134     case Instruction::Shl:
6135     case Instruction::LShr:
6136     case Instruction::AShr:
6137     case Instruction::And:
6138     case Instruction::Or:
6139     case Instruction::Xor: {
6140       // Certain instructions can be cheaper to vectorize if they have a
6141       // constant second vector operand.
6142       TargetTransformInfo::OperandValueKind Op1VK =
6143           TargetTransformInfo::OK_AnyValue;
6144       TargetTransformInfo::OperandValueKind Op2VK =
6145           TargetTransformInfo::OK_UniformConstantValue;
6146       TargetTransformInfo::OperandValueProperties Op1VP =
6147           TargetTransformInfo::OP_None;
6148       TargetTransformInfo::OperandValueProperties Op2VP =
6149           TargetTransformInfo::OP_PowerOf2;
6150 
6151       // If all operands are exactly the same ConstantInt then set the
6152       // operand kind to OK_UniformConstantValue.
6153       // If instead not all operands are constants, then set the operand kind
6154       // to OK_AnyValue. If all operands are constants but not the same,
6155       // then set the operand kind to OK_NonUniformConstantValue.
6156       ConstantInt *CInt0 = nullptr;
6157       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
6158         const Instruction *I = cast<Instruction>(VL[i]);
6159         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
6160         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
6161         if (!CInt) {
6162           Op2VK = TargetTransformInfo::OK_AnyValue;
6163           Op2VP = TargetTransformInfo::OP_None;
6164           break;
6165         }
6166         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
6167             !CInt->getValue().isPowerOf2())
6168           Op2VP = TargetTransformInfo::OP_None;
6169         if (i == 0) {
6170           CInt0 = CInt;
6171           continue;
6172         }
6173         if (CInt0 != CInt)
6174           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6175       }
6176 
6177       SmallVector<const Value *, 4> Operands(VL0->operand_values());
6178       InstructionCost ScalarEltCost =
6179           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
6180                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6181       if (NeedToShuffleReuses) {
6182         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6183       }
6184       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6185       InstructionCost VecCost =
6186           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
6187                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
6188       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6189       return CommonCost + VecCost - ScalarCost;
6190     }
6191     case Instruction::GetElementPtr: {
6192       TargetTransformInfo::OperandValueKind Op1VK =
6193           TargetTransformInfo::OK_AnyValue;
6194       TargetTransformInfo::OperandValueKind Op2VK =
6195           TargetTransformInfo::OK_UniformConstantValue;
6196 
6197       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
6198           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
6199       if (NeedToShuffleReuses) {
6200         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6201       }
6202       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
6203       InstructionCost VecCost = TTI->getArithmeticInstrCost(
6204           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
6205       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6206       return CommonCost + VecCost - ScalarCost;
6207     }
6208     case Instruction::Load: {
6209       // Cost of wide load - cost of scalar loads.
6210       Align Alignment = cast<LoadInst>(VL0)->getAlign();
6211       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6212           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
6213       if (NeedToShuffleReuses) {
6214         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6215       }
6216       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
6217       InstructionCost VecLdCost;
6218       if (E->State == TreeEntry::Vectorize) {
6219         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
6220                                          CostKind, VL0);
6221       } else {
6222         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
6223         Align CommonAlignment = Alignment;
6224         for (Value *V : VL)
6225           CommonAlignment =
6226               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6227         VecLdCost = TTI->getGatherScatterOpCost(
6228             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
6229             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
6230       }
6231       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
6232       return CommonCost + VecLdCost - ScalarLdCost;
6233     }
6234     case Instruction::Store: {
6235       // We know that we can merge the stores. Calculate the cost.
6236       bool IsReorder = !E->ReorderIndices.empty();
6237       auto *SI =
6238           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
6239       Align Alignment = SI->getAlign();
6240       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
6241           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
6242       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
6243       InstructionCost VecStCost = TTI->getMemoryOpCost(
6244           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
6245       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
6246       return CommonCost + VecStCost - ScalarStCost;
6247     }
6248     case Instruction::Call: {
6249       CallInst *CI = cast<CallInst>(VL0);
6250       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6251 
6252       // Calculate the cost of the scalar and vector calls.
6253       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
6254       InstructionCost ScalarEltCost =
6255           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
6256       if (NeedToShuffleReuses) {
6257         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
6258       }
6259       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
6260 
6261       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6262       InstructionCost VecCallCost =
6263           std::min(VecCallCosts.first, VecCallCosts.second);
6264 
6265       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
6266                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
6267                         << " for " << *CI << "\n");
6268 
6269       return CommonCost + VecCallCost - ScalarCallCost;
6270     }
6271     case Instruction::ShuffleVector: {
6272       assert(E->isAltShuffle() &&
6273              ((Instruction::isBinaryOp(E->getOpcode()) &&
6274                Instruction::isBinaryOp(E->getAltOpcode())) ||
6275               (Instruction::isCast(E->getOpcode()) &&
6276                Instruction::isCast(E->getAltOpcode())) ||
6277               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6278              "Invalid Shuffle Vector Operand");
6279       InstructionCost ScalarCost = 0;
6280       if (NeedToShuffleReuses) {
6281         for (unsigned Idx : E->ReuseShuffleIndices) {
6282           Instruction *I = cast<Instruction>(VL[Idx]);
6283           CommonCost -= TTI->getInstructionCost(I, CostKind);
6284         }
6285         for (Value *V : VL) {
6286           Instruction *I = cast<Instruction>(V);
6287           CommonCost += TTI->getInstructionCost(I, CostKind);
6288         }
6289       }
6290       for (Value *V : VL) {
6291         Instruction *I = cast<Instruction>(V);
6292         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6293         ScalarCost += TTI->getInstructionCost(I, CostKind);
6294       }
6295       // VecCost is equal to sum of the cost of creating 2 vectors
6296       // and the cost of creating shuffle.
6297       InstructionCost VecCost = 0;
6298       // Try to find the previous shuffle node with the same operands and same
6299       // main/alternate ops.
6300       auto &&TryFindNodeWithEqualOperands = [this, E]() {
6301         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
6302           if (TE.get() == E)
6303             break;
6304           if (TE->isAltShuffle() &&
6305               ((TE->getOpcode() == E->getOpcode() &&
6306                 TE->getAltOpcode() == E->getAltOpcode()) ||
6307                (TE->getOpcode() == E->getAltOpcode() &&
6308                 TE->getAltOpcode() == E->getOpcode())) &&
6309               TE->hasEqualOperands(*E))
6310             return true;
6311         }
6312         return false;
6313       };
6314       if (TryFindNodeWithEqualOperands()) {
6315         LLVM_DEBUG({
6316           dbgs() << "SLP: diamond match for alternate node found.\n";
6317           E->dump();
6318         });
6319         // No need to add new vector costs here since we're going to reuse
6320         // same main/alternate vector ops, just do different shuffling.
6321       } else if (Instruction::isBinaryOp(E->getOpcode())) {
6322         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
6323         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
6324                                                CostKind);
6325       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6326         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
6327                                           Builder.getInt1Ty(),
6328                                           CI0->getPredicate(), CostKind, VL0);
6329         VecCost += TTI->getCmpSelInstrCost(
6330             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
6331             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
6332             E->getAltOp());
6333       } else {
6334         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
6335         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
6336         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
6337         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
6338         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
6339                                         TTI::CastContextHint::None, CostKind);
6340         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
6341                                          TTI::CastContextHint::None, CostKind);
6342       }
6343 
6344       if (E->ReuseShuffleIndices.empty()) {
6345         CommonCost =
6346             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6347       } else {
6348         SmallVector<int> Mask;
6349         buildShuffleEntryMask(
6350             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6351             [E](Instruction *I) {
6352               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6353               return I->getOpcode() == E->getAltOpcode();
6354             },
6355             Mask);
6356         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6357                                          FinalVecTy, Mask);
6358       }
6359       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6360       return CommonCost + VecCost - ScalarCost;
6361     }
6362     default:
6363       llvm_unreachable("Unknown instruction");
6364   }
6365 }
6366 
6367 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6368   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6369                     << VectorizableTree.size() << " is fully vectorizable .\n");
6370 
6371   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6372     SmallVector<int> Mask;
6373     return TE->State == TreeEntry::NeedToGather &&
6374            !any_of(TE->Scalars,
6375                    [this](Value *V) { return EphValues.contains(V); }) &&
6376            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6377             TE->Scalars.size() < Limit ||
6378             ((TE->getOpcode() == Instruction::ExtractElement ||
6379               all_of(TE->Scalars,
6380                      [](Value *V) {
6381                        return isa<ExtractElementInst, UndefValue>(V);
6382                      })) &&
6383              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6384             (TE->State == TreeEntry::NeedToGather &&
6385              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6386   };
6387 
6388   // We only handle trees of heights 1 and 2.
6389   if (VectorizableTree.size() == 1 &&
6390       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6391        (ForReduction &&
6392         AreVectorizableGathers(VectorizableTree[0].get(),
6393                                VectorizableTree[0]->Scalars.size()) &&
6394         VectorizableTree[0]->getVectorFactor() > 2)))
6395     return true;
6396 
6397   if (VectorizableTree.size() != 2)
6398     return false;
6399 
6400   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6401   // with the second gather nodes if they have less scalar operands rather than
6402   // the initial tree element (may be profitable to shuffle the second gather)
6403   // or they are extractelements, which form shuffle.
6404   SmallVector<int> Mask;
6405   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6406       AreVectorizableGathers(VectorizableTree[1].get(),
6407                              VectorizableTree[0]->Scalars.size()))
6408     return true;
6409 
6410   // Gathering cost would be too much for tiny trees.
6411   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6412       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6413        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6414     return false;
6415 
6416   return true;
6417 }
6418 
6419 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6420                                        TargetTransformInfo *TTI,
6421                                        bool MustMatchOrInst) {
6422   // Look past the root to find a source value. Arbitrarily follow the
6423   // path through operand 0 of any 'or'. Also, peek through optional
6424   // shift-left-by-multiple-of-8-bits.
6425   Value *ZextLoad = Root;
6426   const APInt *ShAmtC;
6427   bool FoundOr = false;
6428   while (!isa<ConstantExpr>(ZextLoad) &&
6429          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6430           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6431            ShAmtC->urem(8) == 0))) {
6432     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6433     ZextLoad = BinOp->getOperand(0);
6434     if (BinOp->getOpcode() == Instruction::Or)
6435       FoundOr = true;
6436   }
6437   // Check if the input is an extended load of the required or/shift expression.
6438   Value *Load;
6439   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6440       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6441     return false;
6442 
6443   // Require that the total load bit width is a legal integer type.
6444   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6445   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6446   Type *SrcTy = Load->getType();
6447   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6448   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6449     return false;
6450 
6451   // Everything matched - assume that we can fold the whole sequence using
6452   // load combining.
6453   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6454              << *(cast<Instruction>(Root)) << "\n");
6455 
6456   return true;
6457 }
6458 
6459 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6460   if (RdxKind != RecurKind::Or)
6461     return false;
6462 
6463   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6464   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6465   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6466                                     /* MatchOr */ false);
6467 }
6468 
6469 bool BoUpSLP::isLoadCombineCandidate() const {
6470   // Peek through a final sequence of stores and check if all operations are
6471   // likely to be load-combined.
6472   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6473   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6474     Value *X;
6475     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6476         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6477       return false;
6478   }
6479   return true;
6480 }
6481 
6482 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6483   // No need to vectorize inserts of gathered values.
6484   if (VectorizableTree.size() == 2 &&
6485       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6486       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6487     return true;
6488 
6489   // We can vectorize the tree if its size is greater than or equal to the
6490   // minimum size specified by the MinTreeSize command line option.
6491   if (VectorizableTree.size() >= MinTreeSize)
6492     return false;
6493 
6494   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6495   // can vectorize it if we can prove it fully vectorizable.
6496   if (isFullyVectorizableTinyTree(ForReduction))
6497     return false;
6498 
6499   assert(VectorizableTree.empty()
6500              ? ExternalUses.empty()
6501              : true && "We shouldn't have any external users");
6502 
6503   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6504   // vectorizable.
6505   return true;
6506 }
6507 
6508 InstructionCost BoUpSLP::getSpillCost() const {
6509   // Walk from the bottom of the tree to the top, tracking which values are
6510   // live. When we see a call instruction that is not part of our tree,
6511   // query TTI to see if there is a cost to keeping values live over it
6512   // (for example, if spills and fills are required).
6513   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6514   InstructionCost Cost = 0;
6515 
6516   SmallPtrSet<Instruction*, 4> LiveValues;
6517   Instruction *PrevInst = nullptr;
6518 
6519   // The entries in VectorizableTree are not necessarily ordered by their
6520   // position in basic blocks. Collect them and order them by dominance so later
6521   // instructions are guaranteed to be visited first. For instructions in
6522   // different basic blocks, we only scan to the beginning of the block, so
6523   // their order does not matter, as long as all instructions in a basic block
6524   // are grouped together. Using dominance ensures a deterministic order.
6525   SmallVector<Instruction *, 16> OrderedScalars;
6526   for (const auto &TEPtr : VectorizableTree) {
6527     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6528     if (!Inst)
6529       continue;
6530     OrderedScalars.push_back(Inst);
6531   }
6532   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6533     auto *NodeA = DT->getNode(A->getParent());
6534     auto *NodeB = DT->getNode(B->getParent());
6535     assert(NodeA && "Should only process reachable instructions");
6536     assert(NodeB && "Should only process reachable instructions");
6537     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6538            "Different nodes should have different DFS numbers");
6539     if (NodeA != NodeB)
6540       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6541     return B->comesBefore(A);
6542   });
6543 
6544   for (Instruction *Inst : OrderedScalars) {
6545     if (!PrevInst) {
6546       PrevInst = Inst;
6547       continue;
6548     }
6549 
6550     // Update LiveValues.
6551     LiveValues.erase(PrevInst);
6552     for (auto &J : PrevInst->operands()) {
6553       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6554         LiveValues.insert(cast<Instruction>(&*J));
6555     }
6556 
6557     LLVM_DEBUG({
6558       dbgs() << "SLP: #LV: " << LiveValues.size();
6559       for (auto *X : LiveValues)
6560         dbgs() << " " << X->getName();
6561       dbgs() << ", Looking at ";
6562       Inst->dump();
6563     });
6564 
6565     // Now find the sequence of instructions between PrevInst and Inst.
6566     unsigned NumCalls = 0;
6567     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6568                                  PrevInstIt =
6569                                      PrevInst->getIterator().getReverse();
6570     while (InstIt != PrevInstIt) {
6571       if (PrevInstIt == PrevInst->getParent()->rend()) {
6572         PrevInstIt = Inst->getParent()->rbegin();
6573         continue;
6574       }
6575 
6576       // Debug information does not impact spill cost.
6577       if ((isa<CallInst>(&*PrevInstIt) &&
6578            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6579           &*PrevInstIt != PrevInst)
6580         NumCalls++;
6581 
6582       ++PrevInstIt;
6583     }
6584 
6585     if (NumCalls) {
6586       SmallVector<Type*, 4> V;
6587       for (auto *II : LiveValues) {
6588         auto *ScalarTy = II->getType();
6589         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6590           ScalarTy = VectorTy->getElementType();
6591         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6592       }
6593       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6594     }
6595 
6596     PrevInst = Inst;
6597   }
6598 
6599   return Cost;
6600 }
6601 
6602 /// Check if two insertelement instructions are from the same buildvector.
6603 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6604                                             InsertElementInst *V) {
6605   // Instructions must be from the same basic blocks.
6606   if (VU->getParent() != V->getParent())
6607     return false;
6608   // Checks if 2 insertelements are from the same buildvector.
6609   if (VU->getType() != V->getType())
6610     return false;
6611   // Multiple used inserts are separate nodes.
6612   if (!VU->hasOneUse() && !V->hasOneUse())
6613     return false;
6614   auto *IE1 = VU;
6615   auto *IE2 = V;
6616   unsigned Idx1 = *getInsertIndex(IE1);
6617   unsigned Idx2 = *getInsertIndex(IE2);
6618   // Go through the vector operand of insertelement instructions trying to find
6619   // either VU as the original vector for IE2 or V as the original vector for
6620   // IE1.
6621   do {
6622     if (IE2 == VU)
6623       return VU->hasOneUse();
6624     if (IE1 == V)
6625       return V->hasOneUse();
6626     if (IE1) {
6627       if ((IE1 != VU && !IE1->hasOneUse()) ||
6628           getInsertIndex(IE1).getValueOr(Idx2) == Idx2)
6629         IE1 = nullptr;
6630       else
6631         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6632     }
6633     if (IE2) {
6634       if ((IE2 != V && !IE2->hasOneUse()) ||
6635           getInsertIndex(IE2).getValueOr(Idx1) == Idx1)
6636         IE2 = nullptr;
6637       else
6638         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6639     }
6640   } while (IE1 || IE2);
6641   return false;
6642 }
6643 
6644 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6645 /// buildvector sequence.
6646 static bool isFirstInsertElement(const InsertElementInst *IE1,
6647                                  const InsertElementInst *IE2) {
6648   const auto *I1 = IE1;
6649   const auto *I2 = IE2;
6650   const InsertElementInst *PrevI1;
6651   const InsertElementInst *PrevI2;
6652   unsigned Idx1 = *getInsertIndex(IE1);
6653   unsigned Idx2 = *getInsertIndex(IE2);
6654   do {
6655     if (I2 == IE1)
6656       return true;
6657     if (I1 == IE2)
6658       return false;
6659     PrevI1 = I1;
6660     PrevI2 = I2;
6661     if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
6662         getInsertIndex(I1).getValueOr(Idx2) != Idx2)
6663       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6664     if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
6665         getInsertIndex(I2).getValueOr(Idx1) != Idx1)
6666       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6667   } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
6668   llvm_unreachable("Two different buildvectors not expected.");
6669 }
6670 
6671 namespace {
6672 /// Returns incoming Value *, if the requested type is Value * too, or a default
6673 /// value, otherwise.
6674 struct ValueSelect {
6675   template <typename U>
6676   static typename std::enable_if<std::is_same<Value *, U>::value, Value *>::type
6677   get(Value *V) {
6678     return V;
6679   }
6680   template <typename U>
6681   static typename std::enable_if<!std::is_same<Value *, U>::value, U>::type
6682   get(Value *) {
6683     return U();
6684   }
6685 };
6686 } // namespace
6687 
6688 /// Does the analysis of the provided shuffle masks and performs the requested
6689 /// actions on the vectors with the given shuffle masks. It tries to do it in
6690 /// several steps.
6691 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6692 /// have common VF and perform action for 2 input vectors (including non-undef
6693 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6694 /// and processed as a shuffle of 2 elements.
6695 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6696 /// action only for 1 vector with the given mask, if it is not the identity
6697 /// mask.
6698 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6699 /// vectors, combing the masks properly between the steps.
6700 template <typename T>
6701 static T *performExtractsShuffleAction(
6702     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6703     function_ref<unsigned(T *)> GetVF,
6704     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6705     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6706   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6707   SmallVector<int> Mask(ShuffleMask.begin()->second);
6708   auto VMIt = std::next(ShuffleMask.begin());
6709   T *Prev = nullptr;
6710   bool IsBaseNotUndef = !isUndefVector(Base);
6711   if (IsBaseNotUndef) {
6712     // Base is not undef, need to combine it with the next subvectors.
6713     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6714     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6715       if (Mask[Idx] == UndefMaskElem)
6716         Mask[Idx] = Idx;
6717       else
6718         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6719     }
6720     auto *V = ValueSelect::get<T *>(Base);
6721     (void)V;
6722     assert((!V || GetVF(V) == Mask.size()) &&
6723            "Expected base vector of VF number of elements.");
6724     Prev = Action(Mask, {nullptr, Res.first});
6725   } else if (ShuffleMask.size() == 1) {
6726     // Base is undef and only 1 vector is shuffled - perform the action only for
6727     // single vector, if the mask is not the identity mask.
6728     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6729     if (Res.second)
6730       // Identity mask is found.
6731       Prev = Res.first;
6732     else
6733       Prev = Action(Mask, {ShuffleMask.begin()->first});
6734   } else {
6735     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6736     // shuffles step by step, combining shuffle between the steps.
6737     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6738     unsigned Vec2VF = GetVF(VMIt->first);
6739     if (Vec1VF == Vec2VF) {
6740       // No need to resize the input vectors since they are of the same size, we
6741       // can shuffle them directly.
6742       ArrayRef<int> SecMask = VMIt->second;
6743       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6744         if (SecMask[I] != UndefMaskElem) {
6745           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6746           Mask[I] = SecMask[I] + Vec1VF;
6747         }
6748       }
6749       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6750     } else {
6751       // Vectors of different sizes - resize and reshuffle.
6752       std::pair<T *, bool> Res1 =
6753           ResizeAction(ShuffleMask.begin()->first, Mask);
6754       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6755       ArrayRef<int> SecMask = VMIt->second;
6756       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6757         if (Mask[I] != UndefMaskElem) {
6758           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6759           if (Res1.second)
6760             Mask[I] = I;
6761         } else if (SecMask[I] != UndefMaskElem) {
6762           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6763           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6764         }
6765       }
6766       Prev = Action(Mask, {Res1.first, Res2.first});
6767     }
6768     VMIt = std::next(VMIt);
6769   }
6770   // Perform requested actions for the remaining masks/vectors.
6771   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6772     // Shuffle other input vectors, if any.
6773     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6774     ArrayRef<int> SecMask = VMIt->second;
6775     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6776       if (SecMask[I] != UndefMaskElem) {
6777         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6778                "Multiple uses of scalars.");
6779         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6780       } else if (Mask[I] != UndefMaskElem) {
6781         Mask[I] = I;
6782       }
6783     }
6784     Prev = Action(Mask, {Prev, Res.first});
6785   }
6786   return Prev;
6787 }
6788 
6789 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6790   InstructionCost Cost = 0;
6791   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6792                     << VectorizableTree.size() << ".\n");
6793 
6794   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6795 
6796   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6797     TreeEntry &TE = *VectorizableTree[I];
6798 
6799     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6800     Cost += C;
6801     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6802                       << " for bundle that starts with " << *TE.Scalars[0]
6803                       << ".\n"
6804                       << "SLP: Current total cost = " << Cost << "\n");
6805   }
6806 
6807   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6808   InstructionCost ExtractCost = 0;
6809   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6810   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6811   SmallVector<APInt> DemandedElts;
6812   for (ExternalUser &EU : ExternalUses) {
6813     // We only add extract cost once for the same scalar.
6814     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6815         !ExtractCostCalculated.insert(EU.Scalar).second)
6816       continue;
6817 
6818     // Uses by ephemeral values are free (because the ephemeral value will be
6819     // removed prior to code generation, and so the extraction will be
6820     // removed as well).
6821     if (EphValues.count(EU.User))
6822       continue;
6823 
6824     // No extract cost for vector "scalar"
6825     if (isa<FixedVectorType>(EU.Scalar->getType()))
6826       continue;
6827 
6828     // Already counted the cost for external uses when tried to adjust the cost
6829     // for extractelements, no need to add it again.
6830     if (isa<ExtractElementInst>(EU.Scalar))
6831       continue;
6832 
6833     // If found user is an insertelement, do not calculate extract cost but try
6834     // to detect it as a final shuffled/identity match.
6835     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6836       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6837         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6838         if (InsertIdx) {
6839           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6840           auto *It =
6841               find_if(FirstUsers,
6842                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6843                         return areTwoInsertFromSameBuildVector(
6844                             VU, cast<InsertElementInst>(Pair.first));
6845                       });
6846           int VecId = -1;
6847           if (It == FirstUsers.end()) {
6848             (void)ShuffleMasks.emplace_back();
6849             SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6850             if (Mask.empty())
6851               Mask.assign(FTy->getNumElements(), UndefMaskElem);
6852             // Find the insertvector, vectorized in tree, if any.
6853             Value *Base = VU;
6854             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6855               if (IEBase != EU.User &&
6856                   (!IEBase->hasOneUse() ||
6857                    getInsertIndex(IEBase).getValueOr(*InsertIdx) == *InsertIdx))
6858                 break;
6859               // Build the mask for the vectorized insertelement instructions.
6860               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6861                 VU = IEBase;
6862                 do {
6863                   IEBase = cast<InsertElementInst>(Base);
6864                   int Idx = *getInsertIndex(IEBase);
6865                   assert(Mask[Idx] == UndefMaskElem &&
6866                          "InsertElementInstruction used already.");
6867                   Mask[Idx] = Idx;
6868                   Base = IEBase->getOperand(0);
6869                 } while (E == getTreeEntry(Base));
6870                 break;
6871               }
6872               Base = cast<InsertElementInst>(Base)->getOperand(0);
6873             }
6874             FirstUsers.emplace_back(VU, ScalarTE);
6875             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6876             VecId = FirstUsers.size() - 1;
6877           } else {
6878             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6879               It->first = VU;
6880             VecId = std::distance(FirstUsers.begin(), It);
6881           }
6882           int InIdx = *InsertIdx;
6883           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6884           if (Mask.empty())
6885             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6886           Mask[InIdx] = EU.Lane;
6887           DemandedElts[VecId].setBit(InIdx);
6888           continue;
6889         }
6890       }
6891     }
6892 
6893     // If we plan to rewrite the tree in a smaller type, we will need to sign
6894     // extend the extracted value back to the original type. Here, we account
6895     // for the extract and the added cost of the sign extend if needed.
6896     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6897     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6898     if (MinBWs.count(ScalarRoot)) {
6899       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6900       auto Extend =
6901           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6902       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6903       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6904                                                    VecTy, EU.Lane);
6905     } else {
6906       ExtractCost +=
6907           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6908     }
6909   }
6910 
6911   InstructionCost SpillCost = getSpillCost();
6912   Cost += SpillCost + ExtractCost;
6913   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6914     InstructionCost C = 0;
6915     unsigned VF = Mask.size();
6916     unsigned VecVF = TE->getVectorFactor();
6917     if (VF != VecVF &&
6918         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6919          (all_of(Mask,
6920                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6921           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6922       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6923       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6924                 OrigMask.begin());
6925       C = TTI->getShuffleCost(
6926           TTI::SK_PermuteSingleSrc,
6927           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6928       LLVM_DEBUG(
6929           dbgs() << "SLP: Adding cost " << C
6930                  << " for final shuffle of insertelement external users.\n";
6931           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6932       Cost += C;
6933       return std::make_pair(TE, true);
6934     }
6935     return std::make_pair(TE, false);
6936   };
6937   // Calculate the cost of the reshuffled vectors, if any.
6938   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6939     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6940     unsigned VF = ShuffleMasks[I].begin()->second.size();
6941     auto *FTy = FixedVectorType::get(
6942         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6943     auto Vector = ShuffleMasks[I].takeVector();
6944     auto &&EstimateShufflesCost = [this, FTy,
6945                                    &Cost](ArrayRef<int> Mask,
6946                                           ArrayRef<const TreeEntry *> TEs) {
6947       assert((TEs.size() == 1 || TEs.size() == 2) &&
6948              "Expected exactly 1 or 2 tree entries.");
6949       if (TEs.size() == 1) {
6950         int Limit = 2 * Mask.size();
6951         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6952             !ShuffleVectorInst::isIdentityMask(Mask)) {
6953           InstructionCost C =
6954               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6955           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6956                             << " for final shuffle of insertelement "
6957                                "external users.\n";
6958                      TEs.front()->dump();
6959                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6960           Cost += C;
6961         }
6962       } else {
6963         InstructionCost C =
6964             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
6965         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6966                           << " for final shuffle of vector node and external "
6967                              "insertelement users.\n";
6968                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
6969                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
6970         Cost += C;
6971       }
6972       return TEs.back();
6973     };
6974     (void)performExtractsShuffleAction<const TreeEntry>(
6975         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
6976         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
6977         EstimateShufflesCost);
6978     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6979         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
6980         /*Insert*/ true, /*Extract*/ false);
6981     Cost -= InsertCost;
6982   }
6983 
6984 #ifndef NDEBUG
6985   SmallString<256> Str;
6986   {
6987     raw_svector_ostream OS(Str);
6988     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6989        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6990        << "SLP: Total Cost = " << Cost << ".\n";
6991   }
6992   LLVM_DEBUG(dbgs() << Str);
6993   if (ViewSLPTree)
6994     ViewGraph(this, "SLP" + F->getName(), false, Str);
6995 #endif
6996 
6997   return Cost;
6998 }
6999 
7000 Optional<TargetTransformInfo::ShuffleKind>
7001 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
7002                                SmallVectorImpl<const TreeEntry *> &Entries) {
7003   // TODO: currently checking only for Scalars in the tree entry, need to count
7004   // reused elements too for better cost estimation.
7005   Mask.assign(TE->Scalars.size(), UndefMaskElem);
7006   Entries.clear();
7007   // Build a lists of values to tree entries.
7008   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
7009   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
7010     if (EntryPtr.get() == TE)
7011       break;
7012     if (EntryPtr->State != TreeEntry::NeedToGather)
7013       continue;
7014     for (Value *V : EntryPtr->Scalars)
7015       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
7016   }
7017   // Find all tree entries used by the gathered values. If no common entries
7018   // found - not a shuffle.
7019   // Here we build a set of tree nodes for each gathered value and trying to
7020   // find the intersection between these sets. If we have at least one common
7021   // tree node for each gathered value - we have just a permutation of the
7022   // single vector. If we have 2 different sets, we're in situation where we
7023   // have a permutation of 2 input vectors.
7024   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
7025   DenseMap<Value *, int> UsedValuesEntry;
7026   for (Value *V : TE->Scalars) {
7027     if (isa<UndefValue>(V))
7028       continue;
7029     // Build a list of tree entries where V is used.
7030     SmallPtrSet<const TreeEntry *, 4> VToTEs;
7031     auto It = ValueToTEs.find(V);
7032     if (It != ValueToTEs.end())
7033       VToTEs = It->second;
7034     if (const TreeEntry *VTE = getTreeEntry(V))
7035       VToTEs.insert(VTE);
7036     if (VToTEs.empty())
7037       return None;
7038     if (UsedTEs.empty()) {
7039       // The first iteration, just insert the list of nodes to vector.
7040       UsedTEs.push_back(VToTEs);
7041     } else {
7042       // Need to check if there are any previously used tree nodes which use V.
7043       // If there are no such nodes, consider that we have another one input
7044       // vector.
7045       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
7046       unsigned Idx = 0;
7047       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
7048         // Do we have a non-empty intersection of previously listed tree entries
7049         // and tree entries using current V?
7050         set_intersect(VToTEs, Set);
7051         if (!VToTEs.empty()) {
7052           // Yes, write the new subset and continue analysis for the next
7053           // scalar.
7054           Set.swap(VToTEs);
7055           break;
7056         }
7057         VToTEs = SavedVToTEs;
7058         ++Idx;
7059       }
7060       // No non-empty intersection found - need to add a second set of possible
7061       // source vectors.
7062       if (Idx == UsedTEs.size()) {
7063         // If the number of input vectors is greater than 2 - not a permutation,
7064         // fallback to the regular gather.
7065         if (UsedTEs.size() == 2)
7066           return None;
7067         UsedTEs.push_back(SavedVToTEs);
7068         Idx = UsedTEs.size() - 1;
7069       }
7070       UsedValuesEntry.try_emplace(V, Idx);
7071     }
7072   }
7073 
7074   if (UsedTEs.empty()) {
7075     assert(all_of(TE->Scalars, UndefValue::classof) &&
7076            "Expected vector of undefs only.");
7077     return None;
7078   }
7079 
7080   unsigned VF = 0;
7081   if (UsedTEs.size() == 1) {
7082     // Try to find the perfect match in another gather node at first.
7083     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
7084       return EntryPtr->isSame(TE->Scalars);
7085     });
7086     if (It != UsedTEs.front().end()) {
7087       Entries.push_back(*It);
7088       std::iota(Mask.begin(), Mask.end(), 0);
7089       return TargetTransformInfo::SK_PermuteSingleSrc;
7090     }
7091     // No perfect match, just shuffle, so choose the first tree node.
7092     Entries.push_back(*UsedTEs.front().begin());
7093   } else {
7094     // Try to find nodes with the same vector factor.
7095     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
7096     DenseMap<int, const TreeEntry *> VFToTE;
7097     for (const TreeEntry *TE : UsedTEs.front())
7098       VFToTE.try_emplace(TE->getVectorFactor(), TE);
7099     for (const TreeEntry *TE : UsedTEs.back()) {
7100       auto It = VFToTE.find(TE->getVectorFactor());
7101       if (It != VFToTE.end()) {
7102         VF = It->first;
7103         Entries.push_back(It->second);
7104         Entries.push_back(TE);
7105         break;
7106       }
7107     }
7108     // No 2 source vectors with the same vector factor - give up and do regular
7109     // gather.
7110     if (Entries.empty())
7111       return None;
7112   }
7113 
7114   // Build a shuffle mask for better cost estimation and vector emission.
7115   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
7116     Value *V = TE->Scalars[I];
7117     if (isa<UndefValue>(V))
7118       continue;
7119     unsigned Idx = UsedValuesEntry.lookup(V);
7120     const TreeEntry *VTE = Entries[Idx];
7121     int FoundLane = VTE->findLaneForValue(V);
7122     Mask[I] = Idx * VF + FoundLane;
7123     // Extra check required by isSingleSourceMaskImpl function (called by
7124     // ShuffleVectorInst::isSingleSourceMask).
7125     if (Mask[I] >= 2 * E)
7126       return None;
7127   }
7128   switch (Entries.size()) {
7129   case 1:
7130     return TargetTransformInfo::SK_PermuteSingleSrc;
7131   case 2:
7132     return TargetTransformInfo::SK_PermuteTwoSrc;
7133   default:
7134     break;
7135   }
7136   return None;
7137 }
7138 
7139 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
7140                                        const APInt &ShuffledIndices,
7141                                        bool NeedToShuffle) const {
7142   InstructionCost Cost =
7143       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
7144                                     /*Extract*/ false);
7145   if (NeedToShuffle)
7146     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
7147   return Cost;
7148 }
7149 
7150 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
7151   // Find the type of the operands in VL.
7152   Type *ScalarTy = VL[0]->getType();
7153   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
7154     ScalarTy = SI->getValueOperand()->getType();
7155   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
7156   bool DuplicateNonConst = false;
7157   // Find the cost of inserting/extracting values from the vector.
7158   // Check if the same elements are inserted several times and count them as
7159   // shuffle candidates.
7160   APInt ShuffledElements = APInt::getZero(VL.size());
7161   DenseSet<Value *> UniqueElements;
7162   // Iterate in reverse order to consider insert elements with the high cost.
7163   for (unsigned I = VL.size(); I > 0; --I) {
7164     unsigned Idx = I - 1;
7165     // No need to shuffle duplicates for constants.
7166     if (isConstant(VL[Idx])) {
7167       ShuffledElements.setBit(Idx);
7168       continue;
7169     }
7170     if (!UniqueElements.insert(VL[Idx]).second) {
7171       DuplicateNonConst = true;
7172       ShuffledElements.setBit(Idx);
7173     }
7174   }
7175   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
7176 }
7177 
7178 // Perform operand reordering on the instructions in VL and return the reordered
7179 // operands in Left and Right.
7180 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
7181                                              SmallVectorImpl<Value *> &Left,
7182                                              SmallVectorImpl<Value *> &Right,
7183                                              const DataLayout &DL,
7184                                              ScalarEvolution &SE,
7185                                              const BoUpSLP &R) {
7186   if (VL.empty())
7187     return;
7188   VLOperands Ops(VL, DL, SE, R);
7189   // Reorder the operands in place.
7190   Ops.reorder();
7191   Left = Ops.getVL(0);
7192   Right = Ops.getVL(1);
7193 }
7194 
7195 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
7196   // Get the basic block this bundle is in. All instructions in the bundle
7197   // should be in this block.
7198   auto *Front = E->getMainOp();
7199   auto *BB = Front->getParent();
7200   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
7201     auto *I = cast<Instruction>(V);
7202     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
7203   }));
7204 
7205   auto &&FindLastInst = [E, Front]() {
7206     Instruction *LastInst = Front;
7207     for (Value *V : E->Scalars) {
7208       auto *I = dyn_cast<Instruction>(V);
7209       if (!I)
7210         continue;
7211       if (LastInst->comesBefore(I))
7212         LastInst = I;
7213     }
7214     return LastInst;
7215   };
7216 
7217   auto &&FindFirstInst = [E, Front]() {
7218     Instruction *FirstInst = Front;
7219     for (Value *V : E->Scalars) {
7220       auto *I = dyn_cast<Instruction>(V);
7221       if (!I)
7222         continue;
7223       if (I->comesBefore(FirstInst))
7224         FirstInst = I;
7225     }
7226     return FirstInst;
7227   };
7228 
7229   // Set the insert point to the beginning of the basic block if the entry
7230   // should not be scheduled.
7231   if (E->State != TreeEntry::NeedToGather &&
7232       doesNotNeedToSchedule(E->Scalars)) {
7233     Instruction *InsertInst;
7234     if (all_of(E->Scalars, isUsedOutsideBlock))
7235       InsertInst = FindLastInst();
7236     else
7237       InsertInst = FindFirstInst();
7238     // If the instruction is PHI, set the insert point after all the PHIs.
7239     if (isa<PHINode>(InsertInst))
7240       InsertInst = BB->getFirstNonPHI();
7241     BasicBlock::iterator InsertPt = InsertInst->getIterator();
7242     Builder.SetInsertPoint(BB, InsertPt);
7243     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7244     return;
7245   }
7246 
7247   // The last instruction in the bundle in program order.
7248   Instruction *LastInst = nullptr;
7249 
7250   // Find the last instruction. The common case should be that BB has been
7251   // scheduled, and the last instruction is VL.back(). So we start with
7252   // VL.back() and iterate over schedule data until we reach the end of the
7253   // bundle. The end of the bundle is marked by null ScheduleData.
7254   if (BlocksSchedules.count(BB)) {
7255     Value *V = E->isOneOf(E->Scalars.back());
7256     if (doesNotNeedToBeScheduled(V))
7257       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
7258     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
7259     if (Bundle && Bundle->isPartOfBundle())
7260       for (; Bundle; Bundle = Bundle->NextInBundle)
7261         if (Bundle->OpValue == Bundle->Inst)
7262           LastInst = Bundle->Inst;
7263   }
7264 
7265   // LastInst can still be null at this point if there's either not an entry
7266   // for BB in BlocksSchedules or there's no ScheduleData available for
7267   // VL.back(). This can be the case if buildTree_rec aborts for various
7268   // reasons (e.g., the maximum recursion depth is reached, the maximum region
7269   // size is reached, etc.). ScheduleData is initialized in the scheduling
7270   // "dry-run".
7271   //
7272   // If this happens, we can still find the last instruction by brute force. We
7273   // iterate forwards from Front (inclusive) until we either see all
7274   // instructions in the bundle or reach the end of the block. If Front is the
7275   // last instruction in program order, LastInst will be set to Front, and we
7276   // will visit all the remaining instructions in the block.
7277   //
7278   // One of the reasons we exit early from buildTree_rec is to place an upper
7279   // bound on compile-time. Thus, taking an additional compile-time hit here is
7280   // not ideal. However, this should be exceedingly rare since it requires that
7281   // we both exit early from buildTree_rec and that the bundle be out-of-order
7282   // (causing us to iterate all the way to the end of the block).
7283   if (!LastInst) {
7284     LastInst = FindLastInst();
7285     // If the instruction is PHI, set the insert point after all the PHIs.
7286     if (isa<PHINode>(LastInst))
7287       LastInst = BB->getFirstNonPHI()->getPrevNode();
7288   }
7289   assert(LastInst && "Failed to find last instruction in bundle");
7290 
7291   // Set the insertion point after the last instruction in the bundle. Set the
7292   // debug location to Front.
7293   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
7294   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
7295 }
7296 
7297 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
7298   // List of instructions/lanes from current block and/or the blocks which are
7299   // part of the current loop. These instructions will be inserted at the end to
7300   // make it possible to optimize loops and hoist invariant instructions out of
7301   // the loops body with better chances for success.
7302   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
7303   SmallSet<int, 4> PostponedIndices;
7304   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
7305   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
7306     SmallPtrSet<BasicBlock *, 4> Visited;
7307     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
7308       InsertBB = InsertBB->getSinglePredecessor();
7309     return InsertBB && InsertBB == InstBB;
7310   };
7311   for (int I = 0, E = VL.size(); I < E; ++I) {
7312     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
7313       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
7314            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
7315           PostponedIndices.insert(I).second)
7316         PostponedInsts.emplace_back(Inst, I);
7317   }
7318 
7319   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
7320     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
7321     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
7322     if (!InsElt)
7323       return Vec;
7324     GatherShuffleSeq.insert(InsElt);
7325     CSEBlocks.insert(InsElt->getParent());
7326     // Add to our 'need-to-extract' list.
7327     if (TreeEntry *Entry = getTreeEntry(V)) {
7328       // Find which lane we need to extract.
7329       unsigned FoundLane = Entry->findLaneForValue(V);
7330       ExternalUses.emplace_back(V, InsElt, FoundLane);
7331     }
7332     return Vec;
7333   };
7334   Value *Val0 =
7335       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
7336   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
7337   Value *Vec = PoisonValue::get(VecTy);
7338   SmallVector<int> NonConsts;
7339   // Insert constant values at first.
7340   for (int I = 0, E = VL.size(); I < E; ++I) {
7341     if (PostponedIndices.contains(I))
7342       continue;
7343     if (!isConstant(VL[I])) {
7344       NonConsts.push_back(I);
7345       continue;
7346     }
7347     Vec = CreateInsertElement(Vec, VL[I], I);
7348   }
7349   // Insert non-constant values.
7350   for (int I : NonConsts)
7351     Vec = CreateInsertElement(Vec, VL[I], I);
7352   // Append instructions, which are/may be part of the loop, in the end to make
7353   // it possible to hoist non-loop-based instructions.
7354   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
7355     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
7356 
7357   return Vec;
7358 }
7359 
7360 namespace {
7361 /// Merges shuffle masks and emits final shuffle instruction, if required.
7362 class ShuffleInstructionBuilder {
7363   IRBuilderBase &Builder;
7364   const unsigned VF = 0;
7365   bool IsFinalized = false;
7366   SmallVector<int, 4> Mask;
7367   /// Holds all of the instructions that we gathered.
7368   SetVector<Instruction *> &GatherShuffleSeq;
7369   /// A list of blocks that we are going to CSE.
7370   SetVector<BasicBlock *> &CSEBlocks;
7371 
7372 public:
7373   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
7374                             SetVector<Instruction *> &GatherShuffleSeq,
7375                             SetVector<BasicBlock *> &CSEBlocks)
7376       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
7377         CSEBlocks(CSEBlocks) {}
7378 
7379   /// Adds a mask, inverting it before applying.
7380   void addInversedMask(ArrayRef<unsigned> SubMask) {
7381     if (SubMask.empty())
7382       return;
7383     SmallVector<int, 4> NewMask;
7384     inversePermutation(SubMask, NewMask);
7385     addMask(NewMask);
7386   }
7387 
7388   /// Functions adds masks, merging them into  single one.
7389   void addMask(ArrayRef<unsigned> SubMask) {
7390     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7391     addMask(NewMask);
7392   }
7393 
7394   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7395 
7396   Value *finalize(Value *V) {
7397     IsFinalized = true;
7398     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7399     if (VF == ValueVF && Mask.empty())
7400       return V;
7401     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7402     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7403     addMask(NormalizedMask);
7404 
7405     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7406       return V;
7407     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7408     if (auto *I = dyn_cast<Instruction>(Vec)) {
7409       GatherShuffleSeq.insert(I);
7410       CSEBlocks.insert(I->getParent());
7411     }
7412     return Vec;
7413   }
7414 
7415   ~ShuffleInstructionBuilder() {
7416     assert((IsFinalized || Mask.empty()) &&
7417            "Shuffle construction must be finalized.");
7418   }
7419 };
7420 } // namespace
7421 
7422 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7423   const unsigned VF = VL.size();
7424   InstructionsState S = getSameOpcode(VL);
7425   if (S.getOpcode()) {
7426     if (TreeEntry *E = getTreeEntry(S.OpValue))
7427       if (E->isSame(VL)) {
7428         Value *V = vectorizeTree(E);
7429         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7430           if (!E->ReuseShuffleIndices.empty()) {
7431             // Reshuffle to get only unique values.
7432             // If some of the scalars are duplicated in the vectorization tree
7433             // entry, we do not vectorize them but instead generate a mask for
7434             // the reuses. But if there are several users of the same entry,
7435             // they may have different vectorization factors. This is especially
7436             // important for PHI nodes. In this case, we need to adapt the
7437             // resulting instruction for the user vectorization factor and have
7438             // to reshuffle it again to take only unique elements of the vector.
7439             // Without this code the function incorrectly returns reduced vector
7440             // instruction with the same elements, not with the unique ones.
7441 
7442             // block:
7443             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7444             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7445             // ... (use %2)
7446             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7447             // br %block
7448             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7449             SmallSet<int, 4> UsedIdxs;
7450             int Pos = 0;
7451             int Sz = VL.size();
7452             for (int Idx : E->ReuseShuffleIndices) {
7453               if (Idx != Sz && Idx != UndefMaskElem &&
7454                   UsedIdxs.insert(Idx).second)
7455                 UniqueIdxs[Idx] = Pos;
7456               ++Pos;
7457             }
7458             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7459                                             "less than original vector size.");
7460             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7461             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7462           } else {
7463             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7464                    "Expected vectorization factor less "
7465                    "than original vector size.");
7466             SmallVector<int> UniformMask(VF, 0);
7467             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7468             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7469           }
7470           if (auto *I = dyn_cast<Instruction>(V)) {
7471             GatherShuffleSeq.insert(I);
7472             CSEBlocks.insert(I->getParent());
7473           }
7474         }
7475         return V;
7476       }
7477   }
7478 
7479   // Can't vectorize this, so simply build a new vector with each lane
7480   // corresponding to the requested value.
7481   return createBuildVector(VL);
7482 }
7483 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7484   unsigned VF = VL.size();
7485   // Exploit possible reuse of values across lanes.
7486   SmallVector<int> ReuseShuffleIndicies;
7487   SmallVector<Value *> UniqueValues;
7488   if (VL.size() > 2) {
7489     DenseMap<Value *, unsigned> UniquePositions;
7490     unsigned NumValues =
7491         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7492                                     return !isa<UndefValue>(V);
7493                                   }).base());
7494     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7495     int UniqueVals = 0;
7496     for (Value *V : VL.drop_back(VL.size() - VF)) {
7497       if (isa<UndefValue>(V)) {
7498         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7499         continue;
7500       }
7501       if (isConstant(V)) {
7502         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7503         UniqueValues.emplace_back(V);
7504         continue;
7505       }
7506       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7507       ReuseShuffleIndicies.emplace_back(Res.first->second);
7508       if (Res.second) {
7509         UniqueValues.emplace_back(V);
7510         ++UniqueVals;
7511       }
7512     }
7513     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7514       // Emit pure splat vector.
7515       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7516                                   UndefMaskElem);
7517     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7518       ReuseShuffleIndicies.clear();
7519       UniqueValues.clear();
7520       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7521     }
7522     UniqueValues.append(VF - UniqueValues.size(),
7523                         PoisonValue::get(VL[0]->getType()));
7524     VL = UniqueValues;
7525   }
7526 
7527   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7528                                            CSEBlocks);
7529   Value *Vec = gather(VL);
7530   if (!ReuseShuffleIndicies.empty()) {
7531     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7532     Vec = ShuffleBuilder.finalize(Vec);
7533   }
7534   return Vec;
7535 }
7536 
7537 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7538   IRBuilder<>::InsertPointGuard Guard(Builder);
7539 
7540   if (E->VectorizedValue) {
7541     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7542     return E->VectorizedValue;
7543   }
7544 
7545   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7546   unsigned VF = E->getVectorFactor();
7547   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7548                                            CSEBlocks);
7549   if (E->State == TreeEntry::NeedToGather) {
7550     if (E->getMainOp())
7551       setInsertPointAfterBundle(E);
7552     Value *Vec;
7553     SmallVector<int> Mask;
7554     SmallVector<const TreeEntry *> Entries;
7555     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7556         isGatherShuffledEntry(E, Mask, Entries);
7557     if (Shuffle.hasValue()) {
7558       assert((Entries.size() == 1 || Entries.size() == 2) &&
7559              "Expected shuffle of 1 or 2 entries.");
7560       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7561                                         Entries.back()->VectorizedValue, Mask);
7562       if (auto *I = dyn_cast<Instruction>(Vec)) {
7563         GatherShuffleSeq.insert(I);
7564         CSEBlocks.insert(I->getParent());
7565       }
7566     } else {
7567       Vec = gather(E->Scalars);
7568     }
7569     if (NeedToShuffleReuses) {
7570       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7571       Vec = ShuffleBuilder.finalize(Vec);
7572     }
7573     E->VectorizedValue = Vec;
7574     return Vec;
7575   }
7576 
7577   assert((E->State == TreeEntry::Vectorize ||
7578           E->State == TreeEntry::ScatterVectorize) &&
7579          "Unhandled state");
7580   unsigned ShuffleOrOp =
7581       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7582   Instruction *VL0 = E->getMainOp();
7583   Type *ScalarTy = VL0->getType();
7584   if (auto *Store = dyn_cast<StoreInst>(VL0))
7585     ScalarTy = Store->getValueOperand()->getType();
7586   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7587     ScalarTy = IE->getOperand(1)->getType();
7588   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7589   switch (ShuffleOrOp) {
7590     case Instruction::PHI: {
7591       assert(
7592           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7593           "PHI reordering is free.");
7594       auto *PH = cast<PHINode>(VL0);
7595       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7596       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7597       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7598       Value *V = NewPhi;
7599 
7600       // Adjust insertion point once all PHI's have been generated.
7601       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7602       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7603 
7604       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7605       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7606       V = ShuffleBuilder.finalize(V);
7607 
7608       E->VectorizedValue = V;
7609 
7610       // PHINodes may have multiple entries from the same block. We want to
7611       // visit every block once.
7612       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7613 
7614       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7615         ValueList Operands;
7616         BasicBlock *IBB = PH->getIncomingBlock(i);
7617 
7618         if (!VisitedBBs.insert(IBB).second) {
7619           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7620           continue;
7621         }
7622 
7623         Builder.SetInsertPoint(IBB->getTerminator());
7624         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7625         Value *Vec = vectorizeTree(E->getOperand(i));
7626         NewPhi->addIncoming(Vec, IBB);
7627       }
7628 
7629       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7630              "Invalid number of incoming values");
7631       return V;
7632     }
7633 
7634     case Instruction::ExtractElement: {
7635       Value *V = E->getSingleOperand(0);
7636       Builder.SetInsertPoint(VL0);
7637       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7638       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7639       V = ShuffleBuilder.finalize(V);
7640       E->VectorizedValue = V;
7641       return V;
7642     }
7643     case Instruction::ExtractValue: {
7644       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7645       Builder.SetInsertPoint(LI);
7646       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7647       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7648       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7649       Value *NewV = propagateMetadata(V, E->Scalars);
7650       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7651       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7652       NewV = ShuffleBuilder.finalize(NewV);
7653       E->VectorizedValue = NewV;
7654       return NewV;
7655     }
7656     case Instruction::InsertElement: {
7657       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7658       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7659       Value *V = vectorizeTree(E->getOperand(1));
7660 
7661       // Create InsertVector shuffle if necessary
7662       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7663         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7664       }));
7665       const unsigned NumElts =
7666           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7667       const unsigned NumScalars = E->Scalars.size();
7668 
7669       unsigned Offset = *getInsertIndex(VL0);
7670       assert(Offset < NumElts && "Failed to find vector index offset");
7671 
7672       // Create shuffle to resize vector
7673       SmallVector<int> Mask;
7674       if (!E->ReorderIndices.empty()) {
7675         inversePermutation(E->ReorderIndices, Mask);
7676         Mask.append(NumElts - NumScalars, UndefMaskElem);
7677       } else {
7678         Mask.assign(NumElts, UndefMaskElem);
7679         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7680       }
7681       // Create InsertVector shuffle if necessary
7682       bool IsIdentity = true;
7683       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7684       Mask.swap(PrevMask);
7685       for (unsigned I = 0; I < NumScalars; ++I) {
7686         Value *Scalar = E->Scalars[PrevMask[I]];
7687         unsigned InsertIdx = *getInsertIndex(Scalar);
7688         IsIdentity &= InsertIdx - Offset == I;
7689         Mask[InsertIdx - Offset] = I;
7690       }
7691       if (!IsIdentity || NumElts != NumScalars) {
7692         V = Builder.CreateShuffleVector(V, Mask);
7693         if (auto *I = dyn_cast<Instruction>(V)) {
7694           GatherShuffleSeq.insert(I);
7695           CSEBlocks.insert(I->getParent());
7696         }
7697       }
7698 
7699       if ((!IsIdentity || Offset != 0 ||
7700            !isUndefVector(FirstInsert->getOperand(0))) &&
7701           NumElts != NumScalars) {
7702         SmallVector<int> InsertMask(NumElts);
7703         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7704         for (unsigned I = 0; I < NumElts; I++) {
7705           if (Mask[I] != UndefMaskElem)
7706             InsertMask[Offset + I] = NumElts + I;
7707         }
7708 
7709         V = Builder.CreateShuffleVector(
7710             FirstInsert->getOperand(0), V, InsertMask,
7711             cast<Instruction>(E->Scalars.back())->getName());
7712         if (auto *I = dyn_cast<Instruction>(V)) {
7713           GatherShuffleSeq.insert(I);
7714           CSEBlocks.insert(I->getParent());
7715         }
7716       }
7717 
7718       ++NumVectorInstructions;
7719       E->VectorizedValue = V;
7720       return V;
7721     }
7722     case Instruction::ZExt:
7723     case Instruction::SExt:
7724     case Instruction::FPToUI:
7725     case Instruction::FPToSI:
7726     case Instruction::FPExt:
7727     case Instruction::PtrToInt:
7728     case Instruction::IntToPtr:
7729     case Instruction::SIToFP:
7730     case Instruction::UIToFP:
7731     case Instruction::Trunc:
7732     case Instruction::FPTrunc:
7733     case Instruction::BitCast: {
7734       setInsertPointAfterBundle(E);
7735 
7736       Value *InVec = vectorizeTree(E->getOperand(0));
7737 
7738       if (E->VectorizedValue) {
7739         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7740         return E->VectorizedValue;
7741       }
7742 
7743       auto *CI = cast<CastInst>(VL0);
7744       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7745       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7746       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7747       V = ShuffleBuilder.finalize(V);
7748 
7749       E->VectorizedValue = V;
7750       ++NumVectorInstructions;
7751       return V;
7752     }
7753     case Instruction::FCmp:
7754     case Instruction::ICmp: {
7755       setInsertPointAfterBundle(E);
7756 
7757       Value *L = vectorizeTree(E->getOperand(0));
7758       Value *R = vectorizeTree(E->getOperand(1));
7759 
7760       if (E->VectorizedValue) {
7761         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7762         return E->VectorizedValue;
7763       }
7764 
7765       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7766       Value *V = Builder.CreateCmp(P0, L, R);
7767       propagateIRFlags(V, E->Scalars, VL0);
7768       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7769       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7770       V = ShuffleBuilder.finalize(V);
7771 
7772       E->VectorizedValue = V;
7773       ++NumVectorInstructions;
7774       return V;
7775     }
7776     case Instruction::Select: {
7777       setInsertPointAfterBundle(E);
7778 
7779       Value *Cond = vectorizeTree(E->getOperand(0));
7780       Value *True = vectorizeTree(E->getOperand(1));
7781       Value *False = vectorizeTree(E->getOperand(2));
7782 
7783       if (E->VectorizedValue) {
7784         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7785         return E->VectorizedValue;
7786       }
7787 
7788       Value *V = Builder.CreateSelect(Cond, True, False);
7789       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7790       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7791       V = ShuffleBuilder.finalize(V);
7792 
7793       E->VectorizedValue = V;
7794       ++NumVectorInstructions;
7795       return V;
7796     }
7797     case Instruction::FNeg: {
7798       setInsertPointAfterBundle(E);
7799 
7800       Value *Op = vectorizeTree(E->getOperand(0));
7801 
7802       if (E->VectorizedValue) {
7803         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7804         return E->VectorizedValue;
7805       }
7806 
7807       Value *V = Builder.CreateUnOp(
7808           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7809       propagateIRFlags(V, E->Scalars, VL0);
7810       if (auto *I = dyn_cast<Instruction>(V))
7811         V = propagateMetadata(I, E->Scalars);
7812 
7813       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7814       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7815       V = ShuffleBuilder.finalize(V);
7816 
7817       E->VectorizedValue = V;
7818       ++NumVectorInstructions;
7819 
7820       return V;
7821     }
7822     case Instruction::Add:
7823     case Instruction::FAdd:
7824     case Instruction::Sub:
7825     case Instruction::FSub:
7826     case Instruction::Mul:
7827     case Instruction::FMul:
7828     case Instruction::UDiv:
7829     case Instruction::SDiv:
7830     case Instruction::FDiv:
7831     case Instruction::URem:
7832     case Instruction::SRem:
7833     case Instruction::FRem:
7834     case Instruction::Shl:
7835     case Instruction::LShr:
7836     case Instruction::AShr:
7837     case Instruction::And:
7838     case Instruction::Or:
7839     case Instruction::Xor: {
7840       setInsertPointAfterBundle(E);
7841 
7842       Value *LHS = vectorizeTree(E->getOperand(0));
7843       Value *RHS = vectorizeTree(E->getOperand(1));
7844 
7845       if (E->VectorizedValue) {
7846         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7847         return E->VectorizedValue;
7848       }
7849 
7850       Value *V = Builder.CreateBinOp(
7851           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7852           RHS);
7853       propagateIRFlags(V, E->Scalars, VL0);
7854       if (auto *I = dyn_cast<Instruction>(V))
7855         V = propagateMetadata(I, E->Scalars);
7856 
7857       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7858       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7859       V = ShuffleBuilder.finalize(V);
7860 
7861       E->VectorizedValue = V;
7862       ++NumVectorInstructions;
7863 
7864       return V;
7865     }
7866     case Instruction::Load: {
7867       // Loads are inserted at the head of the tree because we don't want to
7868       // sink them all the way down past store instructions.
7869       setInsertPointAfterBundle(E);
7870 
7871       LoadInst *LI = cast<LoadInst>(VL0);
7872       Instruction *NewLI;
7873       unsigned AS = LI->getPointerAddressSpace();
7874       Value *PO = LI->getPointerOperand();
7875       if (E->State == TreeEntry::Vectorize) {
7876         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7877         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7878 
7879         // The pointer operand uses an in-tree scalar so we add the new BitCast
7880         // or LoadInst to ExternalUses list to make sure that an extract will
7881         // be generated in the future.
7882         if (TreeEntry *Entry = getTreeEntry(PO)) {
7883           // Find which lane we need to extract.
7884           unsigned FoundLane = Entry->findLaneForValue(PO);
7885           ExternalUses.emplace_back(
7886               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7887         }
7888       } else {
7889         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7890         Value *VecPtr = vectorizeTree(E->getOperand(0));
7891         // Use the minimum alignment of the gathered loads.
7892         Align CommonAlignment = LI->getAlign();
7893         for (Value *V : E->Scalars)
7894           CommonAlignment =
7895               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7896         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7897       }
7898       Value *V = propagateMetadata(NewLI, E->Scalars);
7899 
7900       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7901       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7902       V = ShuffleBuilder.finalize(V);
7903       E->VectorizedValue = V;
7904       ++NumVectorInstructions;
7905       return V;
7906     }
7907     case Instruction::Store: {
7908       auto *SI = cast<StoreInst>(VL0);
7909       unsigned AS = SI->getPointerAddressSpace();
7910 
7911       setInsertPointAfterBundle(E);
7912 
7913       Value *VecValue = vectorizeTree(E->getOperand(0));
7914       ShuffleBuilder.addMask(E->ReorderIndices);
7915       VecValue = ShuffleBuilder.finalize(VecValue);
7916 
7917       Value *ScalarPtr = SI->getPointerOperand();
7918       Value *VecPtr = Builder.CreateBitCast(
7919           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7920       StoreInst *ST =
7921           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7922 
7923       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7924       // StoreInst to ExternalUses to make sure that an extract will be
7925       // generated in the future.
7926       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7927         // Find which lane we need to extract.
7928         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7929         ExternalUses.push_back(ExternalUser(
7930             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7931             FoundLane));
7932       }
7933 
7934       Value *V = propagateMetadata(ST, E->Scalars);
7935 
7936       E->VectorizedValue = V;
7937       ++NumVectorInstructions;
7938       return V;
7939     }
7940     case Instruction::GetElementPtr: {
7941       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7942       setInsertPointAfterBundle(E);
7943 
7944       Value *Op0 = vectorizeTree(E->getOperand(0));
7945 
7946       SmallVector<Value *> OpVecs;
7947       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7948         Value *OpVec = vectorizeTree(E->getOperand(J));
7949         OpVecs.push_back(OpVec);
7950       }
7951 
7952       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7953       if (Instruction *I = dyn_cast<Instruction>(V))
7954         V = propagateMetadata(I, E->Scalars);
7955 
7956       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7957       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7958       V = ShuffleBuilder.finalize(V);
7959 
7960       E->VectorizedValue = V;
7961       ++NumVectorInstructions;
7962 
7963       return V;
7964     }
7965     case Instruction::Call: {
7966       CallInst *CI = cast<CallInst>(VL0);
7967       setInsertPointAfterBundle(E);
7968 
7969       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7970       if (Function *FI = CI->getCalledFunction())
7971         IID = FI->getIntrinsicID();
7972 
7973       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7974 
7975       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7976       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7977                           VecCallCosts.first <= VecCallCosts.second;
7978 
7979       Value *ScalarArg = nullptr;
7980       std::vector<Value *> OpVecs;
7981       SmallVector<Type *, 2> TysForDecl =
7982           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7983       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7984         ValueList OpVL;
7985         // Some intrinsics have scalar arguments. This argument should not be
7986         // vectorized.
7987         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7988           CallInst *CEI = cast<CallInst>(VL0);
7989           ScalarArg = CEI->getArgOperand(j);
7990           OpVecs.push_back(CEI->getArgOperand(j));
7991           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7992             TysForDecl.push_back(ScalarArg->getType());
7993           continue;
7994         }
7995 
7996         Value *OpVec = vectorizeTree(E->getOperand(j));
7997         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7998         OpVecs.push_back(OpVec);
7999         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
8000           TysForDecl.push_back(OpVec->getType());
8001       }
8002 
8003       Function *CF;
8004       if (!UseIntrinsic) {
8005         VFShape Shape =
8006             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
8007                                   VecTy->getNumElements())),
8008                          false /*HasGlobalPred*/);
8009         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
8010       } else {
8011         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
8012       }
8013 
8014       SmallVector<OperandBundleDef, 1> OpBundles;
8015       CI->getOperandBundlesAsDefs(OpBundles);
8016       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
8017 
8018       // The scalar argument uses an in-tree scalar so we add the new vectorized
8019       // call to ExternalUses list to make sure that an extract will be
8020       // generated in the future.
8021       if (ScalarArg) {
8022         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
8023           // Find which lane we need to extract.
8024           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
8025           ExternalUses.push_back(
8026               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
8027         }
8028       }
8029 
8030       propagateIRFlags(V, E->Scalars, VL0);
8031       ShuffleBuilder.addInversedMask(E->ReorderIndices);
8032       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
8033       V = ShuffleBuilder.finalize(V);
8034 
8035       E->VectorizedValue = V;
8036       ++NumVectorInstructions;
8037       return V;
8038     }
8039     case Instruction::ShuffleVector: {
8040       assert(E->isAltShuffle() &&
8041              ((Instruction::isBinaryOp(E->getOpcode()) &&
8042                Instruction::isBinaryOp(E->getAltOpcode())) ||
8043               (Instruction::isCast(E->getOpcode()) &&
8044                Instruction::isCast(E->getAltOpcode())) ||
8045               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
8046              "Invalid Shuffle Vector Operand");
8047 
8048       Value *LHS = nullptr, *RHS = nullptr;
8049       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
8050         setInsertPointAfterBundle(E);
8051         LHS = vectorizeTree(E->getOperand(0));
8052         RHS = vectorizeTree(E->getOperand(1));
8053       } else {
8054         setInsertPointAfterBundle(E);
8055         LHS = vectorizeTree(E->getOperand(0));
8056       }
8057 
8058       if (E->VectorizedValue) {
8059         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
8060         return E->VectorizedValue;
8061       }
8062 
8063       Value *V0, *V1;
8064       if (Instruction::isBinaryOp(E->getOpcode())) {
8065         V0 = Builder.CreateBinOp(
8066             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
8067         V1 = Builder.CreateBinOp(
8068             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
8069       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
8070         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
8071         auto *AltCI = cast<CmpInst>(E->getAltOp());
8072         CmpInst::Predicate AltPred = AltCI->getPredicate();
8073         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
8074       } else {
8075         V0 = Builder.CreateCast(
8076             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
8077         V1 = Builder.CreateCast(
8078             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
8079       }
8080       // Add V0 and V1 to later analysis to try to find and remove matching
8081       // instruction, if any.
8082       for (Value *V : {V0, V1}) {
8083         if (auto *I = dyn_cast<Instruction>(V)) {
8084           GatherShuffleSeq.insert(I);
8085           CSEBlocks.insert(I->getParent());
8086         }
8087       }
8088 
8089       // Create shuffle to take alternate operations from the vector.
8090       // Also, gather up main and alt scalar ops to propagate IR flags to
8091       // each vector operation.
8092       ValueList OpScalars, AltScalars;
8093       SmallVector<int> Mask;
8094       buildShuffleEntryMask(
8095           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
8096           [E](Instruction *I) {
8097             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
8098             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
8099           },
8100           Mask, &OpScalars, &AltScalars);
8101 
8102       propagateIRFlags(V0, OpScalars);
8103       propagateIRFlags(V1, AltScalars);
8104 
8105       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
8106       if (auto *I = dyn_cast<Instruction>(V)) {
8107         V = propagateMetadata(I, E->Scalars);
8108         GatherShuffleSeq.insert(I);
8109         CSEBlocks.insert(I->getParent());
8110       }
8111       V = ShuffleBuilder.finalize(V);
8112 
8113       E->VectorizedValue = V;
8114       ++NumVectorInstructions;
8115 
8116       return V;
8117     }
8118     default:
8119     llvm_unreachable("unknown inst");
8120   }
8121   return nullptr;
8122 }
8123 
8124 Value *BoUpSLP::vectorizeTree() {
8125   ExtraValueToDebugLocsMap ExternallyUsedValues;
8126   return vectorizeTree(ExternallyUsedValues);
8127 }
8128 
8129 namespace {
8130 /// Data type for handling buildvector sequences with the reused scalars from
8131 /// other tree entries.
8132 struct ShuffledInsertData {
8133   /// List of insertelements to be replaced by shuffles.
8134   SmallVector<InsertElementInst *> InsertElements;
8135   /// The parent vectors and shuffle mask for the given list of inserts.
8136   MapVector<Value *, SmallVector<int>> ValueMasks;
8137 };
8138 } // namespace
8139 
8140 Value *
8141 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
8142   // All blocks must be scheduled before any instructions are inserted.
8143   for (auto &BSIter : BlocksSchedules) {
8144     scheduleBlock(BSIter.second.get());
8145   }
8146 
8147   Builder.SetInsertPoint(&F->getEntryBlock().front());
8148   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
8149 
8150   // If the vectorized tree can be rewritten in a smaller type, we truncate the
8151   // vectorized root. InstCombine will then rewrite the entire expression. We
8152   // sign extend the extracted values below.
8153   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
8154   if (MinBWs.count(ScalarRoot)) {
8155     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
8156       // If current instr is a phi and not the last phi, insert it after the
8157       // last phi node.
8158       if (isa<PHINode>(I))
8159         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
8160       else
8161         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
8162     }
8163     auto BundleWidth = VectorizableTree[0]->Scalars.size();
8164     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
8165     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
8166     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
8167     VectorizableTree[0]->VectorizedValue = Trunc;
8168   }
8169 
8170   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
8171                     << " values .\n");
8172 
8173   SmallVector<ShuffledInsertData> ShuffledInserts;
8174   // Maps vector instruction to original insertelement instruction
8175   DenseMap<Value *, InsertElementInst *> VectorToInsertElement;
8176   // Extract all of the elements with the external uses.
8177   for (const auto &ExternalUse : ExternalUses) {
8178     Value *Scalar = ExternalUse.Scalar;
8179     llvm::User *User = ExternalUse.User;
8180 
8181     // Skip users that we already RAUW. This happens when one instruction
8182     // has multiple uses of the same value.
8183     if (User && !is_contained(Scalar->users(), User))
8184       continue;
8185     TreeEntry *E = getTreeEntry(Scalar);
8186     assert(E && "Invalid scalar");
8187     assert(E->State != TreeEntry::NeedToGather &&
8188            "Extracting from a gather list");
8189 
8190     Value *Vec = E->VectorizedValue;
8191     assert(Vec && "Can't find vectorizable value");
8192 
8193     Value *Lane = Builder.getInt32(ExternalUse.Lane);
8194     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
8195       if (Scalar->getType() != Vec->getType()) {
8196         Value *Ex;
8197         // "Reuse" the existing extract to improve final codegen.
8198         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
8199           Ex = Builder.CreateExtractElement(ES->getOperand(0),
8200                                             ES->getOperand(1));
8201         } else {
8202           Ex = Builder.CreateExtractElement(Vec, Lane);
8203         }
8204         // If necessary, sign-extend or zero-extend ScalarRoot
8205         // to the larger type.
8206         if (!MinBWs.count(ScalarRoot))
8207           return Ex;
8208         if (MinBWs[ScalarRoot].second)
8209           return Builder.CreateSExt(Ex, Scalar->getType());
8210         return Builder.CreateZExt(Ex, Scalar->getType());
8211       }
8212       assert(isa<FixedVectorType>(Scalar->getType()) &&
8213              isa<InsertElementInst>(Scalar) &&
8214              "In-tree scalar of vector type is not insertelement?");
8215       auto *IE = cast<InsertElementInst>(Scalar);
8216       VectorToInsertElement.try_emplace(Vec, IE);
8217       return Vec;
8218     };
8219     // If User == nullptr, the Scalar is used as extra arg. Generate
8220     // ExtractElement instruction and update the record for this scalar in
8221     // ExternallyUsedValues.
8222     if (!User) {
8223       assert(ExternallyUsedValues.count(Scalar) &&
8224              "Scalar with nullptr as an external user must be registered in "
8225              "ExternallyUsedValues map");
8226       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8227         Builder.SetInsertPoint(VecI->getParent(),
8228                                std::next(VecI->getIterator()));
8229       } else {
8230         Builder.SetInsertPoint(&F->getEntryBlock().front());
8231       }
8232       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8233       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
8234       auto &NewInstLocs = ExternallyUsedValues[NewInst];
8235       auto It = ExternallyUsedValues.find(Scalar);
8236       assert(It != ExternallyUsedValues.end() &&
8237              "Externally used scalar is not found in ExternallyUsedValues");
8238       NewInstLocs.append(It->second);
8239       ExternallyUsedValues.erase(Scalar);
8240       // Required to update internally referenced instructions.
8241       Scalar->replaceAllUsesWith(NewInst);
8242       continue;
8243     }
8244 
8245     if (auto *VU = dyn_cast<InsertElementInst>(User)) {
8246       if (!Scalar->getType()->isVectorTy()) {
8247         if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) {
8248           Optional<unsigned> InsertIdx = getInsertIndex(VU);
8249           if (InsertIdx) {
8250             auto *It =
8251                 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) {
8252                   // Checks if 2 insertelements are from the same buildvector.
8253                   InsertElementInst *VecInsert = Data.InsertElements.front();
8254                   return areTwoInsertFromSameBuildVector(VU, VecInsert);
8255                 });
8256             unsigned Idx = *InsertIdx;
8257             if (It == ShuffledInserts.end()) {
8258               (void)ShuffledInserts.emplace_back();
8259               It = std::next(ShuffledInserts.begin(),
8260                              ShuffledInserts.size() - 1);
8261               SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
8262               if (Mask.empty())
8263                 Mask.assign(FTy->getNumElements(), UndefMaskElem);
8264               // Find the insertvector, vectorized in tree, if any.
8265               Value *Base = VU;
8266               while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
8267                 if (IEBase != User &&
8268                     (!IEBase->hasOneUse() ||
8269                      getInsertIndex(IEBase).getValueOr(Idx) == Idx))
8270                   break;
8271                 // Build the mask for the vectorized insertelement instructions.
8272                 if (const TreeEntry *E = getTreeEntry(IEBase)) {
8273                   do {
8274                     IEBase = cast<InsertElementInst>(Base);
8275                     int IEIdx = *getInsertIndex(IEBase);
8276                     assert(Mask[Idx] == UndefMaskElem &&
8277                            "InsertElementInstruction used already.");
8278                     Mask[IEIdx] = IEIdx;
8279                     Base = IEBase->getOperand(0);
8280                   } while (E == getTreeEntry(Base));
8281                   break;
8282                 }
8283                 Base = cast<InsertElementInst>(Base)->getOperand(0);
8284                 // After the vectorization the def-use chain has changed, need
8285                 // to look through original insertelement instructions, if they
8286                 // get replaced by vector instructions.
8287                 auto It = VectorToInsertElement.find(Base);
8288                 if (It != VectorToInsertElement.end())
8289                   Base = It->second;
8290               }
8291             }
8292             SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
8293             if (Mask.empty())
8294               Mask.assign(FTy->getNumElements(), UndefMaskElem);
8295             Mask[Idx] = ExternalUse.Lane;
8296             It->InsertElements.push_back(cast<InsertElementInst>(User));
8297             continue;
8298           }
8299         }
8300       }
8301     }
8302 
8303     // Generate extracts for out-of-tree users.
8304     // Find the insertion point for the extractelement lane.
8305     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
8306       if (PHINode *PH = dyn_cast<PHINode>(User)) {
8307         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
8308           if (PH->getIncomingValue(i) == Scalar) {
8309             Instruction *IncomingTerminator =
8310                 PH->getIncomingBlock(i)->getTerminator();
8311             if (isa<CatchSwitchInst>(IncomingTerminator)) {
8312               Builder.SetInsertPoint(VecI->getParent(),
8313                                      std::next(VecI->getIterator()));
8314             } else {
8315               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
8316             }
8317             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8318             CSEBlocks.insert(PH->getIncomingBlock(i));
8319             PH->setOperand(i, NewInst);
8320           }
8321         }
8322       } else {
8323         Builder.SetInsertPoint(cast<Instruction>(User));
8324         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8325         CSEBlocks.insert(cast<Instruction>(User)->getParent());
8326         User->replaceUsesOfWith(Scalar, NewInst);
8327       }
8328     } else {
8329       Builder.SetInsertPoint(&F->getEntryBlock().front());
8330       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
8331       CSEBlocks.insert(&F->getEntryBlock());
8332       User->replaceUsesOfWith(Scalar, NewInst);
8333     }
8334 
8335     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
8336   }
8337 
8338   // Checks if the mask is an identity mask.
8339   auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) {
8340     int Limit = Mask.size();
8341     return VecTy->getNumElements() == Mask.size() &&
8342            all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) &&
8343            ShuffleVectorInst::isIdentityMask(Mask);
8344   };
8345   // Tries to combine 2 different masks into single one.
8346   auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) {
8347     SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem);
8348     for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
8349       if (ExtMask[I] == UndefMaskElem)
8350         continue;
8351       NewMask[I] = Mask[ExtMask[I]];
8352     }
8353     Mask.swap(NewMask);
8354   };
8355   // Peek through shuffles, trying to simplify the final shuffle code.
8356   auto &&PeekThroughShuffles =
8357       [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask,
8358                                        bool CheckForLengthChange = false) {
8359         while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
8360           // Exit if not a fixed vector type or changing size shuffle.
8361           if (!isa<FixedVectorType>(SV->getType()) ||
8362               (CheckForLengthChange && SV->changesLength()))
8363             break;
8364           // Exit if the identity or broadcast mask is found.
8365           if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) ||
8366               SV->isZeroEltSplat())
8367             break;
8368           bool IsOp1Undef = isUndefVector(SV->getOperand(0));
8369           bool IsOp2Undef = isUndefVector(SV->getOperand(1));
8370           if (!IsOp1Undef && !IsOp2Undef)
8371             break;
8372           SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(),
8373                                        SV->getShuffleMask().end());
8374           CombineMasks(ShuffleMask, Mask);
8375           Mask.swap(ShuffleMask);
8376           if (IsOp2Undef)
8377             V = SV->getOperand(0);
8378           else
8379             V = SV->getOperand(1);
8380         }
8381       };
8382   // Smart shuffle instruction emission, walks through shuffles trees and
8383   // tries to find the best matching vector for the actual shuffle
8384   // instruction.
8385   auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles,
8386                           &CombineMasks](Value *V1, Value *V2,
8387                                          ArrayRef<int> Mask) -> Value * {
8388     assert(V1 && "Expected at least one vector value.");
8389     if (V2 && !isUndefVector(V2)) {
8390       // Peek through shuffles.
8391       Value *Op1 = V1;
8392       Value *Op2 = V2;
8393       int VF =
8394           cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
8395       SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem);
8396       SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem);
8397       for (int I = 0, E = Mask.size(); I < E; ++I) {
8398         if (Mask[I] < VF)
8399           CombinedMask1[I] = Mask[I];
8400         else
8401           CombinedMask2[I] = Mask[I] - VF;
8402       }
8403       Value *PrevOp1;
8404       Value *PrevOp2;
8405       do {
8406         PrevOp1 = Op1;
8407         PrevOp2 = Op2;
8408         PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true);
8409         PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true);
8410         // Check if we have 2 resizing shuffles - need to peek through operands
8411         // again.
8412         if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1))
8413           if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2))
8414             if (SV1->getOperand(0)->getType() ==
8415                     SV2->getOperand(0)->getType() &&
8416                 SV1->getOperand(0)->getType() != SV1->getType() &&
8417                 isUndefVector(SV1->getOperand(1)) &&
8418                 isUndefVector(SV2->getOperand(1))) {
8419               Op1 = SV1->getOperand(0);
8420               Op2 = SV2->getOperand(0);
8421               SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(),
8422                                             SV1->getShuffleMask().end());
8423               CombineMasks(ShuffleMask1, CombinedMask1);
8424               CombinedMask1.swap(ShuffleMask1);
8425               SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(),
8426                                             SV2->getShuffleMask().end());
8427               CombineMasks(ShuffleMask2, CombinedMask2);
8428               CombinedMask2.swap(ShuffleMask2);
8429             }
8430       } while (PrevOp1 != Op1 || PrevOp2 != Op2);
8431       VF = cast<VectorType>(Op1->getType())
8432                ->getElementCount()
8433                .getKnownMinValue();
8434       for (int I = 0, E = Mask.size(); I < E; ++I) {
8435         if (CombinedMask2[I] != UndefMaskElem) {
8436           assert(CombinedMask1[I] == UndefMaskElem &&
8437                  "Expected undefined mask element");
8438           CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF);
8439         }
8440       }
8441       Value *Vec = Builder.CreateShuffleVector(
8442           Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2,
8443           CombinedMask1);
8444       if (auto *I = dyn_cast<Instruction>(Vec)) {
8445         GatherShuffleSeq.insert(I);
8446         CSEBlocks.insert(I->getParent());
8447       }
8448       return Vec;
8449     }
8450     if (isa<PoisonValue>(V1))
8451       return PoisonValue::get(FixedVectorType::get(
8452           cast<VectorType>(V1->getType())->getElementType(), Mask.size()));
8453     Value *Op = V1;
8454     SmallVector<int> CombinedMask(Mask.begin(), Mask.end());
8455     PeekThroughShuffles(Op, CombinedMask);
8456     if (!isa<FixedVectorType>(Op->getType()) ||
8457         !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) {
8458       Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask);
8459       if (auto *I = dyn_cast<Instruction>(Vec)) {
8460         GatherShuffleSeq.insert(I);
8461         CSEBlocks.insert(I->getParent());
8462       }
8463       return Vec;
8464     }
8465     return Op;
8466   };
8467 
8468   auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask) {
8469     unsigned VF = Mask.size();
8470     unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
8471     if (VF != VecVF) {
8472       if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) {
8473         Vec = CreateShuffle(Vec, nullptr, Mask);
8474         return std::make_pair(Vec, true);
8475       }
8476       SmallVector<int> ResizeMask(VF, UndefMaskElem);
8477       for (unsigned I = 0; I < VF; ++I) {
8478         if (Mask[I] != UndefMaskElem)
8479           ResizeMask[Mask[I]] = Mask[I];
8480       }
8481       Vec = CreateShuffle(Vec, nullptr, ResizeMask);
8482     }
8483 
8484     return std::make_pair(Vec, false);
8485   };
8486   // Perform shuffling of the vectorize tree entries for better handling of
8487   // external extracts.
8488   for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) {
8489     // Find the first and the last instruction in the list of insertelements.
8490     sort(ShuffledInserts[I].InsertElements, isFirstInsertElement);
8491     InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front();
8492     InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back();
8493     Builder.SetInsertPoint(LastInsert);
8494     auto Vector = ShuffledInserts[I].ValueMasks.takeVector();
8495     Value *NewInst = performExtractsShuffleAction<Value>(
8496         makeMutableArrayRef(Vector.data(), Vector.size()),
8497         FirstInsert->getOperand(0),
8498         [](Value *Vec) {
8499           return cast<VectorType>(Vec->getType())
8500               ->getElementCount()
8501               .getKnownMinValue();
8502         },
8503         ResizeToVF,
8504         [FirstInsert, &CreateShuffle](ArrayRef<int> Mask,
8505                                       ArrayRef<Value *> Vals) {
8506           assert((Vals.size() == 1 || Vals.size() == 2) &&
8507                  "Expected exactly 1 or 2 input values.");
8508           if (Vals.size() == 1) {
8509             // Do not create shuffle if the mask is a simple identity
8510             // non-resizing mask.
8511             if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType())
8512                                    ->getNumElements() ||
8513                 !ShuffleVectorInst::isIdentityMask(Mask))
8514               return CreateShuffle(Vals.front(), nullptr, Mask);
8515             return Vals.front();
8516           }
8517           return CreateShuffle(Vals.front() ? Vals.front()
8518                                             : FirstInsert->getOperand(0),
8519                                Vals.back(), Mask);
8520         });
8521     auto It = ShuffledInserts[I].InsertElements.rbegin();
8522     // Rebuild buildvector chain.
8523     InsertElementInst *II = nullptr;
8524     if (It != ShuffledInserts[I].InsertElements.rend())
8525       II = *It;
8526     SmallVector<Instruction *> Inserts;
8527     while (It != ShuffledInserts[I].InsertElements.rend()) {
8528       assert(II && "Must be an insertelement instruction.");
8529       if (*It == II)
8530         ++It;
8531       else
8532         Inserts.push_back(cast<Instruction>(II));
8533       II = dyn_cast<InsertElementInst>(II->getOperand(0));
8534     }
8535     for (Instruction *II : reverse(Inserts)) {
8536       II->replaceUsesOfWith(II->getOperand(0), NewInst);
8537       if (auto *NewI = dyn_cast<Instruction>(NewInst))
8538         if (II->getParent() == NewI->getParent() && II->comesBefore(NewI))
8539           II->moveAfter(NewI);
8540       NewInst = II;
8541     }
8542     LastInsert->replaceAllUsesWith(NewInst);
8543     for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) {
8544       IE->replaceUsesOfWith(IE->getOperand(1),
8545                             PoisonValue::get(IE->getOperand(1)->getType()));
8546       eraseInstruction(IE);
8547     }
8548     CSEBlocks.insert(LastInsert->getParent());
8549   }
8550 
8551   // For each vectorized value:
8552   for (auto &TEPtr : VectorizableTree) {
8553     TreeEntry *Entry = TEPtr.get();
8554 
8555     // No need to handle users of gathered values.
8556     if (Entry->State == TreeEntry::NeedToGather)
8557       continue;
8558 
8559     assert(Entry->VectorizedValue && "Can't find vectorizable value");
8560 
8561     // For each lane:
8562     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
8563       Value *Scalar = Entry->Scalars[Lane];
8564 
8565 #ifndef NDEBUG
8566       Type *Ty = Scalar->getType();
8567       if (!Ty->isVoidTy()) {
8568         for (User *U : Scalar->users()) {
8569           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
8570 
8571           // It is legal to delete users in the ignorelist.
8572           assert((getTreeEntry(U) || UserIgnoreList.contains(U) ||
8573                   (isa_and_nonnull<Instruction>(U) &&
8574                    isDeleted(cast<Instruction>(U)))) &&
8575                  "Deleting out-of-tree value");
8576         }
8577       }
8578 #endif
8579       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
8580       eraseInstruction(cast<Instruction>(Scalar));
8581     }
8582   }
8583 
8584   Builder.ClearInsertionPoint();
8585   InstrElementSize.clear();
8586 
8587   return VectorizableTree[0]->VectorizedValue;
8588 }
8589 
8590 void BoUpSLP::optimizeGatherSequence() {
8591   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
8592                     << " gather sequences instructions.\n");
8593   // LICM InsertElementInst sequences.
8594   for (Instruction *I : GatherShuffleSeq) {
8595     if (isDeleted(I))
8596       continue;
8597 
8598     // Check if this block is inside a loop.
8599     Loop *L = LI->getLoopFor(I->getParent());
8600     if (!L)
8601       continue;
8602 
8603     // Check if it has a preheader.
8604     BasicBlock *PreHeader = L->getLoopPreheader();
8605     if (!PreHeader)
8606       continue;
8607 
8608     // If the vector or the element that we insert into it are
8609     // instructions that are defined in this basic block then we can't
8610     // hoist this instruction.
8611     if (any_of(I->operands(), [L](Value *V) {
8612           auto *OpI = dyn_cast<Instruction>(V);
8613           return OpI && L->contains(OpI);
8614         }))
8615       continue;
8616 
8617     // We can hoist this instruction. Move it to the pre-header.
8618     I->moveBefore(PreHeader->getTerminator());
8619   }
8620 
8621   // Make a list of all reachable blocks in our CSE queue.
8622   SmallVector<const DomTreeNode *, 8> CSEWorkList;
8623   CSEWorkList.reserve(CSEBlocks.size());
8624   for (BasicBlock *BB : CSEBlocks)
8625     if (DomTreeNode *N = DT->getNode(BB)) {
8626       assert(DT->isReachableFromEntry(N));
8627       CSEWorkList.push_back(N);
8628     }
8629 
8630   // Sort blocks by domination. This ensures we visit a block after all blocks
8631   // dominating it are visited.
8632   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
8633     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
8634            "Different nodes should have different DFS numbers");
8635     return A->getDFSNumIn() < B->getDFSNumIn();
8636   });
8637 
8638   // Less defined shuffles can be replaced by the more defined copies.
8639   // Between two shuffles one is less defined if it has the same vector operands
8640   // and its mask indeces are the same as in the first one or undefs. E.g.
8641   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
8642   // poison, <0, 0, 0, 0>.
8643   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
8644                                            SmallVectorImpl<int> &NewMask) {
8645     if (I1->getType() != I2->getType())
8646       return false;
8647     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
8648     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
8649     if (!SI1 || !SI2)
8650       return I1->isIdenticalTo(I2);
8651     if (SI1->isIdenticalTo(SI2))
8652       return true;
8653     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
8654       if (SI1->getOperand(I) != SI2->getOperand(I))
8655         return false;
8656     // Check if the second instruction is more defined than the first one.
8657     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
8658     ArrayRef<int> SM1 = SI1->getShuffleMask();
8659     // Count trailing undefs in the mask to check the final number of used
8660     // registers.
8661     unsigned LastUndefsCnt = 0;
8662     for (int I = 0, E = NewMask.size(); I < E; ++I) {
8663       if (SM1[I] == UndefMaskElem)
8664         ++LastUndefsCnt;
8665       else
8666         LastUndefsCnt = 0;
8667       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
8668           NewMask[I] != SM1[I])
8669         return false;
8670       if (NewMask[I] == UndefMaskElem)
8671         NewMask[I] = SM1[I];
8672     }
8673     // Check if the last undefs actually change the final number of used vector
8674     // registers.
8675     return SM1.size() - LastUndefsCnt > 1 &&
8676            TTI->getNumberOfParts(SI1->getType()) ==
8677                TTI->getNumberOfParts(
8678                    FixedVectorType::get(SI1->getType()->getElementType(),
8679                                         SM1.size() - LastUndefsCnt));
8680   };
8681   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8682   // instructions. TODO: We can further optimize this scan if we split the
8683   // instructions into different buckets based on the insert lane.
8684   SmallVector<Instruction *, 16> Visited;
8685   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8686     assert(*I &&
8687            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8688            "Worklist not sorted properly!");
8689     BasicBlock *BB = (*I)->getBlock();
8690     // For all instructions in blocks containing gather sequences:
8691     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8692       if (isDeleted(&In))
8693         continue;
8694       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8695           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8696         continue;
8697 
8698       // Check if we can replace this instruction with any of the
8699       // visited instructions.
8700       bool Replaced = false;
8701       for (Instruction *&V : Visited) {
8702         SmallVector<int> NewMask;
8703         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8704             DT->dominates(V->getParent(), In.getParent())) {
8705           In.replaceAllUsesWith(V);
8706           eraseInstruction(&In);
8707           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8708             if (!NewMask.empty())
8709               SI->setShuffleMask(NewMask);
8710           Replaced = true;
8711           break;
8712         }
8713         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8714             GatherShuffleSeq.contains(V) &&
8715             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8716             DT->dominates(In.getParent(), V->getParent())) {
8717           In.moveAfter(V);
8718           V->replaceAllUsesWith(&In);
8719           eraseInstruction(V);
8720           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8721             if (!NewMask.empty())
8722               SI->setShuffleMask(NewMask);
8723           V = &In;
8724           Replaced = true;
8725           break;
8726         }
8727       }
8728       if (!Replaced) {
8729         assert(!is_contained(Visited, &In));
8730         Visited.push_back(&In);
8731       }
8732     }
8733   }
8734   CSEBlocks.clear();
8735   GatherShuffleSeq.clear();
8736 }
8737 
8738 BoUpSLP::ScheduleData *
8739 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8740   ScheduleData *Bundle = nullptr;
8741   ScheduleData *PrevInBundle = nullptr;
8742   for (Value *V : VL) {
8743     if (doesNotNeedToBeScheduled(V))
8744       continue;
8745     ScheduleData *BundleMember = getScheduleData(V);
8746     assert(BundleMember &&
8747            "no ScheduleData for bundle member "
8748            "(maybe not in same basic block)");
8749     assert(BundleMember->isSchedulingEntity() &&
8750            "bundle member already part of other bundle");
8751     if (PrevInBundle) {
8752       PrevInBundle->NextInBundle = BundleMember;
8753     } else {
8754       Bundle = BundleMember;
8755     }
8756 
8757     // Group the instructions to a bundle.
8758     BundleMember->FirstInBundle = Bundle;
8759     PrevInBundle = BundleMember;
8760   }
8761   assert(Bundle && "Failed to find schedule bundle");
8762   return Bundle;
8763 }
8764 
8765 // Groups the instructions to a bundle (which is then a single scheduling entity)
8766 // and schedules instructions until the bundle gets ready.
8767 Optional<BoUpSLP::ScheduleData *>
8768 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8769                                             const InstructionsState &S) {
8770   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8771   // instructions.
8772   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8773       doesNotNeedToSchedule(VL))
8774     return nullptr;
8775 
8776   // Initialize the instruction bundle.
8777   Instruction *OldScheduleEnd = ScheduleEnd;
8778   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8779 
8780   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8781                                                          ScheduleData *Bundle) {
8782     // The scheduling region got new instructions at the lower end (or it is a
8783     // new region for the first bundle). This makes it necessary to
8784     // recalculate all dependencies.
8785     // It is seldom that this needs to be done a second time after adding the
8786     // initial bundle to the region.
8787     if (ScheduleEnd != OldScheduleEnd) {
8788       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8789         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8790       ReSchedule = true;
8791     }
8792     if (Bundle) {
8793       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8794                         << " in block " << BB->getName() << "\n");
8795       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8796     }
8797 
8798     if (ReSchedule) {
8799       resetSchedule();
8800       initialFillReadyList(ReadyInsts);
8801     }
8802 
8803     // Now try to schedule the new bundle or (if no bundle) just calculate
8804     // dependencies. As soon as the bundle is "ready" it means that there are no
8805     // cyclic dependencies and we can schedule it. Note that's important that we
8806     // don't "schedule" the bundle yet (see cancelScheduling).
8807     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8808            !ReadyInsts.empty()) {
8809       ScheduleData *Picked = ReadyInsts.pop_back_val();
8810       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8811              "must be ready to schedule");
8812       schedule(Picked, ReadyInsts);
8813     }
8814   };
8815 
8816   // Make sure that the scheduling region contains all
8817   // instructions of the bundle.
8818   for (Value *V : VL) {
8819     if (doesNotNeedToBeScheduled(V))
8820       continue;
8821     if (!extendSchedulingRegion(V, S)) {
8822       // If the scheduling region got new instructions at the lower end (or it
8823       // is a new region for the first bundle). This makes it necessary to
8824       // recalculate all dependencies.
8825       // Otherwise the compiler may crash trying to incorrectly calculate
8826       // dependencies and emit instruction in the wrong order at the actual
8827       // scheduling.
8828       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8829       return None;
8830     }
8831   }
8832 
8833   bool ReSchedule = false;
8834   for (Value *V : VL) {
8835     if (doesNotNeedToBeScheduled(V))
8836       continue;
8837     ScheduleData *BundleMember = getScheduleData(V);
8838     assert(BundleMember &&
8839            "no ScheduleData for bundle member (maybe not in same basic block)");
8840 
8841     // Make sure we don't leave the pieces of the bundle in the ready list when
8842     // whole bundle might not be ready.
8843     ReadyInsts.remove(BundleMember);
8844 
8845     if (!BundleMember->IsScheduled)
8846       continue;
8847     // A bundle member was scheduled as single instruction before and now
8848     // needs to be scheduled as part of the bundle. We just get rid of the
8849     // existing schedule.
8850     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8851                       << " was already scheduled\n");
8852     ReSchedule = true;
8853   }
8854 
8855   auto *Bundle = buildBundle(VL);
8856   TryScheduleBundleImpl(ReSchedule, Bundle);
8857   if (!Bundle->isReady()) {
8858     cancelScheduling(VL, S.OpValue);
8859     return None;
8860   }
8861   return Bundle;
8862 }
8863 
8864 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8865                                                 Value *OpValue) {
8866   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8867       doesNotNeedToSchedule(VL))
8868     return;
8869 
8870   if (doesNotNeedToBeScheduled(OpValue))
8871     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8872   ScheduleData *Bundle = getScheduleData(OpValue);
8873   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8874   assert(!Bundle->IsScheduled &&
8875          "Can't cancel bundle which is already scheduled");
8876   assert(Bundle->isSchedulingEntity() &&
8877          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8878          "tried to unbundle something which is not a bundle");
8879 
8880   // Remove the bundle from the ready list.
8881   if (Bundle->isReady())
8882     ReadyInsts.remove(Bundle);
8883 
8884   // Un-bundle: make single instructions out of the bundle.
8885   ScheduleData *BundleMember = Bundle;
8886   while (BundleMember) {
8887     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8888     BundleMember->FirstInBundle = BundleMember;
8889     ScheduleData *Next = BundleMember->NextInBundle;
8890     BundleMember->NextInBundle = nullptr;
8891     BundleMember->TE = nullptr;
8892     if (BundleMember->unscheduledDepsInBundle() == 0) {
8893       ReadyInsts.insert(BundleMember);
8894     }
8895     BundleMember = Next;
8896   }
8897 }
8898 
8899 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8900   // Allocate a new ScheduleData for the instruction.
8901   if (ChunkPos >= ChunkSize) {
8902     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8903     ChunkPos = 0;
8904   }
8905   return &(ScheduleDataChunks.back()[ChunkPos++]);
8906 }
8907 
8908 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8909                                                       const InstructionsState &S) {
8910   if (getScheduleData(V, isOneOf(S, V)))
8911     return true;
8912   Instruction *I = dyn_cast<Instruction>(V);
8913   assert(I && "bundle member must be an instruction");
8914   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8915          !doesNotNeedToBeScheduled(I) &&
8916          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8917          "be scheduled");
8918   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8919     ScheduleData *ISD = getScheduleData(I);
8920     if (!ISD)
8921       return false;
8922     assert(isInSchedulingRegion(ISD) &&
8923            "ScheduleData not in scheduling region");
8924     ScheduleData *SD = allocateScheduleDataChunks();
8925     SD->Inst = I;
8926     SD->init(SchedulingRegionID, S.OpValue);
8927     ExtraScheduleDataMap[I][S.OpValue] = SD;
8928     return true;
8929   };
8930   if (CheckScheduleForI(I))
8931     return true;
8932   if (!ScheduleStart) {
8933     // It's the first instruction in the new region.
8934     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8935     ScheduleStart = I;
8936     ScheduleEnd = I->getNextNode();
8937     if (isOneOf(S, I) != I)
8938       CheckScheduleForI(I);
8939     assert(ScheduleEnd && "tried to vectorize a terminator?");
8940     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8941     return true;
8942   }
8943   // Search up and down at the same time, because we don't know if the new
8944   // instruction is above or below the existing scheduling region.
8945   BasicBlock::reverse_iterator UpIter =
8946       ++ScheduleStart->getIterator().getReverse();
8947   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8948   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8949   BasicBlock::iterator LowerEnd = BB->end();
8950   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8951          &*DownIter != I) {
8952     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8953       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8954       return false;
8955     }
8956 
8957     ++UpIter;
8958     ++DownIter;
8959   }
8960   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8961     assert(I->getParent() == ScheduleStart->getParent() &&
8962            "Instruction is in wrong basic block.");
8963     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8964     ScheduleStart = I;
8965     if (isOneOf(S, I) != I)
8966       CheckScheduleForI(I);
8967     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8968                       << "\n");
8969     return true;
8970   }
8971   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8972          "Expected to reach top of the basic block or instruction down the "
8973          "lower end.");
8974   assert(I->getParent() == ScheduleEnd->getParent() &&
8975          "Instruction is in wrong basic block.");
8976   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8977                    nullptr);
8978   ScheduleEnd = I->getNextNode();
8979   if (isOneOf(S, I) != I)
8980     CheckScheduleForI(I);
8981   assert(ScheduleEnd && "tried to vectorize a terminator?");
8982   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8983   return true;
8984 }
8985 
8986 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8987                                                 Instruction *ToI,
8988                                                 ScheduleData *PrevLoadStore,
8989                                                 ScheduleData *NextLoadStore) {
8990   ScheduleData *CurrentLoadStore = PrevLoadStore;
8991   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8992     // No need to allocate data for non-schedulable instructions.
8993     if (doesNotNeedToBeScheduled(I))
8994       continue;
8995     ScheduleData *SD = ScheduleDataMap.lookup(I);
8996     if (!SD) {
8997       SD = allocateScheduleDataChunks();
8998       ScheduleDataMap[I] = SD;
8999       SD->Inst = I;
9000     }
9001     assert(!isInSchedulingRegion(SD) &&
9002            "new ScheduleData already in scheduling region");
9003     SD->init(SchedulingRegionID, I);
9004 
9005     if (I->mayReadOrWriteMemory() &&
9006         (!isa<IntrinsicInst>(I) ||
9007          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
9008           cast<IntrinsicInst>(I)->getIntrinsicID() !=
9009               Intrinsic::pseudoprobe))) {
9010       // Update the linked list of memory accessing instructions.
9011       if (CurrentLoadStore) {
9012         CurrentLoadStore->NextLoadStore = SD;
9013       } else {
9014         FirstLoadStoreInRegion = SD;
9015       }
9016       CurrentLoadStore = SD;
9017     }
9018 
9019     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
9020         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9021       RegionHasStackSave = true;
9022   }
9023   if (NextLoadStore) {
9024     if (CurrentLoadStore)
9025       CurrentLoadStore->NextLoadStore = NextLoadStore;
9026   } else {
9027     LastLoadStoreInRegion = CurrentLoadStore;
9028   }
9029 }
9030 
9031 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
9032                                                      bool InsertInReadyList,
9033                                                      BoUpSLP *SLP) {
9034   assert(SD->isSchedulingEntity());
9035 
9036   SmallVector<ScheduleData *, 10> WorkList;
9037   WorkList.push_back(SD);
9038 
9039   while (!WorkList.empty()) {
9040     ScheduleData *SD = WorkList.pop_back_val();
9041     for (ScheduleData *BundleMember = SD; BundleMember;
9042          BundleMember = BundleMember->NextInBundle) {
9043       assert(isInSchedulingRegion(BundleMember));
9044       if (BundleMember->hasValidDependencies())
9045         continue;
9046 
9047       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
9048                  << "\n");
9049       BundleMember->Dependencies = 0;
9050       BundleMember->resetUnscheduledDeps();
9051 
9052       // Handle def-use chain dependencies.
9053       if (BundleMember->OpValue != BundleMember->Inst) {
9054         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
9055           BundleMember->Dependencies++;
9056           ScheduleData *DestBundle = UseSD->FirstInBundle;
9057           if (!DestBundle->IsScheduled)
9058             BundleMember->incrementUnscheduledDeps(1);
9059           if (!DestBundle->hasValidDependencies())
9060             WorkList.push_back(DestBundle);
9061         }
9062       } else {
9063         for (User *U : BundleMember->Inst->users()) {
9064           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
9065             BundleMember->Dependencies++;
9066             ScheduleData *DestBundle = UseSD->FirstInBundle;
9067             if (!DestBundle->IsScheduled)
9068               BundleMember->incrementUnscheduledDeps(1);
9069             if (!DestBundle->hasValidDependencies())
9070               WorkList.push_back(DestBundle);
9071           }
9072         }
9073       }
9074 
9075       auto makeControlDependent = [&](Instruction *I) {
9076         auto *DepDest = getScheduleData(I);
9077         assert(DepDest && "must be in schedule window");
9078         DepDest->ControlDependencies.push_back(BundleMember);
9079         BundleMember->Dependencies++;
9080         ScheduleData *DestBundle = DepDest->FirstInBundle;
9081         if (!DestBundle->IsScheduled)
9082           BundleMember->incrementUnscheduledDeps(1);
9083         if (!DestBundle->hasValidDependencies())
9084           WorkList.push_back(DestBundle);
9085       };
9086 
9087       // Any instruction which isn't safe to speculate at the begining of the
9088       // block is control dependend on any early exit or non-willreturn call
9089       // which proceeds it.
9090       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
9091         for (Instruction *I = BundleMember->Inst->getNextNode();
9092              I != ScheduleEnd; I = I->getNextNode()) {
9093           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
9094             continue;
9095 
9096           // Add the dependency
9097           makeControlDependent(I);
9098 
9099           if (!isGuaranteedToTransferExecutionToSuccessor(I))
9100             // Everything past here must be control dependent on I.
9101             break;
9102         }
9103       }
9104 
9105       if (RegionHasStackSave) {
9106         // If we have an inalloc alloca instruction, it needs to be scheduled
9107         // after any preceeding stacksave.  We also need to prevent any alloca
9108         // from reordering above a preceeding stackrestore.
9109         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
9110             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
9111           for (Instruction *I = BundleMember->Inst->getNextNode();
9112                I != ScheduleEnd; I = I->getNextNode()) {
9113             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
9114                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9115               // Any allocas past here must be control dependent on I, and I
9116               // must be memory dependend on BundleMember->Inst.
9117               break;
9118 
9119             if (!isa<AllocaInst>(I))
9120               continue;
9121 
9122             // Add the dependency
9123             makeControlDependent(I);
9124           }
9125         }
9126 
9127         // In addition to the cases handle just above, we need to prevent
9128         // allocas from moving below a stacksave.  The stackrestore case
9129         // is currently thought to be conservatism.
9130         if (isa<AllocaInst>(BundleMember->Inst)) {
9131           for (Instruction *I = BundleMember->Inst->getNextNode();
9132                I != ScheduleEnd; I = I->getNextNode()) {
9133             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
9134                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
9135               continue;
9136 
9137             // Add the dependency
9138             makeControlDependent(I);
9139             break;
9140           }
9141         }
9142       }
9143 
9144       // Handle the memory dependencies (if any).
9145       ScheduleData *DepDest = BundleMember->NextLoadStore;
9146       if (!DepDest)
9147         continue;
9148       Instruction *SrcInst = BundleMember->Inst;
9149       assert(SrcInst->mayReadOrWriteMemory() &&
9150              "NextLoadStore list for non memory effecting bundle?");
9151       MemoryLocation SrcLoc = getLocation(SrcInst);
9152       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
9153       unsigned numAliased = 0;
9154       unsigned DistToSrc = 1;
9155 
9156       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
9157         assert(isInSchedulingRegion(DepDest));
9158 
9159         // We have two limits to reduce the complexity:
9160         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
9161         //    SLP->isAliased (which is the expensive part in this loop).
9162         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
9163         //    the whole loop (even if the loop is fast, it's quadratic).
9164         //    It's important for the loop break condition (see below) to
9165         //    check this limit even between two read-only instructions.
9166         if (DistToSrc >= MaxMemDepDistance ||
9167             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
9168              (numAliased >= AliasedCheckLimit ||
9169               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
9170 
9171           // We increment the counter only if the locations are aliased
9172           // (instead of counting all alias checks). This gives a better
9173           // balance between reduced runtime and accurate dependencies.
9174           numAliased++;
9175 
9176           DepDest->MemoryDependencies.push_back(BundleMember);
9177           BundleMember->Dependencies++;
9178           ScheduleData *DestBundle = DepDest->FirstInBundle;
9179           if (!DestBundle->IsScheduled) {
9180             BundleMember->incrementUnscheduledDeps(1);
9181           }
9182           if (!DestBundle->hasValidDependencies()) {
9183             WorkList.push_back(DestBundle);
9184           }
9185         }
9186 
9187         // Example, explaining the loop break condition: Let's assume our
9188         // starting instruction is i0 and MaxMemDepDistance = 3.
9189         //
9190         //                      +--------v--v--v
9191         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
9192         //             +--------^--^--^
9193         //
9194         // MaxMemDepDistance let us stop alias-checking at i3 and we add
9195         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
9196         // Previously we already added dependencies from i3 to i6,i7,i8
9197         // (because of MaxMemDepDistance). As we added a dependency from
9198         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
9199         // and we can abort this loop at i6.
9200         if (DistToSrc >= 2 * MaxMemDepDistance)
9201           break;
9202         DistToSrc++;
9203       }
9204     }
9205     if (InsertInReadyList && SD->isReady()) {
9206       ReadyInsts.insert(SD);
9207       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
9208                         << "\n");
9209     }
9210   }
9211 }
9212 
9213 void BoUpSLP::BlockScheduling::resetSchedule() {
9214   assert(ScheduleStart &&
9215          "tried to reset schedule on block which has not been scheduled");
9216   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
9217     doForAllOpcodes(I, [&](ScheduleData *SD) {
9218       assert(isInSchedulingRegion(SD) &&
9219              "ScheduleData not in scheduling region");
9220       SD->IsScheduled = false;
9221       SD->resetUnscheduledDeps();
9222     });
9223   }
9224   ReadyInsts.clear();
9225 }
9226 
9227 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
9228   if (!BS->ScheduleStart)
9229     return;
9230 
9231   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
9232 
9233   // A key point - if we got here, pre-scheduling was able to find a valid
9234   // scheduling of the sub-graph of the scheduling window which consists
9235   // of all vector bundles and their transitive users.  As such, we do not
9236   // need to reschedule anything *outside of* that subgraph.
9237 
9238   BS->resetSchedule();
9239 
9240   // For the real scheduling we use a more sophisticated ready-list: it is
9241   // sorted by the original instruction location. This lets the final schedule
9242   // be as  close as possible to the original instruction order.
9243   // WARNING: If changing this order causes a correctness issue, that means
9244   // there is some missing dependence edge in the schedule data graph.
9245   struct ScheduleDataCompare {
9246     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
9247       return SD2->SchedulingPriority < SD1->SchedulingPriority;
9248     }
9249   };
9250   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
9251 
9252   // Ensure that all dependency data is updated (for nodes in the sub-graph)
9253   // and fill the ready-list with initial instructions.
9254   int Idx = 0;
9255   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
9256        I = I->getNextNode()) {
9257     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
9258       TreeEntry *SDTE = getTreeEntry(SD->Inst);
9259       (void)SDTE;
9260       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
9261               SD->isPartOfBundle() ==
9262                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
9263              "scheduler and vectorizer bundle mismatch");
9264       SD->FirstInBundle->SchedulingPriority = Idx++;
9265 
9266       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
9267         BS->calculateDependencies(SD, false, this);
9268     });
9269   }
9270   BS->initialFillReadyList(ReadyInsts);
9271 
9272   Instruction *LastScheduledInst = BS->ScheduleEnd;
9273 
9274   // Do the "real" scheduling.
9275   while (!ReadyInsts.empty()) {
9276     ScheduleData *picked = *ReadyInsts.begin();
9277     ReadyInsts.erase(ReadyInsts.begin());
9278 
9279     // Move the scheduled instruction(s) to their dedicated places, if not
9280     // there yet.
9281     for (ScheduleData *BundleMember = picked; BundleMember;
9282          BundleMember = BundleMember->NextInBundle) {
9283       Instruction *pickedInst = BundleMember->Inst;
9284       if (pickedInst->getNextNode() != LastScheduledInst)
9285         pickedInst->moveBefore(LastScheduledInst);
9286       LastScheduledInst = pickedInst;
9287     }
9288 
9289     BS->schedule(picked, ReadyInsts);
9290   }
9291 
9292   // Check that we didn't break any of our invariants.
9293 #ifdef EXPENSIVE_CHECKS
9294   BS->verify();
9295 #endif
9296 
9297 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
9298   // Check that all schedulable entities got scheduled
9299   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
9300     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
9301       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
9302         assert(SD->IsScheduled && "must be scheduled at this point");
9303       }
9304     });
9305   }
9306 #endif
9307 
9308   // Avoid duplicate scheduling of the block.
9309   BS->ScheduleStart = nullptr;
9310 }
9311 
9312 unsigned BoUpSLP::getVectorElementSize(Value *V) {
9313   // If V is a store, just return the width of the stored value (or value
9314   // truncated just before storing) without traversing the expression tree.
9315   // This is the common case.
9316   if (auto *Store = dyn_cast<StoreInst>(V))
9317     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
9318 
9319   if (auto *IEI = dyn_cast<InsertElementInst>(V))
9320     return getVectorElementSize(IEI->getOperand(1));
9321 
9322   auto E = InstrElementSize.find(V);
9323   if (E != InstrElementSize.end())
9324     return E->second;
9325 
9326   // If V is not a store, we can traverse the expression tree to find loads
9327   // that feed it. The type of the loaded value may indicate a more suitable
9328   // width than V's type. We want to base the vector element size on the width
9329   // of memory operations where possible.
9330   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
9331   SmallPtrSet<Instruction *, 16> Visited;
9332   if (auto *I = dyn_cast<Instruction>(V)) {
9333     Worklist.emplace_back(I, I->getParent());
9334     Visited.insert(I);
9335   }
9336 
9337   // Traverse the expression tree in bottom-up order looking for loads. If we
9338   // encounter an instruction we don't yet handle, we give up.
9339   auto Width = 0u;
9340   while (!Worklist.empty()) {
9341     Instruction *I;
9342     BasicBlock *Parent;
9343     std::tie(I, Parent) = Worklist.pop_back_val();
9344 
9345     // We should only be looking at scalar instructions here. If the current
9346     // instruction has a vector type, skip.
9347     auto *Ty = I->getType();
9348     if (isa<VectorType>(Ty))
9349       continue;
9350 
9351     // If the current instruction is a load, update MaxWidth to reflect the
9352     // width of the loaded value.
9353     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
9354         isa<ExtractValueInst>(I))
9355       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
9356 
9357     // Otherwise, we need to visit the operands of the instruction. We only
9358     // handle the interesting cases from buildTree here. If an operand is an
9359     // instruction we haven't yet visited and from the same basic block as the
9360     // user or the use is a PHI node, we add it to the worklist.
9361     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9362              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
9363              isa<UnaryOperator>(I)) {
9364       for (Use &U : I->operands())
9365         if (auto *J = dyn_cast<Instruction>(U.get()))
9366           if (Visited.insert(J).second &&
9367               (isa<PHINode>(I) || J->getParent() == Parent))
9368             Worklist.emplace_back(J, J->getParent());
9369     } else {
9370       break;
9371     }
9372   }
9373 
9374   // If we didn't encounter a memory access in the expression tree, or if we
9375   // gave up for some reason, just return the width of V. Otherwise, return the
9376   // maximum width we found.
9377   if (!Width) {
9378     if (auto *CI = dyn_cast<CmpInst>(V))
9379       V = CI->getOperand(0);
9380     Width = DL->getTypeSizeInBits(V->getType());
9381   }
9382 
9383   for (Instruction *I : Visited)
9384     InstrElementSize[I] = Width;
9385 
9386   return Width;
9387 }
9388 
9389 // Determine if a value V in a vectorizable expression Expr can be demoted to a
9390 // smaller type with a truncation. We collect the values that will be demoted
9391 // in ToDemote and additional roots that require investigating in Roots.
9392 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
9393                                   SmallVectorImpl<Value *> &ToDemote,
9394                                   SmallVectorImpl<Value *> &Roots) {
9395   // We can always demote constants.
9396   if (isa<Constant>(V)) {
9397     ToDemote.push_back(V);
9398     return true;
9399   }
9400 
9401   // If the value is not an instruction in the expression with only one use, it
9402   // cannot be demoted.
9403   auto *I = dyn_cast<Instruction>(V);
9404   if (!I || !I->hasOneUse() || !Expr.count(I))
9405     return false;
9406 
9407   switch (I->getOpcode()) {
9408 
9409   // We can always demote truncations and extensions. Since truncations can
9410   // seed additional demotion, we save the truncated value.
9411   case Instruction::Trunc:
9412     Roots.push_back(I->getOperand(0));
9413     break;
9414   case Instruction::ZExt:
9415   case Instruction::SExt:
9416     if (isa<ExtractElementInst>(I->getOperand(0)) ||
9417         isa<InsertElementInst>(I->getOperand(0)))
9418       return false;
9419     break;
9420 
9421   // We can demote certain binary operations if we can demote both of their
9422   // operands.
9423   case Instruction::Add:
9424   case Instruction::Sub:
9425   case Instruction::Mul:
9426   case Instruction::And:
9427   case Instruction::Or:
9428   case Instruction::Xor:
9429     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
9430         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
9431       return false;
9432     break;
9433 
9434   // We can demote selects if we can demote their true and false values.
9435   case Instruction::Select: {
9436     SelectInst *SI = cast<SelectInst>(I);
9437     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
9438         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
9439       return false;
9440     break;
9441   }
9442 
9443   // We can demote phis if we can demote all their incoming operands. Note that
9444   // we don't need to worry about cycles since we ensure single use above.
9445   case Instruction::PHI: {
9446     PHINode *PN = cast<PHINode>(I);
9447     for (Value *IncValue : PN->incoming_values())
9448       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
9449         return false;
9450     break;
9451   }
9452 
9453   // Otherwise, conservatively give up.
9454   default:
9455     return false;
9456   }
9457 
9458   // Record the value that we can demote.
9459   ToDemote.push_back(V);
9460   return true;
9461 }
9462 
9463 void BoUpSLP::computeMinimumValueSizes() {
9464   // If there are no external uses, the expression tree must be rooted by a
9465   // store. We can't demote in-memory values, so there is nothing to do here.
9466   if (ExternalUses.empty())
9467     return;
9468 
9469   // We only attempt to truncate integer expressions.
9470   auto &TreeRoot = VectorizableTree[0]->Scalars;
9471   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
9472   if (!TreeRootIT)
9473     return;
9474 
9475   // If the expression is not rooted by a store, these roots should have
9476   // external uses. We will rely on InstCombine to rewrite the expression in
9477   // the narrower type. However, InstCombine only rewrites single-use values.
9478   // This means that if a tree entry other than a root is used externally, it
9479   // must have multiple uses and InstCombine will not rewrite it. The code
9480   // below ensures that only the roots are used externally.
9481   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
9482   for (auto &EU : ExternalUses)
9483     if (!Expr.erase(EU.Scalar))
9484       return;
9485   if (!Expr.empty())
9486     return;
9487 
9488   // Collect the scalar values of the vectorizable expression. We will use this
9489   // context to determine which values can be demoted. If we see a truncation,
9490   // we mark it as seeding another demotion.
9491   for (auto &EntryPtr : VectorizableTree)
9492     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
9493 
9494   // Ensure the roots of the vectorizable tree don't form a cycle. They must
9495   // have a single external user that is not in the vectorizable tree.
9496   for (auto *Root : TreeRoot)
9497     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
9498       return;
9499 
9500   // Conservatively determine if we can actually truncate the roots of the
9501   // expression. Collect the values that can be demoted in ToDemote and
9502   // additional roots that require investigating in Roots.
9503   SmallVector<Value *, 32> ToDemote;
9504   SmallVector<Value *, 4> Roots;
9505   for (auto *Root : TreeRoot)
9506     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
9507       return;
9508 
9509   // The maximum bit width required to represent all the values that can be
9510   // demoted without loss of precision. It would be safe to truncate the roots
9511   // of the expression to this width.
9512   auto MaxBitWidth = 8u;
9513 
9514   // We first check if all the bits of the roots are demanded. If they're not,
9515   // we can truncate the roots to this narrower type.
9516   for (auto *Root : TreeRoot) {
9517     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
9518     MaxBitWidth = std::max<unsigned>(
9519         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
9520   }
9521 
9522   // True if the roots can be zero-extended back to their original type, rather
9523   // than sign-extended. We know that if the leading bits are not demanded, we
9524   // can safely zero-extend. So we initialize IsKnownPositive to True.
9525   bool IsKnownPositive = true;
9526 
9527   // If all the bits of the roots are demanded, we can try a little harder to
9528   // compute a narrower type. This can happen, for example, if the roots are
9529   // getelementptr indices. InstCombine promotes these indices to the pointer
9530   // width. Thus, all their bits are technically demanded even though the
9531   // address computation might be vectorized in a smaller type.
9532   //
9533   // We start by looking at each entry that can be demoted. We compute the
9534   // maximum bit width required to store the scalar by using ValueTracking to
9535   // compute the number of high-order bits we can truncate.
9536   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
9537       llvm::all_of(TreeRoot, [](Value *R) {
9538         assert(R->hasOneUse() && "Root should have only one use!");
9539         return isa<GetElementPtrInst>(R->user_back());
9540       })) {
9541     MaxBitWidth = 8u;
9542 
9543     // Determine if the sign bit of all the roots is known to be zero. If not,
9544     // IsKnownPositive is set to False.
9545     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
9546       KnownBits Known = computeKnownBits(R, *DL);
9547       return Known.isNonNegative();
9548     });
9549 
9550     // Determine the maximum number of bits required to store the scalar
9551     // values.
9552     for (auto *Scalar : ToDemote) {
9553       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
9554       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
9555       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
9556     }
9557 
9558     // If we can't prove that the sign bit is zero, we must add one to the
9559     // maximum bit width to account for the unknown sign bit. This preserves
9560     // the existing sign bit so we can safely sign-extend the root back to the
9561     // original type. Otherwise, if we know the sign bit is zero, we will
9562     // zero-extend the root instead.
9563     //
9564     // FIXME: This is somewhat suboptimal, as there will be cases where adding
9565     //        one to the maximum bit width will yield a larger-than-necessary
9566     //        type. In general, we need to add an extra bit only if we can't
9567     //        prove that the upper bit of the original type is equal to the
9568     //        upper bit of the proposed smaller type. If these two bits are the
9569     //        same (either zero or one) we know that sign-extending from the
9570     //        smaller type will result in the same value. Here, since we can't
9571     //        yet prove this, we are just making the proposed smaller type
9572     //        larger to ensure correctness.
9573     if (!IsKnownPositive)
9574       ++MaxBitWidth;
9575   }
9576 
9577   // Round MaxBitWidth up to the next power-of-two.
9578   if (!isPowerOf2_64(MaxBitWidth))
9579     MaxBitWidth = NextPowerOf2(MaxBitWidth);
9580 
9581   // If the maximum bit width we compute is less than the with of the roots'
9582   // type, we can proceed with the narrowing. Otherwise, do nothing.
9583   if (MaxBitWidth >= TreeRootIT->getBitWidth())
9584     return;
9585 
9586   // If we can truncate the root, we must collect additional values that might
9587   // be demoted as a result. That is, those seeded by truncations we will
9588   // modify.
9589   while (!Roots.empty())
9590     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
9591 
9592   // Finally, map the values we can demote to the maximum bit with we computed.
9593   for (auto *Scalar : ToDemote)
9594     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
9595 }
9596 
9597 namespace {
9598 
9599 /// The SLPVectorizer Pass.
9600 struct SLPVectorizer : public FunctionPass {
9601   SLPVectorizerPass Impl;
9602 
9603   /// Pass identification, replacement for typeid
9604   static char ID;
9605 
9606   explicit SLPVectorizer() : FunctionPass(ID) {
9607     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
9608   }
9609 
9610   bool doInitialization(Module &M) override { return false; }
9611 
9612   bool runOnFunction(Function &F) override {
9613     if (skipFunction(F))
9614       return false;
9615 
9616     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
9617     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
9618     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
9619     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
9620     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
9621     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
9622     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
9623     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
9624     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
9625     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
9626 
9627     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9628   }
9629 
9630   void getAnalysisUsage(AnalysisUsage &AU) const override {
9631     FunctionPass::getAnalysisUsage(AU);
9632     AU.addRequired<AssumptionCacheTracker>();
9633     AU.addRequired<ScalarEvolutionWrapperPass>();
9634     AU.addRequired<AAResultsWrapperPass>();
9635     AU.addRequired<TargetTransformInfoWrapperPass>();
9636     AU.addRequired<LoopInfoWrapperPass>();
9637     AU.addRequired<DominatorTreeWrapperPass>();
9638     AU.addRequired<DemandedBitsWrapperPass>();
9639     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
9640     AU.addRequired<InjectTLIMappingsLegacy>();
9641     AU.addPreserved<LoopInfoWrapperPass>();
9642     AU.addPreserved<DominatorTreeWrapperPass>();
9643     AU.addPreserved<AAResultsWrapperPass>();
9644     AU.addPreserved<GlobalsAAWrapperPass>();
9645     AU.setPreservesCFG();
9646   }
9647 };
9648 
9649 } // end anonymous namespace
9650 
9651 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
9652   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
9653   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
9654   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
9655   auto *AA = &AM.getResult<AAManager>(F);
9656   auto *LI = &AM.getResult<LoopAnalysis>(F);
9657   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
9658   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
9659   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
9660   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9661 
9662   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
9663   if (!Changed)
9664     return PreservedAnalyses::all();
9665 
9666   PreservedAnalyses PA;
9667   PA.preserveSet<CFGAnalyses>();
9668   return PA;
9669 }
9670 
9671 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9672                                 TargetTransformInfo *TTI_,
9673                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9674                                 LoopInfo *LI_, DominatorTree *DT_,
9675                                 AssumptionCache *AC_, DemandedBits *DB_,
9676                                 OptimizationRemarkEmitter *ORE_) {
9677   if (!RunSLPVectorization)
9678     return false;
9679   SE = SE_;
9680   TTI = TTI_;
9681   TLI = TLI_;
9682   AA = AA_;
9683   LI = LI_;
9684   DT = DT_;
9685   AC = AC_;
9686   DB = DB_;
9687   DL = &F.getParent()->getDataLayout();
9688 
9689   Stores.clear();
9690   GEPs.clear();
9691   bool Changed = false;
9692 
9693   // If the target claims to have no vector registers don't attempt
9694   // vectorization.
9695   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9696     LLVM_DEBUG(
9697         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9698     return false;
9699   }
9700 
9701   // Don't vectorize when the attribute NoImplicitFloat is used.
9702   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9703     return false;
9704 
9705   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9706 
9707   // Use the bottom up slp vectorizer to construct chains that start with
9708   // store instructions.
9709   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9710 
9711   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9712   // delete instructions.
9713 
9714   // Update DFS numbers now so that we can use them for ordering.
9715   DT->updateDFSNumbers();
9716 
9717   // Scan the blocks in the function in post order.
9718   for (auto BB : post_order(&F.getEntryBlock())) {
9719     // Start new block - clear the list of reduction roots.
9720     R.clearReductionData();
9721     collectSeedInstructions(BB);
9722 
9723     // Vectorize trees that end at stores.
9724     if (!Stores.empty()) {
9725       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9726                         << " underlying objects.\n");
9727       Changed |= vectorizeStoreChains(R);
9728     }
9729 
9730     // Vectorize trees that end at reductions.
9731     Changed |= vectorizeChainsInBlock(BB, R);
9732 
9733     // Vectorize the index computations of getelementptr instructions. This
9734     // is primarily intended to catch gather-like idioms ending at
9735     // non-consecutive loads.
9736     if (!GEPs.empty()) {
9737       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9738                         << " underlying objects.\n");
9739       Changed |= vectorizeGEPIndices(BB, R);
9740     }
9741   }
9742 
9743   if (Changed) {
9744     R.optimizeGatherSequence();
9745     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9746   }
9747   return Changed;
9748 }
9749 
9750 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9751                                             unsigned Idx, unsigned MinVF) {
9752   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9753                     << "\n");
9754   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9755   unsigned VF = Chain.size();
9756 
9757   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9758     return false;
9759 
9760   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9761                     << "\n");
9762 
9763   R.buildTree(Chain);
9764   if (R.isTreeTinyAndNotFullyVectorizable())
9765     return false;
9766   if (R.isLoadCombineCandidate())
9767     return false;
9768   R.reorderTopToBottom();
9769   R.reorderBottomToTop();
9770   R.buildExternalUses();
9771 
9772   R.computeMinimumValueSizes();
9773 
9774   InstructionCost Cost = R.getTreeCost();
9775 
9776   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9777   if (Cost < -SLPCostThreshold) {
9778     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9779 
9780     using namespace ore;
9781 
9782     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9783                                         cast<StoreInst>(Chain[0]))
9784                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9785                      << " and with tree size "
9786                      << NV("TreeSize", R.getTreeSize()));
9787 
9788     R.vectorizeTree();
9789     return true;
9790   }
9791 
9792   return false;
9793 }
9794 
9795 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9796                                         BoUpSLP &R) {
9797   // We may run into multiple chains that merge into a single chain. We mark the
9798   // stores that we vectorized so that we don't visit the same store twice.
9799   BoUpSLP::ValueSet VectorizedStores;
9800   bool Changed = false;
9801 
9802   int E = Stores.size();
9803   SmallBitVector Tails(E, false);
9804   int MaxIter = MaxStoreLookup.getValue();
9805   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9806       E, std::make_pair(E, INT_MAX));
9807   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9808   int IterCnt;
9809   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9810                                   &CheckedPairs,
9811                                   &ConsecutiveChain](int K, int Idx) {
9812     if (IterCnt >= MaxIter)
9813       return true;
9814     if (CheckedPairs[Idx].test(K))
9815       return ConsecutiveChain[K].second == 1 &&
9816              ConsecutiveChain[K].first == Idx;
9817     ++IterCnt;
9818     CheckedPairs[Idx].set(K);
9819     CheckedPairs[K].set(Idx);
9820     Optional<int> Diff = getPointersDiff(
9821         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9822         Stores[Idx]->getValueOperand()->getType(),
9823         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9824     if (!Diff || *Diff == 0)
9825       return false;
9826     int Val = *Diff;
9827     if (Val < 0) {
9828       if (ConsecutiveChain[Idx].second > -Val) {
9829         Tails.set(K);
9830         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9831       }
9832       return false;
9833     }
9834     if (ConsecutiveChain[K].second <= Val)
9835       return false;
9836 
9837     Tails.set(Idx);
9838     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9839     return Val == 1;
9840   };
9841   // Do a quadratic search on all of the given stores in reverse order and find
9842   // all of the pairs of stores that follow each other.
9843   for (int Idx = E - 1; Idx >= 0; --Idx) {
9844     // If a store has multiple consecutive store candidates, search according
9845     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9846     // This is because usually pairing with immediate succeeding or preceding
9847     // candidate create the best chance to find slp vectorization opportunity.
9848     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9849     IterCnt = 0;
9850     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9851       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9852           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9853         break;
9854   }
9855 
9856   // Tracks if we tried to vectorize stores starting from the given tail
9857   // already.
9858   SmallBitVector TriedTails(E, false);
9859   // For stores that start but don't end a link in the chain:
9860   for (int Cnt = E; Cnt > 0; --Cnt) {
9861     int I = Cnt - 1;
9862     if (ConsecutiveChain[I].first == E || Tails.test(I))
9863       continue;
9864     // We found a store instr that starts a chain. Now follow the chain and try
9865     // to vectorize it.
9866     BoUpSLP::ValueList Operands;
9867     // Collect the chain into a list.
9868     while (I != E && !VectorizedStores.count(Stores[I])) {
9869       Operands.push_back(Stores[I]);
9870       Tails.set(I);
9871       if (ConsecutiveChain[I].second != 1) {
9872         // Mark the new end in the chain and go back, if required. It might be
9873         // required if the original stores come in reversed order, for example.
9874         if (ConsecutiveChain[I].first != E &&
9875             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9876             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9877           TriedTails.set(I);
9878           Tails.reset(ConsecutiveChain[I].first);
9879           if (Cnt < ConsecutiveChain[I].first + 2)
9880             Cnt = ConsecutiveChain[I].first + 2;
9881         }
9882         break;
9883       }
9884       // Move to the next value in the chain.
9885       I = ConsecutiveChain[I].first;
9886     }
9887     assert(!Operands.empty() && "Expected non-empty list of stores.");
9888 
9889     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9890     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9891     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9892 
9893     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9894                               MaxElts);
9895     auto *Store = cast<StoreInst>(Operands[0]);
9896     Type *StoreTy = Store->getValueOperand()->getType();
9897     Type *ValueTy = StoreTy;
9898     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
9899       ValueTy = Trunc->getSrcTy();
9900     unsigned MinVF = TTI->getStoreMinimumVF(
9901         R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
9902 
9903     // FIXME: Is division-by-2 the correct step? Should we assert that the
9904     // register size is a power-of-2?
9905     unsigned StartIdx = 0;
9906     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9907       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9908         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9909         if (!VectorizedStores.count(Slice.front()) &&
9910             !VectorizedStores.count(Slice.back()) &&
9911             vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
9912           // Mark the vectorized stores so that we don't vectorize them again.
9913           VectorizedStores.insert(Slice.begin(), Slice.end());
9914           Changed = true;
9915           // If we vectorized initial block, no need to try to vectorize it
9916           // again.
9917           if (Cnt == StartIdx)
9918             StartIdx += Size;
9919           Cnt += Size;
9920           continue;
9921         }
9922         ++Cnt;
9923       }
9924       // Check if the whole array was vectorized already - exit.
9925       if (StartIdx >= Operands.size())
9926         break;
9927     }
9928   }
9929 
9930   return Changed;
9931 }
9932 
9933 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9934   // Initialize the collections. We will make a single pass over the block.
9935   Stores.clear();
9936   GEPs.clear();
9937 
9938   // Visit the store and getelementptr instructions in BB and organize them in
9939   // Stores and GEPs according to the underlying objects of their pointer
9940   // operands.
9941   for (Instruction &I : *BB) {
9942     // Ignore store instructions that are volatile or have a pointer operand
9943     // that doesn't point to a scalar type.
9944     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9945       if (!SI->isSimple())
9946         continue;
9947       if (!isValidElementType(SI->getValueOperand()->getType()))
9948         continue;
9949       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9950     }
9951 
9952     // Ignore getelementptr instructions that have more than one index, a
9953     // constant index, or a pointer operand that doesn't point to a scalar
9954     // type.
9955     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9956       auto Idx = GEP->idx_begin()->get();
9957       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9958         continue;
9959       if (!isValidElementType(Idx->getType()))
9960         continue;
9961       if (GEP->getType()->isVectorTy())
9962         continue;
9963       GEPs[GEP->getPointerOperand()].push_back(GEP);
9964     }
9965   }
9966 }
9967 
9968 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9969   if (!A || !B)
9970     return false;
9971   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9972     return false;
9973   Value *VL[] = {A, B};
9974   return tryToVectorizeList(VL, R);
9975 }
9976 
9977 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9978                                            bool LimitForRegisterSize) {
9979   if (VL.size() < 2)
9980     return false;
9981 
9982   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9983                     << VL.size() << ".\n");
9984 
9985   // Check that all of the parts are instructions of the same type,
9986   // we permit an alternate opcode via InstructionsState.
9987   InstructionsState S = getSameOpcode(VL);
9988   if (!S.getOpcode())
9989     return false;
9990 
9991   Instruction *I0 = cast<Instruction>(S.OpValue);
9992   // Make sure invalid types (including vector type) are rejected before
9993   // determining vectorization factor for scalar instructions.
9994   for (Value *V : VL) {
9995     Type *Ty = V->getType();
9996     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9997       // NOTE: the following will give user internal llvm type name, which may
9998       // not be useful.
9999       R.getORE()->emit([&]() {
10000         std::string type_str;
10001         llvm::raw_string_ostream rso(type_str);
10002         Ty->print(rso);
10003         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
10004                << "Cannot SLP vectorize list: type "
10005                << rso.str() + " is unsupported by vectorizer";
10006       });
10007       return false;
10008     }
10009   }
10010 
10011   unsigned Sz = R.getVectorElementSize(I0);
10012   unsigned MinVF = R.getMinVF(Sz);
10013   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
10014   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
10015   if (MaxVF < 2) {
10016     R.getORE()->emit([&]() {
10017       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
10018              << "Cannot SLP vectorize list: vectorization factor "
10019              << "less than 2 is not supported";
10020     });
10021     return false;
10022   }
10023 
10024   bool Changed = false;
10025   bool CandidateFound = false;
10026   InstructionCost MinCost = SLPCostThreshold.getValue();
10027   Type *ScalarTy = VL[0]->getType();
10028   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
10029     ScalarTy = IE->getOperand(1)->getType();
10030 
10031   unsigned NextInst = 0, MaxInst = VL.size();
10032   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
10033     // No actual vectorization should happen, if number of parts is the same as
10034     // provided vectorization factor (i.e. the scalar type is used for vector
10035     // code during codegen).
10036     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
10037     if (TTI->getNumberOfParts(VecTy) == VF)
10038       continue;
10039     for (unsigned I = NextInst; I < MaxInst; ++I) {
10040       unsigned OpsWidth = 0;
10041 
10042       if (I + VF > MaxInst)
10043         OpsWidth = MaxInst - I;
10044       else
10045         OpsWidth = VF;
10046 
10047       if (!isPowerOf2_32(OpsWidth))
10048         continue;
10049 
10050       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
10051           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
10052         break;
10053 
10054       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
10055       // Check that a previous iteration of this loop did not delete the Value.
10056       if (llvm::any_of(Ops, [&R](Value *V) {
10057             auto *I = dyn_cast<Instruction>(V);
10058             return I && R.isDeleted(I);
10059           }))
10060         continue;
10061 
10062       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
10063                         << "\n");
10064 
10065       R.buildTree(Ops);
10066       if (R.isTreeTinyAndNotFullyVectorizable())
10067         continue;
10068       R.reorderTopToBottom();
10069       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
10070       R.buildExternalUses();
10071 
10072       R.computeMinimumValueSizes();
10073       InstructionCost Cost = R.getTreeCost();
10074       CandidateFound = true;
10075       MinCost = std::min(MinCost, Cost);
10076 
10077       if (Cost < -SLPCostThreshold) {
10078         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
10079         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
10080                                                     cast<Instruction>(Ops[0]))
10081                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
10082                                  << " and with tree size "
10083                                  << ore::NV("TreeSize", R.getTreeSize()));
10084 
10085         R.vectorizeTree();
10086         // Move to the next bundle.
10087         I += VF - 1;
10088         NextInst = I + 1;
10089         Changed = true;
10090       }
10091     }
10092   }
10093 
10094   if (!Changed && CandidateFound) {
10095     R.getORE()->emit([&]() {
10096       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
10097              << "List vectorization was possible but not beneficial with cost "
10098              << ore::NV("Cost", MinCost) << " >= "
10099              << ore::NV("Treshold", -SLPCostThreshold);
10100     });
10101   } else if (!Changed) {
10102     R.getORE()->emit([&]() {
10103       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
10104              << "Cannot SLP vectorize list: vectorization was impossible"
10105              << " with available vectorization factors";
10106     });
10107   }
10108   return Changed;
10109 }
10110 
10111 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
10112   if (!I)
10113     return false;
10114 
10115   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
10116       isa<VectorType>(I->getType()))
10117     return false;
10118 
10119   Value *P = I->getParent();
10120 
10121   // Vectorize in current basic block only.
10122   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
10123   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
10124   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
10125     return false;
10126 
10127   // First collect all possible candidates
10128   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
10129   Candidates.emplace_back(Op0, Op1);
10130 
10131   auto *A = dyn_cast<BinaryOperator>(Op0);
10132   auto *B = dyn_cast<BinaryOperator>(Op1);
10133   // Try to skip B.
10134   if (A && B && B->hasOneUse()) {
10135     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
10136     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
10137     if (B0 && B0->getParent() == P)
10138       Candidates.emplace_back(A, B0);
10139     if (B1 && B1->getParent() == P)
10140       Candidates.emplace_back(A, B1);
10141   }
10142   // Try to skip A.
10143   if (B && A && A->hasOneUse()) {
10144     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
10145     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
10146     if (A0 && A0->getParent() == P)
10147       Candidates.emplace_back(A0, B);
10148     if (A1 && A1->getParent() == P)
10149       Candidates.emplace_back(A1, B);
10150   }
10151 
10152   if (Candidates.size() == 1)
10153     return tryToVectorizePair(Op0, Op1, R);
10154 
10155   // We have multiple options. Try to pick the single best.
10156   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
10157   if (!BestCandidate)
10158     return false;
10159   return tryToVectorizePair(Candidates[*BestCandidate].first,
10160                             Candidates[*BestCandidate].second, R);
10161 }
10162 
10163 namespace {
10164 
10165 /// Model horizontal reductions.
10166 ///
10167 /// A horizontal reduction is a tree of reduction instructions that has values
10168 /// that can be put into a vector as its leaves. For example:
10169 ///
10170 /// mul mul mul mul
10171 ///  \  /    \  /
10172 ///   +       +
10173 ///    \     /
10174 ///       +
10175 /// This tree has "mul" as its leaf values and "+" as its reduction
10176 /// instructions. A reduction can feed into a store or a binary operation
10177 /// feeding a phi.
10178 ///    ...
10179 ///    \  /
10180 ///     +
10181 ///     |
10182 ///  phi +=
10183 ///
10184 ///  Or:
10185 ///    ...
10186 ///    \  /
10187 ///     +
10188 ///     |
10189 ///   *p =
10190 ///
10191 class HorizontalReduction {
10192   using ReductionOpsType = SmallVector<Value *, 16>;
10193   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
10194   ReductionOpsListType ReductionOps;
10195   /// List of possibly reduced values.
10196   SmallVector<SmallVector<Value *>> ReducedVals;
10197   /// Maps reduced value to the corresponding reduction operation.
10198   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
10199   // Use map vector to make stable output.
10200   MapVector<Instruction *, Value *> ExtraArgs;
10201   WeakTrackingVH ReductionRoot;
10202   /// The type of reduction operation.
10203   RecurKind RdxKind;
10204 
10205   static bool isCmpSelMinMax(Instruction *I) {
10206     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
10207            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
10208   }
10209 
10210   // And/or are potentially poison-safe logical patterns like:
10211   // select x, y, false
10212   // select x, true, y
10213   static bool isBoolLogicOp(Instruction *I) {
10214     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
10215            match(I, m_LogicalOr(m_Value(), m_Value()));
10216   }
10217 
10218   /// Checks if instruction is associative and can be vectorized.
10219   static bool isVectorizable(RecurKind Kind, Instruction *I) {
10220     if (Kind == RecurKind::None)
10221       return false;
10222 
10223     // Integer ops that map to select instructions or intrinsics are fine.
10224     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
10225         isBoolLogicOp(I))
10226       return true;
10227 
10228     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
10229       // FP min/max are associative except for NaN and -0.0. We do not
10230       // have to rule out -0.0 here because the intrinsic semantics do not
10231       // specify a fixed result for it.
10232       return I->getFastMathFlags().noNaNs();
10233     }
10234 
10235     return I->isAssociative();
10236   }
10237 
10238   static Value *getRdxOperand(Instruction *I, unsigned Index) {
10239     // Poison-safe 'or' takes the form: select X, true, Y
10240     // To make that work with the normal operand processing, we skip the
10241     // true value operand.
10242     // TODO: Change the code and data structures to handle this without a hack.
10243     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
10244       return I->getOperand(2);
10245     return I->getOperand(Index);
10246   }
10247 
10248   /// Creates reduction operation with the current opcode.
10249   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
10250                          Value *RHS, const Twine &Name, bool UseSelect) {
10251     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
10252     switch (Kind) {
10253     case RecurKind::Or:
10254       if (UseSelect &&
10255           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
10256         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
10257       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10258                                  Name);
10259     case RecurKind::And:
10260       if (UseSelect &&
10261           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
10262         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
10263       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10264                                  Name);
10265     case RecurKind::Add:
10266     case RecurKind::Mul:
10267     case RecurKind::Xor:
10268     case RecurKind::FAdd:
10269     case RecurKind::FMul:
10270       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
10271                                  Name);
10272     case RecurKind::FMax:
10273       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
10274     case RecurKind::FMin:
10275       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
10276     case RecurKind::SMax:
10277       if (UseSelect) {
10278         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
10279         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10280       }
10281       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
10282     case RecurKind::SMin:
10283       if (UseSelect) {
10284         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
10285         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10286       }
10287       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
10288     case RecurKind::UMax:
10289       if (UseSelect) {
10290         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
10291         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10292       }
10293       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
10294     case RecurKind::UMin:
10295       if (UseSelect) {
10296         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
10297         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
10298       }
10299       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
10300     default:
10301       llvm_unreachable("Unknown reduction operation.");
10302     }
10303   }
10304 
10305   /// Creates reduction operation with the current opcode with the IR flags
10306   /// from \p ReductionOps.
10307   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
10308                          Value *RHS, const Twine &Name,
10309                          const ReductionOpsListType &ReductionOps) {
10310     bool UseSelect = ReductionOps.size() == 2 ||
10311                      // Logical or/and.
10312                      (ReductionOps.size() == 1 &&
10313                       isa<SelectInst>(ReductionOps.front().front()));
10314     assert((!UseSelect || ReductionOps.size() != 2 ||
10315             isa<SelectInst>(ReductionOps[1][0])) &&
10316            "Expected cmp + select pairs for reduction");
10317     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
10318     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
10319       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
10320         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
10321         propagateIRFlags(Op, ReductionOps[1]);
10322         return Op;
10323       }
10324     }
10325     propagateIRFlags(Op, ReductionOps[0]);
10326     return Op;
10327   }
10328 
10329   /// Creates reduction operation with the current opcode with the IR flags
10330   /// from \p I.
10331   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
10332                          Value *RHS, const Twine &Name, Value *I) {
10333     auto *SelI = dyn_cast<SelectInst>(I);
10334     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
10335     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
10336       if (auto *Sel = dyn_cast<SelectInst>(Op))
10337         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
10338     }
10339     propagateIRFlags(Op, I);
10340     return Op;
10341   }
10342 
10343   static RecurKind getRdxKind(Value *V) {
10344     auto *I = dyn_cast<Instruction>(V);
10345     if (!I)
10346       return RecurKind::None;
10347     if (match(I, m_Add(m_Value(), m_Value())))
10348       return RecurKind::Add;
10349     if (match(I, m_Mul(m_Value(), m_Value())))
10350       return RecurKind::Mul;
10351     if (match(I, m_And(m_Value(), m_Value())) ||
10352         match(I, m_LogicalAnd(m_Value(), m_Value())))
10353       return RecurKind::And;
10354     if (match(I, m_Or(m_Value(), m_Value())) ||
10355         match(I, m_LogicalOr(m_Value(), m_Value())))
10356       return RecurKind::Or;
10357     if (match(I, m_Xor(m_Value(), m_Value())))
10358       return RecurKind::Xor;
10359     if (match(I, m_FAdd(m_Value(), m_Value())))
10360       return RecurKind::FAdd;
10361     if (match(I, m_FMul(m_Value(), m_Value())))
10362       return RecurKind::FMul;
10363 
10364     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
10365       return RecurKind::FMax;
10366     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
10367       return RecurKind::FMin;
10368 
10369     // This matches either cmp+select or intrinsics. SLP is expected to handle
10370     // either form.
10371     // TODO: If we are canonicalizing to intrinsics, we can remove several
10372     //       special-case paths that deal with selects.
10373     if (match(I, m_SMax(m_Value(), m_Value())))
10374       return RecurKind::SMax;
10375     if (match(I, m_SMin(m_Value(), m_Value())))
10376       return RecurKind::SMin;
10377     if (match(I, m_UMax(m_Value(), m_Value())))
10378       return RecurKind::UMax;
10379     if (match(I, m_UMin(m_Value(), m_Value())))
10380       return RecurKind::UMin;
10381 
10382     if (auto *Select = dyn_cast<SelectInst>(I)) {
10383       // Try harder: look for min/max pattern based on instructions producing
10384       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
10385       // During the intermediate stages of SLP, it's very common to have
10386       // pattern like this (since optimizeGatherSequence is run only once
10387       // at the end):
10388       // %1 = extractelement <2 x i32> %a, i32 0
10389       // %2 = extractelement <2 x i32> %a, i32 1
10390       // %cond = icmp sgt i32 %1, %2
10391       // %3 = extractelement <2 x i32> %a, i32 0
10392       // %4 = extractelement <2 x i32> %a, i32 1
10393       // %select = select i1 %cond, i32 %3, i32 %4
10394       CmpInst::Predicate Pred;
10395       Instruction *L1;
10396       Instruction *L2;
10397 
10398       Value *LHS = Select->getTrueValue();
10399       Value *RHS = Select->getFalseValue();
10400       Value *Cond = Select->getCondition();
10401 
10402       // TODO: Support inverse predicates.
10403       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
10404         if (!isa<ExtractElementInst>(RHS) ||
10405             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10406           return RecurKind::None;
10407       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
10408         if (!isa<ExtractElementInst>(LHS) ||
10409             !L1->isIdenticalTo(cast<Instruction>(LHS)))
10410           return RecurKind::None;
10411       } else {
10412         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
10413           return RecurKind::None;
10414         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
10415             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
10416             !L2->isIdenticalTo(cast<Instruction>(RHS)))
10417           return RecurKind::None;
10418       }
10419 
10420       switch (Pred) {
10421       default:
10422         return RecurKind::None;
10423       case CmpInst::ICMP_SGT:
10424       case CmpInst::ICMP_SGE:
10425         return RecurKind::SMax;
10426       case CmpInst::ICMP_SLT:
10427       case CmpInst::ICMP_SLE:
10428         return RecurKind::SMin;
10429       case CmpInst::ICMP_UGT:
10430       case CmpInst::ICMP_UGE:
10431         return RecurKind::UMax;
10432       case CmpInst::ICMP_ULT:
10433       case CmpInst::ICMP_ULE:
10434         return RecurKind::UMin;
10435       }
10436     }
10437     return RecurKind::None;
10438   }
10439 
10440   /// Get the index of the first operand.
10441   static unsigned getFirstOperandIndex(Instruction *I) {
10442     return isCmpSelMinMax(I) ? 1 : 0;
10443   }
10444 
10445   /// Total number of operands in the reduction operation.
10446   static unsigned getNumberOfOperands(Instruction *I) {
10447     return isCmpSelMinMax(I) ? 3 : 2;
10448   }
10449 
10450   /// Checks if the instruction is in basic block \p BB.
10451   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
10452   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
10453     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
10454       auto *Sel = cast<SelectInst>(I);
10455       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
10456       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
10457     }
10458     return I->getParent() == BB;
10459   }
10460 
10461   /// Expected number of uses for reduction operations/reduced values.
10462   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
10463     if (IsCmpSelMinMax) {
10464       // SelectInst must be used twice while the condition op must have single
10465       // use only.
10466       if (auto *Sel = dyn_cast<SelectInst>(I))
10467         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
10468       return I->hasNUses(2);
10469     }
10470 
10471     // Arithmetic reduction operation must be used once only.
10472     return I->hasOneUse();
10473   }
10474 
10475   /// Initializes the list of reduction operations.
10476   void initReductionOps(Instruction *I) {
10477     if (isCmpSelMinMax(I))
10478       ReductionOps.assign(2, ReductionOpsType());
10479     else
10480       ReductionOps.assign(1, ReductionOpsType());
10481   }
10482 
10483   /// Add all reduction operations for the reduction instruction \p I.
10484   void addReductionOps(Instruction *I) {
10485     if (isCmpSelMinMax(I)) {
10486       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
10487       ReductionOps[1].emplace_back(I);
10488     } else {
10489       ReductionOps[0].emplace_back(I);
10490     }
10491   }
10492 
10493   static Value *getLHS(RecurKind Kind, Instruction *I) {
10494     if (Kind == RecurKind::None)
10495       return nullptr;
10496     return I->getOperand(getFirstOperandIndex(I));
10497   }
10498   static Value *getRHS(RecurKind Kind, Instruction *I) {
10499     if (Kind == RecurKind::None)
10500       return nullptr;
10501     return I->getOperand(getFirstOperandIndex(I) + 1);
10502   }
10503 
10504 public:
10505   HorizontalReduction() = default;
10506 
10507   /// Try to find a reduction tree.
10508   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
10509                                  ScalarEvolution &SE, const DataLayout &DL,
10510                                  const TargetLibraryInfo &TLI) {
10511     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
10512            "Phi needs to use the binary operator");
10513     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
10514             isa<IntrinsicInst>(Inst)) &&
10515            "Expected binop, select, or intrinsic for reduction matching");
10516     RdxKind = getRdxKind(Inst);
10517 
10518     // We could have a initial reductions that is not an add.
10519     //  r *= v1 + v2 + v3 + v4
10520     // In such a case start looking for a tree rooted in the first '+'.
10521     if (Phi) {
10522       if (getLHS(RdxKind, Inst) == Phi) {
10523         Phi = nullptr;
10524         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
10525         if (!Inst)
10526           return false;
10527         RdxKind = getRdxKind(Inst);
10528       } else if (getRHS(RdxKind, Inst) == Phi) {
10529         Phi = nullptr;
10530         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
10531         if (!Inst)
10532           return false;
10533         RdxKind = getRdxKind(Inst);
10534       }
10535     }
10536 
10537     if (!isVectorizable(RdxKind, Inst))
10538       return false;
10539 
10540     // Analyze "regular" integer/FP types for reductions - no target-specific
10541     // types or pointers.
10542     Type *Ty = Inst->getType();
10543     if (!isValidElementType(Ty) || Ty->isPointerTy())
10544       return false;
10545 
10546     // Though the ultimate reduction may have multiple uses, its condition must
10547     // have only single use.
10548     if (auto *Sel = dyn_cast<SelectInst>(Inst))
10549       if (!Sel->getCondition()->hasOneUse())
10550         return false;
10551 
10552     ReductionRoot = Inst;
10553 
10554     // Iterate through all the operands of the possible reduction tree and
10555     // gather all the reduced values, sorting them by their value id.
10556     BasicBlock *BB = Inst->getParent();
10557     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
10558     SmallVector<Instruction *> Worklist(1, Inst);
10559     // Checks if the operands of the \p TreeN instruction are also reduction
10560     // operations or should be treated as reduced values or an extra argument,
10561     // which is not part of the reduction.
10562     auto &&CheckOperands = [this, IsCmpSelMinMax,
10563                             BB](Instruction *TreeN,
10564                                 SmallVectorImpl<Value *> &ExtraArgs,
10565                                 SmallVectorImpl<Value *> &PossibleReducedVals,
10566                                 SmallVectorImpl<Instruction *> &ReductionOps) {
10567       for (int I = getFirstOperandIndex(TreeN),
10568                End = getNumberOfOperands(TreeN);
10569            I < End; ++I) {
10570         Value *EdgeVal = getRdxOperand(TreeN, I);
10571         ReducedValsToOps[EdgeVal].push_back(TreeN);
10572         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
10573         // Edge has wrong parent - mark as an extra argument.
10574         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
10575             !hasSameParent(EdgeInst, BB)) {
10576           ExtraArgs.push_back(EdgeVal);
10577           continue;
10578         }
10579         // If the edge is not an instruction, or it is different from the main
10580         // reduction opcode or has too many uses - possible reduced value.
10581         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
10582             IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) ||
10583             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
10584             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
10585           PossibleReducedVals.push_back(EdgeVal);
10586           continue;
10587         }
10588         ReductionOps.push_back(EdgeInst);
10589       }
10590     };
10591     // Try to regroup reduced values so that it gets more profitable to try to
10592     // reduce them. Values are grouped by their value ids, instructions - by
10593     // instruction op id and/or alternate op id, plus do extra analysis for
10594     // loads (grouping them by the distabce between pointers) and cmp
10595     // instructions (grouping them by the predicate).
10596     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
10597         PossibleReducedVals;
10598     initReductionOps(Inst);
10599     while (!Worklist.empty()) {
10600       Instruction *TreeN = Worklist.pop_back_val();
10601       SmallVector<Value *> Args;
10602       SmallVector<Value *> PossibleRedVals;
10603       SmallVector<Instruction *> PossibleReductionOps;
10604       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
10605       // If too many extra args - mark the instruction itself as a reduction
10606       // value, not a reduction operation.
10607       if (Args.size() < 2) {
10608         addReductionOps(TreeN);
10609         // Add extra args.
10610         if (!Args.empty()) {
10611           assert(Args.size() == 1 && "Expected only single argument.");
10612           ExtraArgs[TreeN] = Args.front();
10613         }
10614         // Add reduction values. The values are sorted for better vectorization
10615         // results.
10616         for (Value *V : PossibleRedVals) {
10617           size_t Key, Idx;
10618           std::tie(Key, Idx) = generateKeySubkey(
10619               V, &TLI,
10620               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10621                 for (const auto &LoadData : PossibleReducedVals[Key]) {
10622                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10623                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10624                                       LI->getType(), LI->getPointerOperand(),
10625                                       DL, SE, /*StrictCheck=*/true))
10626                     return hash_value(RLI->getPointerOperand());
10627                 }
10628                 return hash_value(LI->getPointerOperand());
10629               },
10630               /*AllowAlternate=*/false);
10631           ++PossibleReducedVals[Key][Idx]
10632                 .insert(std::make_pair(V, 0))
10633                 .first->second;
10634         }
10635         Worklist.append(PossibleReductionOps.rbegin(),
10636                         PossibleReductionOps.rend());
10637       } else {
10638         size_t Key, Idx;
10639         std::tie(Key, Idx) = generateKeySubkey(
10640             TreeN, &TLI,
10641             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
10642               for (const auto &LoadData : PossibleReducedVals[Key]) {
10643                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
10644                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
10645                                     LI->getType(), LI->getPointerOperand(), DL,
10646                                     SE, /*StrictCheck=*/true))
10647                   return hash_value(RLI->getPointerOperand());
10648               }
10649               return hash_value(LI->getPointerOperand());
10650             },
10651             /*AllowAlternate=*/false);
10652         ++PossibleReducedVals[Key][Idx]
10653               .insert(std::make_pair(TreeN, 0))
10654               .first->second;
10655       }
10656     }
10657     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
10658     // Sort values by the total number of values kinds to start the reduction
10659     // from the longest possible reduced values sequences.
10660     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
10661       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
10662       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
10663       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
10664            It != E; ++It) {
10665         PossibleRedValsVect.emplace_back();
10666         auto RedValsVect = It->second.takeVector();
10667         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
10668           return P1.second < P2.second;
10669         });
10670         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
10671           PossibleRedValsVect.back().append(Data.second, Data.first);
10672       }
10673       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
10674         return P1.size() > P2.size();
10675       });
10676       ReducedVals.emplace_back();
10677       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10678         ReducedVals.back().append(Data.rbegin(), Data.rend());
10679     }
10680     // Sort the reduced values by number of same/alternate opcode and/or pointer
10681     // operand.
10682     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10683       return P1.size() > P2.size();
10684     });
10685     return true;
10686   }
10687 
10688   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10689   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10690     constexpr int ReductionLimit = 4;
10691     // If there are a sufficient number of reduction values, reduce
10692     // to a nearby power-of-2. We can safely generate oversized
10693     // vectors and rely on the backend to split them to legal sizes.
10694     unsigned NumReducedVals = std::accumulate(
10695         ReducedVals.begin(), ReducedVals.end(), 0,
10696         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10697     if (NumReducedVals < ReductionLimit)
10698       return nullptr;
10699 
10700     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10701 
10702     // Track the reduced values in case if they are replaced by extractelement
10703     // because of the vectorization.
10704     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10705     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10706     // The same extra argument may be used several times, so log each attempt
10707     // to use it.
10708     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10709       assert(Pair.first && "DebugLoc must be set.");
10710       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10711       TrackedVals.try_emplace(Pair.second, Pair.second);
10712     }
10713 
10714     // The compare instruction of a min/max is the insertion point for new
10715     // instructions and may be replaced with a new compare instruction.
10716     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10717       assert(isa<SelectInst>(RdxRootInst) &&
10718              "Expected min/max reduction to have select root instruction");
10719       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10720       assert(isa<Instruction>(ScalarCond) &&
10721              "Expected min/max reduction to have compare condition");
10722       return cast<Instruction>(ScalarCond);
10723     };
10724 
10725     // The reduction root is used as the insertion point for new instructions,
10726     // so set it as externally used to prevent it from being deleted.
10727     ExternallyUsedValues[ReductionRoot];
10728     SmallVector<Value *> IgnoreList;
10729     for (ReductionOpsType &RdxOps : ReductionOps)
10730       for (Value *RdxOp : RdxOps) {
10731         if (!RdxOp)
10732           continue;
10733         IgnoreList.push_back(RdxOp);
10734       }
10735     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10736 
10737     // Need to track reduced vals, they may be changed during vectorization of
10738     // subvectors.
10739     for (ArrayRef<Value *> Candidates : ReducedVals)
10740       for (Value *V : Candidates)
10741         TrackedVals.try_emplace(V, V);
10742 
10743     DenseMap<Value *, unsigned> VectorizedVals;
10744     Value *VectorizedTree = nullptr;
10745     bool CheckForReusedReductionOps = false;
10746     // Try to vectorize elements based on their type.
10747     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10748       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10749       InstructionsState S = getSameOpcode(OrigReducedVals);
10750       SmallVector<Value *> Candidates;
10751       DenseMap<Value *, Value *> TrackedToOrig;
10752       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10753         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10754         // Check if the reduction value was not overriden by the extractelement
10755         // instruction because of the vectorization and exclude it, if it is not
10756         // compatible with other values.
10757         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10758           if (isVectorLikeInstWithConstOps(Inst) &&
10759               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10760             continue;
10761         Candidates.push_back(RdxVal);
10762         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10763       }
10764       bool ShuffledExtracts = false;
10765       // Try to handle shuffled extractelements.
10766       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10767           I + 1 < E) {
10768         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10769         if (NextS.getOpcode() == Instruction::ExtractElement &&
10770             !NextS.isAltShuffle()) {
10771           SmallVector<Value *> CommonCandidates(Candidates);
10772           for (Value *RV : ReducedVals[I + 1]) {
10773             Value *RdxVal = TrackedVals.find(RV)->second;
10774             // Check if the reduction value was not overriden by the
10775             // extractelement instruction because of the vectorization and
10776             // exclude it, if it is not compatible with other values.
10777             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10778               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10779                 continue;
10780             CommonCandidates.push_back(RdxVal);
10781             TrackedToOrig.try_emplace(RdxVal, RV);
10782           }
10783           SmallVector<int> Mask;
10784           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10785             ++I;
10786             Candidates.swap(CommonCandidates);
10787             ShuffledExtracts = true;
10788           }
10789         }
10790       }
10791       unsigned NumReducedVals = Candidates.size();
10792       if (NumReducedVals < ReductionLimit)
10793         continue;
10794 
10795       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10796       unsigned Start = 0;
10797       unsigned Pos = Start;
10798       // Restarts vectorization attempt with lower vector factor.
10799       unsigned PrevReduxWidth = ReduxWidth;
10800       bool CheckForReusedReductionOpsLocal = false;
10801       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10802                                   &CheckForReusedReductionOpsLocal,
10803                                   &PrevReduxWidth, &V,
10804                                   &IgnoreList](bool IgnoreVL = false) {
10805         bool IsAnyRedOpGathered =
10806             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10807               return V.isGathered(RedOp);
10808             });
10809         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10810           // Check if any of the reduction ops are gathered. If so, worth
10811           // trying again with less number of reduction ops.
10812           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10813         }
10814         ++Pos;
10815         if (Pos < NumReducedVals - ReduxWidth + 1)
10816           return IsAnyRedOpGathered;
10817         Pos = Start;
10818         ReduxWidth /= 2;
10819         return IsAnyRedOpGathered;
10820       };
10821       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10822              ReduxWidth >= ReductionLimit) {
10823         // Dependency in tree of the reduction ops - drop this attempt, try
10824         // later.
10825         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10826             Start == 0) {
10827           CheckForReusedReductionOps = true;
10828           break;
10829         }
10830         PrevReduxWidth = ReduxWidth;
10831         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10832         // Beeing analyzed already - skip.
10833         if (V.areAnalyzedReductionVals(VL)) {
10834           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10835           continue;
10836         }
10837         // Early exit if any of the reduction values were deleted during
10838         // previous vectorization attempts.
10839         if (any_of(VL, [&V](Value *RedVal) {
10840               auto *RedValI = dyn_cast<Instruction>(RedVal);
10841               if (!RedValI)
10842                 return false;
10843               return V.isDeleted(RedValI);
10844             }))
10845           break;
10846         V.buildTree(VL, IgnoreList);
10847         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10848           if (!AdjustReducedVals())
10849             V.analyzedReductionVals(VL);
10850           continue;
10851         }
10852         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10853           if (!AdjustReducedVals())
10854             V.analyzedReductionVals(VL);
10855           continue;
10856         }
10857         V.reorderTopToBottom();
10858         // No need to reorder the root node at all.
10859         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10860         // Keep extracted other reduction values, if they are used in the
10861         // vectorization trees.
10862         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10863             ExternallyUsedValues);
10864         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10865           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10866             continue;
10867           for_each(ReducedVals[Cnt],
10868                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10869                      if (isa<Instruction>(V))
10870                        LocalExternallyUsedValues[TrackedVals[V]];
10871                    });
10872         }
10873         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10874           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10875             continue;
10876           unsigned NumOps = VectorizedVals.lookup(Candidates[Cnt]) +
10877                             std::count(VL.begin(), VL.end(), Candidates[Cnt]);
10878           if (NumOps != ReducedValsToOps.find(Candidates[Cnt])->second.size())
10879             LocalExternallyUsedValues[Candidates[Cnt]];
10880         }
10881         V.buildExternalUses(LocalExternallyUsedValues);
10882 
10883         V.computeMinimumValueSizes();
10884 
10885         // Intersect the fast-math-flags from all reduction operations.
10886         FastMathFlags RdxFMF;
10887         RdxFMF.set();
10888         for (Value *U : IgnoreList)
10889           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10890             RdxFMF &= FPMO->getFastMathFlags();
10891         // Estimate cost.
10892         InstructionCost TreeCost = V.getTreeCost(VL);
10893         InstructionCost ReductionCost =
10894             getReductionCost(TTI, VL, ReduxWidth, RdxFMF);
10895         InstructionCost Cost = TreeCost + ReductionCost;
10896         if (!Cost.isValid()) {
10897           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10898           return nullptr;
10899         }
10900         if (Cost >= -SLPCostThreshold) {
10901           V.getORE()->emit([&]() {
10902             return OptimizationRemarkMissed(
10903                        SV_NAME, "HorSLPNotBeneficial",
10904                        ReducedValsToOps.find(VL[0])->second.front())
10905                    << "Vectorizing horizontal reduction is possible"
10906                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10907                    << " and threshold "
10908                    << ore::NV("Threshold", -SLPCostThreshold);
10909           });
10910           if (!AdjustReducedVals())
10911             V.analyzedReductionVals(VL);
10912           continue;
10913         }
10914 
10915         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10916                           << Cost << ". (HorRdx)\n");
10917         V.getORE()->emit([&]() {
10918           return OptimizationRemark(
10919                      SV_NAME, "VectorizedHorizontalReduction",
10920                      ReducedValsToOps.find(VL[0])->second.front())
10921                  << "Vectorized horizontal reduction with cost "
10922                  << ore::NV("Cost", Cost) << " and with tree size "
10923                  << ore::NV("TreeSize", V.getTreeSize());
10924         });
10925 
10926         Builder.setFastMathFlags(RdxFMF);
10927 
10928         // Vectorize a tree.
10929         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10930 
10931         // Emit a reduction. If the root is a select (min/max idiom), the insert
10932         // point is the compare condition of that select.
10933         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10934         if (IsCmpSelMinMax)
10935           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10936         else
10937           Builder.SetInsertPoint(RdxRootInst);
10938 
10939         // To prevent poison from leaking across what used to be sequential,
10940         // safe, scalar boolean logic operations, the reduction operand must be
10941         // frozen.
10942         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10943           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10944 
10945         Value *ReducedSubTree =
10946             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10947 
10948         if (!VectorizedTree) {
10949           // Initialize the final value in the reduction.
10950           VectorizedTree = ReducedSubTree;
10951         } else {
10952           // Update the final value in the reduction.
10953           Builder.SetCurrentDebugLocation(
10954               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10955           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10956                                     ReducedSubTree, "op.rdx", ReductionOps);
10957         }
10958         // Count vectorized reduced values to exclude them from final reduction.
10959         for (Value *V : VL)
10960           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10961                 .first->getSecond();
10962         Pos += ReduxWidth;
10963         Start = Pos;
10964         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10965       }
10966     }
10967     if (VectorizedTree) {
10968       // Finish the reduction.
10969       // Need to add extra arguments and not vectorized possible reduction
10970       // values.
10971       // Try to avoid dependencies between the scalar remainders after
10972       // reductions.
10973       auto &&FinalGen =
10974           [this, &Builder,
10975            &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) {
10976             unsigned Sz = InstVals.size();
10977             SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 +
10978                                                                      Sz % 2);
10979             for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) {
10980               Instruction *RedOp = InstVals[I + 1].first;
10981               Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10982               ReductionOpsListType Ops;
10983               if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10984                 Ops.emplace_back().push_back(Sel->getCondition());
10985               Ops.emplace_back().push_back(RedOp);
10986               Value *RdxVal1 = InstVals[I].second;
10987               Value *StableRdxVal1 = RdxVal1;
10988               auto It1 = TrackedVals.find(RdxVal1);
10989               if (It1 != TrackedVals.end())
10990                 StableRdxVal1 = It1->second;
10991               Value *RdxVal2 = InstVals[I + 1].second;
10992               Value *StableRdxVal2 = RdxVal2;
10993               auto It2 = TrackedVals.find(RdxVal2);
10994               if (It2 != TrackedVals.end())
10995                 StableRdxVal2 = It2->second;
10996               Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1,
10997                                          StableRdxVal2, "op.rdx", Ops);
10998               ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed);
10999             }
11000             if (Sz % 2 == 1)
11001               ExtraReds[Sz / 2] = InstVals.back();
11002             return ExtraReds;
11003           };
11004       SmallVector<std::pair<Instruction *, Value *>> ExtraReductions;
11005       SmallPtrSet<Value *, 8> Visited;
11006       for (ArrayRef<Value *> Candidates : ReducedVals) {
11007         for (Value *RdxVal : Candidates) {
11008           if (!Visited.insert(RdxVal).second)
11009             continue;
11010           unsigned NumOps = VectorizedVals.lookup(RdxVal);
11011           for (Instruction *RedOp :
11012                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
11013                    .drop_back(NumOps))
11014             ExtraReductions.emplace_back(RedOp, RdxVal);
11015         }
11016       }
11017       for (auto &Pair : ExternallyUsedValues) {
11018         // Add each externally used value to the final reduction.
11019         for (auto *I : Pair.second)
11020           ExtraReductions.emplace_back(I, Pair.first);
11021       }
11022       // Iterate through all not-vectorized reduction values/extra arguments.
11023       while (ExtraReductions.size() > 1) {
11024         SmallVector<std::pair<Instruction *, Value *>> NewReds =
11025             FinalGen(ExtraReductions);
11026         ExtraReductions.swap(NewReds);
11027       }
11028       // Final reduction.
11029       if (ExtraReductions.size() == 1) {
11030         Instruction *RedOp = ExtraReductions.back().first;
11031         Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
11032         ReductionOpsListType Ops;
11033         if (auto *Sel = dyn_cast<SelectInst>(RedOp))
11034           Ops.emplace_back().push_back(Sel->getCondition());
11035         Ops.emplace_back().push_back(RedOp);
11036         Value *RdxVal = ExtraReductions.back().second;
11037         Value *StableRdxVal = RdxVal;
11038         auto It = TrackedVals.find(RdxVal);
11039         if (It != TrackedVals.end())
11040           StableRdxVal = It->second;
11041         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
11042                                   StableRdxVal, "op.rdx", Ops);
11043       }
11044 
11045       ReductionRoot->replaceAllUsesWith(VectorizedTree);
11046 
11047       // The original scalar reduction is expected to have no remaining
11048       // uses outside the reduction tree itself.  Assert that we got this
11049       // correct, replace internal uses with undef, and mark for eventual
11050       // deletion.
11051 #ifndef NDEBUG
11052       SmallSet<Value *, 4> IgnoreSet;
11053       for (ArrayRef<Value *> RdxOps : ReductionOps)
11054         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
11055 #endif
11056       for (ArrayRef<Value *> RdxOps : ReductionOps) {
11057         for (Value *Ignore : RdxOps) {
11058           if (!Ignore)
11059             continue;
11060 #ifndef NDEBUG
11061           for (auto *U : Ignore->users()) {
11062             assert(IgnoreSet.count(U) &&
11063                    "All users must be either in the reduction ops list.");
11064           }
11065 #endif
11066           if (!Ignore->use_empty()) {
11067             Value *Undef = UndefValue::get(Ignore->getType());
11068             Ignore->replaceAllUsesWith(Undef);
11069           }
11070           V.eraseInstruction(cast<Instruction>(Ignore));
11071         }
11072       }
11073     } else if (!CheckForReusedReductionOps) {
11074       for (ReductionOpsType &RdxOps : ReductionOps)
11075         for (Value *RdxOp : RdxOps)
11076           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
11077     }
11078     return VectorizedTree;
11079   }
11080 
11081 private:
11082   /// Calculate the cost of a reduction.
11083   InstructionCost getReductionCost(TargetTransformInfo *TTI,
11084                                    ArrayRef<Value *> ReducedVals,
11085                                    unsigned ReduxWidth, FastMathFlags FMF) {
11086     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
11087     Value *FirstReducedVal = ReducedVals.front();
11088     Type *ScalarTy = FirstReducedVal->getType();
11089     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
11090     InstructionCost VectorCost = 0, ScalarCost;
11091     // If all of the reduced values are constant, the vector cost is 0, since
11092     // the reduction value can be calculated at the compile time.
11093     bool AllConsts = all_of(ReducedVals, isConstant);
11094     switch (RdxKind) {
11095     case RecurKind::Add:
11096     case RecurKind::Mul:
11097     case RecurKind::Or:
11098     case RecurKind::And:
11099     case RecurKind::Xor:
11100     case RecurKind::FAdd:
11101     case RecurKind::FMul: {
11102       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
11103       if (!AllConsts)
11104         VectorCost =
11105             TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
11106       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
11107       break;
11108     }
11109     case RecurKind::FMax:
11110     case RecurKind::FMin: {
11111       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
11112       if (!AllConsts) {
11113         auto *VecCondTy =
11114             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
11115         VectorCost =
11116             TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
11117                                         /*IsUnsigned=*/false, CostKind);
11118       }
11119       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
11120       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
11121                                            SclCondTy, RdxPred, CostKind) +
11122                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
11123                                            SclCondTy, RdxPred, CostKind);
11124       break;
11125     }
11126     case RecurKind::SMax:
11127     case RecurKind::SMin:
11128     case RecurKind::UMax:
11129     case RecurKind::UMin: {
11130       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
11131       if (!AllConsts) {
11132         auto *VecCondTy =
11133             cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
11134         bool IsUnsigned =
11135             RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
11136         VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
11137                                                  IsUnsigned, CostKind);
11138       }
11139       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
11140       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
11141                                            SclCondTy, RdxPred, CostKind) +
11142                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
11143                                            SclCondTy, RdxPred, CostKind);
11144       break;
11145     }
11146     default:
11147       llvm_unreachable("Expected arithmetic or min/max reduction operation");
11148     }
11149 
11150     // Scalar cost is repeated for N-1 elements.
11151     ScalarCost *= (ReduxWidth - 1);
11152     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
11153                       << " for reduction that starts with " << *FirstReducedVal
11154                       << " (It is a splitting reduction)\n");
11155     return VectorCost - ScalarCost;
11156   }
11157 
11158   /// Emit a horizontal reduction of the vectorized value.
11159   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
11160                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
11161     assert(VectorizedValue && "Need to have a vectorized tree node");
11162     assert(isPowerOf2_32(ReduxWidth) &&
11163            "We only handle power-of-two reductions for now");
11164     assert(RdxKind != RecurKind::FMulAdd &&
11165            "A call to the llvm.fmuladd intrinsic is not handled yet");
11166 
11167     ++NumVectorInstructions;
11168     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
11169   }
11170 };
11171 
11172 } // end anonymous namespace
11173 
11174 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
11175   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
11176     return cast<FixedVectorType>(IE->getType())->getNumElements();
11177 
11178   unsigned AggregateSize = 1;
11179   auto *IV = cast<InsertValueInst>(InsertInst);
11180   Type *CurrentType = IV->getType();
11181   do {
11182     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
11183       for (auto *Elt : ST->elements())
11184         if (Elt != ST->getElementType(0)) // check homogeneity
11185           return None;
11186       AggregateSize *= ST->getNumElements();
11187       CurrentType = ST->getElementType(0);
11188     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
11189       AggregateSize *= AT->getNumElements();
11190       CurrentType = AT->getElementType();
11191     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
11192       AggregateSize *= VT->getNumElements();
11193       return AggregateSize;
11194     } else if (CurrentType->isSingleValueType()) {
11195       return AggregateSize;
11196     } else {
11197       return None;
11198     }
11199   } while (true);
11200 }
11201 
11202 static void findBuildAggregate_rec(Instruction *LastInsertInst,
11203                                    TargetTransformInfo *TTI,
11204                                    SmallVectorImpl<Value *> &BuildVectorOpds,
11205                                    SmallVectorImpl<Value *> &InsertElts,
11206                                    unsigned OperandOffset) {
11207   do {
11208     Value *InsertedOperand = LastInsertInst->getOperand(1);
11209     Optional<unsigned> OperandIndex =
11210         getInsertIndex(LastInsertInst, OperandOffset);
11211     if (!OperandIndex)
11212       return;
11213     if (isa<InsertElementInst>(InsertedOperand) ||
11214         isa<InsertValueInst>(InsertedOperand)) {
11215       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
11216                              BuildVectorOpds, InsertElts, *OperandIndex);
11217 
11218     } else {
11219       BuildVectorOpds[*OperandIndex] = InsertedOperand;
11220       InsertElts[*OperandIndex] = LastInsertInst;
11221     }
11222     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
11223   } while (LastInsertInst != nullptr &&
11224            (isa<InsertValueInst>(LastInsertInst) ||
11225             isa<InsertElementInst>(LastInsertInst)) &&
11226            LastInsertInst->hasOneUse());
11227 }
11228 
11229 /// Recognize construction of vectors like
11230 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
11231 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
11232 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
11233 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
11234 ///  starting from the last insertelement or insertvalue instruction.
11235 ///
11236 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
11237 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
11238 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
11239 ///
11240 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
11241 ///
11242 /// \return true if it matches.
11243 static bool findBuildAggregate(Instruction *LastInsertInst,
11244                                TargetTransformInfo *TTI,
11245                                SmallVectorImpl<Value *> &BuildVectorOpds,
11246                                SmallVectorImpl<Value *> &InsertElts) {
11247 
11248   assert((isa<InsertElementInst>(LastInsertInst) ||
11249           isa<InsertValueInst>(LastInsertInst)) &&
11250          "Expected insertelement or insertvalue instruction!");
11251 
11252   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
11253          "Expected empty result vectors!");
11254 
11255   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
11256   if (!AggregateSize)
11257     return false;
11258   BuildVectorOpds.resize(*AggregateSize);
11259   InsertElts.resize(*AggregateSize);
11260 
11261   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
11262   llvm::erase_value(BuildVectorOpds, nullptr);
11263   llvm::erase_value(InsertElts, nullptr);
11264   if (BuildVectorOpds.size() >= 2)
11265     return true;
11266 
11267   return false;
11268 }
11269 
11270 /// Try and get a reduction value from a phi node.
11271 ///
11272 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
11273 /// if they come from either \p ParentBB or a containing loop latch.
11274 ///
11275 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
11276 /// if not possible.
11277 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
11278                                 BasicBlock *ParentBB, LoopInfo *LI) {
11279   // There are situations where the reduction value is not dominated by the
11280   // reduction phi. Vectorizing such cases has been reported to cause
11281   // miscompiles. See PR25787.
11282   auto DominatedReduxValue = [&](Value *R) {
11283     return isa<Instruction>(R) &&
11284            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
11285   };
11286 
11287   Value *Rdx = nullptr;
11288 
11289   // Return the incoming value if it comes from the same BB as the phi node.
11290   if (P->getIncomingBlock(0) == ParentBB) {
11291     Rdx = P->getIncomingValue(0);
11292   } else if (P->getIncomingBlock(1) == ParentBB) {
11293     Rdx = P->getIncomingValue(1);
11294   }
11295 
11296   if (Rdx && DominatedReduxValue(Rdx))
11297     return Rdx;
11298 
11299   // Otherwise, check whether we have a loop latch to look at.
11300   Loop *BBL = LI->getLoopFor(ParentBB);
11301   if (!BBL)
11302     return nullptr;
11303   BasicBlock *BBLatch = BBL->getLoopLatch();
11304   if (!BBLatch)
11305     return nullptr;
11306 
11307   // There is a loop latch, return the incoming value if it comes from
11308   // that. This reduction pattern occasionally turns up.
11309   if (P->getIncomingBlock(0) == BBLatch) {
11310     Rdx = P->getIncomingValue(0);
11311   } else if (P->getIncomingBlock(1) == BBLatch) {
11312     Rdx = P->getIncomingValue(1);
11313   }
11314 
11315   if (Rdx && DominatedReduxValue(Rdx))
11316     return Rdx;
11317 
11318   return nullptr;
11319 }
11320 
11321 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
11322   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
11323     return true;
11324   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
11325     return true;
11326   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
11327     return true;
11328   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
11329     return true;
11330   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
11331     return true;
11332   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
11333     return true;
11334   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
11335     return true;
11336   return false;
11337 }
11338 
11339 /// Attempt to reduce a horizontal reduction.
11340 /// If it is legal to match a horizontal reduction feeding the phi node \a P
11341 /// with reduction operators \a Root (or one of its operands) in a basic block
11342 /// \a BB, then check if it can be done. If horizontal reduction is not found
11343 /// and root instruction is a binary operation, vectorization of the operands is
11344 /// attempted.
11345 /// \returns true if a horizontal reduction was matched and reduced or operands
11346 /// of one of the binary instruction were vectorized.
11347 /// \returns false if a horizontal reduction was not matched (or not possible)
11348 /// or no vectorization of any binary operation feeding \a Root instruction was
11349 /// performed.
11350 static bool tryToVectorizeHorReductionOrInstOperands(
11351     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
11352     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
11353     const TargetLibraryInfo &TLI,
11354     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
11355   if (!ShouldVectorizeHor)
11356     return false;
11357 
11358   if (!Root)
11359     return false;
11360 
11361   if (Root->getParent() != BB || isa<PHINode>(Root))
11362     return false;
11363   // Start analysis starting from Root instruction. If horizontal reduction is
11364   // found, try to vectorize it. If it is not a horizontal reduction or
11365   // vectorization is not possible or not effective, and currently analyzed
11366   // instruction is a binary operation, try to vectorize the operands, using
11367   // pre-order DFS traversal order. If the operands were not vectorized, repeat
11368   // the same procedure considering each operand as a possible root of the
11369   // horizontal reduction.
11370   // Interrupt the process if the Root instruction itself was vectorized or all
11371   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
11372   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
11373   // CmpInsts so we can skip extra attempts in
11374   // tryToVectorizeHorReductionOrInstOperands and save compile time.
11375   std::queue<std::pair<Instruction *, unsigned>> Stack;
11376   Stack.emplace(Root, 0);
11377   SmallPtrSet<Value *, 8> VisitedInstrs;
11378   SmallVector<WeakTrackingVH> PostponedInsts;
11379   bool Res = false;
11380   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
11381                                                      Value *&B0,
11382                                                      Value *&B1) -> Value * {
11383     if (R.isAnalyzedReductionRoot(Inst))
11384       return nullptr;
11385     bool IsBinop = matchRdxBop(Inst, B0, B1);
11386     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
11387     if (IsBinop || IsSelect) {
11388       HorizontalReduction HorRdx;
11389       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
11390         return HorRdx.tryToReduce(R, TTI);
11391     }
11392     return nullptr;
11393   };
11394   while (!Stack.empty()) {
11395     Instruction *Inst;
11396     unsigned Level;
11397     std::tie(Inst, Level) = Stack.front();
11398     Stack.pop();
11399     // Do not try to analyze instruction that has already been vectorized.
11400     // This may happen when we vectorize instruction operands on a previous
11401     // iteration while stack was populated before that happened.
11402     if (R.isDeleted(Inst))
11403       continue;
11404     Value *B0 = nullptr, *B1 = nullptr;
11405     if (Value *V = TryToReduce(Inst, B0, B1)) {
11406       Res = true;
11407       // Set P to nullptr to avoid re-analysis of phi node in
11408       // matchAssociativeReduction function unless this is the root node.
11409       P = nullptr;
11410       if (auto *I = dyn_cast<Instruction>(V)) {
11411         // Try to find another reduction.
11412         Stack.emplace(I, Level);
11413         continue;
11414       }
11415     } else {
11416       bool IsBinop = B0 && B1;
11417       if (P && IsBinop) {
11418         Inst = dyn_cast<Instruction>(B0);
11419         if (Inst == P)
11420           Inst = dyn_cast<Instruction>(B1);
11421         if (!Inst) {
11422           // Set P to nullptr to avoid re-analysis of phi node in
11423           // matchAssociativeReduction function unless this is the root node.
11424           P = nullptr;
11425           continue;
11426         }
11427       }
11428       // Set P to nullptr to avoid re-analysis of phi node in
11429       // matchAssociativeReduction function unless this is the root node.
11430       P = nullptr;
11431       // Do not try to vectorize CmpInst operands, this is done separately.
11432       // Final attempt for binop args vectorization should happen after the loop
11433       // to try to find reductions.
11434       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
11435         PostponedInsts.push_back(Inst);
11436     }
11437 
11438     // Try to vectorize operands.
11439     // Continue analysis for the instruction from the same basic block only to
11440     // save compile time.
11441     if (++Level < RecursionMaxDepth)
11442       for (auto *Op : Inst->operand_values())
11443         if (VisitedInstrs.insert(Op).second)
11444           if (auto *I = dyn_cast<Instruction>(Op))
11445             // Do not try to vectorize CmpInst operands,  this is done
11446             // separately.
11447             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
11448                 !R.isDeleted(I) && I->getParent() == BB)
11449               Stack.emplace(I, Level);
11450   }
11451   // Try to vectorized binops where reductions were not found.
11452   for (Value *V : PostponedInsts)
11453     if (auto *Inst = dyn_cast<Instruction>(V))
11454       if (!R.isDeleted(Inst))
11455         Res |= Vectorize(Inst, R);
11456   return Res;
11457 }
11458 
11459 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
11460                                                  BasicBlock *BB, BoUpSLP &R,
11461                                                  TargetTransformInfo *TTI) {
11462   auto *I = dyn_cast_or_null<Instruction>(V);
11463   if (!I)
11464     return false;
11465 
11466   if (!isa<BinaryOperator>(I))
11467     P = nullptr;
11468   // Try to match and vectorize a horizontal reduction.
11469   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
11470     return tryToVectorize(I, R);
11471   };
11472   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
11473                                                   *TLI, ExtraVectorization);
11474 }
11475 
11476 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
11477                                                  BasicBlock *BB, BoUpSLP &R) {
11478   const DataLayout &DL = BB->getModule()->getDataLayout();
11479   if (!R.canMapToVector(IVI->getType(), DL))
11480     return false;
11481 
11482   SmallVector<Value *, 16> BuildVectorOpds;
11483   SmallVector<Value *, 16> BuildVectorInsts;
11484   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
11485     return false;
11486 
11487   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
11488   // Aggregate value is unlikely to be processed in vector register.
11489   return tryToVectorizeList(BuildVectorOpds, R);
11490 }
11491 
11492 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
11493                                                    BasicBlock *BB, BoUpSLP &R) {
11494   SmallVector<Value *, 16> BuildVectorInsts;
11495   SmallVector<Value *, 16> BuildVectorOpds;
11496   SmallVector<int> Mask;
11497   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
11498       (llvm::all_of(
11499            BuildVectorOpds,
11500            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
11501        isFixedVectorShuffle(BuildVectorOpds, Mask)))
11502     return false;
11503 
11504   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
11505   return tryToVectorizeList(BuildVectorInsts, R);
11506 }
11507 
11508 template <typename T>
11509 static bool
11510 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
11511                        function_ref<unsigned(T *)> Limit,
11512                        function_ref<bool(T *, T *)> Comparator,
11513                        function_ref<bool(T *, T *)> AreCompatible,
11514                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
11515                        bool LimitForRegisterSize) {
11516   bool Changed = false;
11517   // Sort by type, parent, operands.
11518   stable_sort(Incoming, Comparator);
11519 
11520   // Try to vectorize elements base on their type.
11521   SmallVector<T *> Candidates;
11522   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
11523     // Look for the next elements with the same type, parent and operand
11524     // kinds.
11525     auto *SameTypeIt = IncIt;
11526     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
11527       ++SameTypeIt;
11528 
11529     // Try to vectorize them.
11530     unsigned NumElts = (SameTypeIt - IncIt);
11531     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
11532                       << NumElts << ")\n");
11533     // The vectorization is a 3-state attempt:
11534     // 1. Try to vectorize instructions with the same/alternate opcodes with the
11535     // size of maximal register at first.
11536     // 2. Try to vectorize remaining instructions with the same type, if
11537     // possible. This may result in the better vectorization results rather than
11538     // if we try just to vectorize instructions with the same/alternate opcodes.
11539     // 3. Final attempt to try to vectorize all instructions with the
11540     // same/alternate ops only, this may result in some extra final
11541     // vectorization.
11542     if (NumElts > 1 &&
11543         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
11544       // Success start over because instructions might have been changed.
11545       Changed = true;
11546     } else if (NumElts < Limit(*IncIt) &&
11547                (Candidates.empty() ||
11548                 Candidates.front()->getType() == (*IncIt)->getType())) {
11549       Candidates.append(IncIt, std::next(IncIt, NumElts));
11550     }
11551     // Final attempt to vectorize instructions with the same types.
11552     if (Candidates.size() > 1 &&
11553         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
11554       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
11555         // Success start over because instructions might have been changed.
11556         Changed = true;
11557       } else if (LimitForRegisterSize) {
11558         // Try to vectorize using small vectors.
11559         for (auto *It = Candidates.begin(), *End = Candidates.end();
11560              It != End;) {
11561           auto *SameTypeIt = It;
11562           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
11563             ++SameTypeIt;
11564           unsigned NumElts = (SameTypeIt - It);
11565           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
11566                                             /*LimitForRegisterSize=*/false))
11567             Changed = true;
11568           It = SameTypeIt;
11569         }
11570       }
11571       Candidates.clear();
11572     }
11573 
11574     // Start over at the next instruction of a different type (or the end).
11575     IncIt = SameTypeIt;
11576   }
11577   return Changed;
11578 }
11579 
11580 /// Compare two cmp instructions. If IsCompatibility is true, function returns
11581 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
11582 /// operands. If IsCompatibility is false, function implements strict weak
11583 /// ordering relation between two cmp instructions, returning true if the first
11584 /// instruction is "less" than the second, i.e. its predicate is less than the
11585 /// predicate of the second or the operands IDs are less than the operands IDs
11586 /// of the second cmp instruction.
11587 template <bool IsCompatibility>
11588 static bool compareCmp(Value *V, Value *V2,
11589                        function_ref<bool(Instruction *)> IsDeleted) {
11590   auto *CI1 = cast<CmpInst>(V);
11591   auto *CI2 = cast<CmpInst>(V2);
11592   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
11593     return false;
11594   if (CI1->getOperand(0)->getType()->getTypeID() <
11595       CI2->getOperand(0)->getType()->getTypeID())
11596     return !IsCompatibility;
11597   if (CI1->getOperand(0)->getType()->getTypeID() >
11598       CI2->getOperand(0)->getType()->getTypeID())
11599     return false;
11600   CmpInst::Predicate Pred1 = CI1->getPredicate();
11601   CmpInst::Predicate Pred2 = CI2->getPredicate();
11602   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
11603   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
11604   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
11605   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
11606   if (BasePred1 < BasePred2)
11607     return !IsCompatibility;
11608   if (BasePred1 > BasePred2)
11609     return false;
11610   // Compare operands.
11611   bool LEPreds = Pred1 <= Pred2;
11612   bool GEPreds = Pred1 >= Pred2;
11613   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
11614     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
11615     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
11616     if (Op1->getValueID() < Op2->getValueID())
11617       return !IsCompatibility;
11618     if (Op1->getValueID() > Op2->getValueID())
11619       return false;
11620     if (auto *I1 = dyn_cast<Instruction>(Op1))
11621       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
11622         if (I1->getParent() != I2->getParent())
11623           return false;
11624         InstructionsState S = getSameOpcode({I1, I2});
11625         if (S.getOpcode())
11626           continue;
11627         return false;
11628       }
11629   }
11630   return IsCompatibility;
11631 }
11632 
11633 bool SLPVectorizerPass::vectorizeSimpleInstructions(
11634     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
11635     bool AtTerminator) {
11636   bool OpsChanged = false;
11637   SmallVector<Instruction *, 4> PostponedCmps;
11638   for (auto *I : reverse(Instructions)) {
11639     if (R.isDeleted(I))
11640       continue;
11641     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
11642       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
11643     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
11644       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
11645     } else if (isa<CmpInst>(I)) {
11646       PostponedCmps.push_back(I);
11647       continue;
11648     }
11649     // Try to find reductions in buildvector sequnces.
11650     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
11651   }
11652   if (AtTerminator) {
11653     // Try to find reductions first.
11654     for (Instruction *I : PostponedCmps) {
11655       if (R.isDeleted(I))
11656         continue;
11657       for (Value *Op : I->operands())
11658         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
11659     }
11660     // Try to vectorize operands as vector bundles.
11661     for (Instruction *I : PostponedCmps) {
11662       if (R.isDeleted(I))
11663         continue;
11664       OpsChanged |= tryToVectorize(I, R);
11665     }
11666     // Try to vectorize list of compares.
11667     // Sort by type, compare predicate, etc.
11668     auto &&CompareSorter = [&R](Value *V, Value *V2) {
11669       return compareCmp<false>(V, V2,
11670                                [&R](Instruction *I) { return R.isDeleted(I); });
11671     };
11672 
11673     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
11674       if (V1 == V2)
11675         return true;
11676       return compareCmp<true>(V1, V2,
11677                               [&R](Instruction *I) { return R.isDeleted(I); });
11678     };
11679     auto Limit = [&R](Value *V) {
11680       unsigned EltSize = R.getVectorElementSize(V);
11681       return std::max(2U, R.getMaxVecRegSize() / EltSize);
11682     };
11683 
11684     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
11685     OpsChanged |= tryToVectorizeSequence<Value>(
11686         Vals, Limit, CompareSorter, AreCompatibleCompares,
11687         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11688           // Exclude possible reductions from other blocks.
11689           bool ArePossiblyReducedInOtherBlock =
11690               any_of(Candidates, [](Value *V) {
11691                 return any_of(V->users(), [V](User *U) {
11692                   return isa<SelectInst>(U) &&
11693                          cast<SelectInst>(U)->getParent() !=
11694                              cast<Instruction>(V)->getParent();
11695                 });
11696               });
11697           if (ArePossiblyReducedInOtherBlock)
11698             return false;
11699           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11700         },
11701         /*LimitForRegisterSize=*/true);
11702     Instructions.clear();
11703   } else {
11704     // Insert in reverse order since the PostponedCmps vector was filled in
11705     // reverse order.
11706     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
11707   }
11708   return OpsChanged;
11709 }
11710 
11711 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
11712   bool Changed = false;
11713   SmallVector<Value *, 4> Incoming;
11714   SmallPtrSet<Value *, 16> VisitedInstrs;
11715   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11716   // node. Allows better to identify the chains that can be vectorized in the
11717   // better way.
11718   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11719   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11720     assert(isValidElementType(V1->getType()) &&
11721            isValidElementType(V2->getType()) &&
11722            "Expected vectorizable types only.");
11723     // It is fine to compare type IDs here, since we expect only vectorizable
11724     // types, like ints, floats and pointers, we don't care about other type.
11725     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11726       return true;
11727     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11728       return false;
11729     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11730     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11731     if (Opcodes1.size() < Opcodes2.size())
11732       return true;
11733     if (Opcodes1.size() > Opcodes2.size())
11734       return false;
11735     Optional<bool> ConstOrder;
11736     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11737       // Undefs are compatible with any other value.
11738       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11739         if (!ConstOrder)
11740           ConstOrder =
11741               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11742         continue;
11743       }
11744       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11745         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11746           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11747           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11748           if (!NodeI1)
11749             return NodeI2 != nullptr;
11750           if (!NodeI2)
11751             return false;
11752           assert((NodeI1 == NodeI2) ==
11753                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11754                  "Different nodes should have different DFS numbers");
11755           if (NodeI1 != NodeI2)
11756             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11757           InstructionsState S = getSameOpcode({I1, I2});
11758           if (S.getOpcode())
11759             continue;
11760           return I1->getOpcode() < I2->getOpcode();
11761         }
11762       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11763         if (!ConstOrder)
11764           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11765         continue;
11766       }
11767       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11768         return true;
11769       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11770         return false;
11771     }
11772     return ConstOrder && *ConstOrder;
11773   };
11774   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11775     if (V1 == V2)
11776       return true;
11777     if (V1->getType() != V2->getType())
11778       return false;
11779     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11780     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11781     if (Opcodes1.size() != Opcodes2.size())
11782       return false;
11783     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11784       // Undefs are compatible with any other value.
11785       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11786         continue;
11787       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11788         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11789           if (I1->getParent() != I2->getParent())
11790             return false;
11791           InstructionsState S = getSameOpcode({I1, I2});
11792           if (S.getOpcode())
11793             continue;
11794           return false;
11795         }
11796       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11797         continue;
11798       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11799         return false;
11800     }
11801     return true;
11802   };
11803   auto Limit = [&R](Value *V) {
11804     unsigned EltSize = R.getVectorElementSize(V);
11805     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11806   };
11807 
11808   bool HaveVectorizedPhiNodes = false;
11809   do {
11810     // Collect the incoming values from the PHIs.
11811     Incoming.clear();
11812     for (Instruction &I : *BB) {
11813       PHINode *P = dyn_cast<PHINode>(&I);
11814       if (!P)
11815         break;
11816 
11817       // No need to analyze deleted, vectorized and non-vectorizable
11818       // instructions.
11819       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11820           isValidElementType(P->getType()))
11821         Incoming.push_back(P);
11822     }
11823 
11824     // Find the corresponding non-phi nodes for better matching when trying to
11825     // build the tree.
11826     for (Value *V : Incoming) {
11827       SmallVectorImpl<Value *> &Opcodes =
11828           PHIToOpcodes.try_emplace(V).first->getSecond();
11829       if (!Opcodes.empty())
11830         continue;
11831       SmallVector<Value *, 4> Nodes(1, V);
11832       SmallPtrSet<Value *, 4> Visited;
11833       while (!Nodes.empty()) {
11834         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11835         if (!Visited.insert(PHI).second)
11836           continue;
11837         for (Value *V : PHI->incoming_values()) {
11838           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11839             Nodes.push_back(PHI1);
11840             continue;
11841           }
11842           Opcodes.emplace_back(V);
11843         }
11844       }
11845     }
11846 
11847     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11848         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11849         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11850           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11851         },
11852         /*LimitForRegisterSize=*/true);
11853     Changed |= HaveVectorizedPhiNodes;
11854     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11855   } while (HaveVectorizedPhiNodes);
11856 
11857   VisitedInstrs.clear();
11858 
11859   SmallVector<Instruction *, 8> PostProcessInstructions;
11860   SmallDenseSet<Instruction *, 4> KeyNodes;
11861   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11862     // Skip instructions with scalable type. The num of elements is unknown at
11863     // compile-time for scalable type.
11864     if (isa<ScalableVectorType>(it->getType()))
11865       continue;
11866 
11867     // Skip instructions marked for the deletion.
11868     if (R.isDeleted(&*it))
11869       continue;
11870     // We may go through BB multiple times so skip the one we have checked.
11871     if (!VisitedInstrs.insert(&*it).second) {
11872       if (it->use_empty() && KeyNodes.contains(&*it) &&
11873           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11874                                       it->isTerminator())) {
11875         // We would like to start over since some instructions are deleted
11876         // and the iterator may become invalid value.
11877         Changed = true;
11878         it = BB->begin();
11879         e = BB->end();
11880       }
11881       continue;
11882     }
11883 
11884     if (isa<DbgInfoIntrinsic>(it))
11885       continue;
11886 
11887     // Try to vectorize reductions that use PHINodes.
11888     if (PHINode *P = dyn_cast<PHINode>(it)) {
11889       // Check that the PHI is a reduction PHI.
11890       if (P->getNumIncomingValues() == 2) {
11891         // Try to match and vectorize a horizontal reduction.
11892         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11893                                      TTI)) {
11894           Changed = true;
11895           it = BB->begin();
11896           e = BB->end();
11897           continue;
11898         }
11899       }
11900       // Try to vectorize the incoming values of the PHI, to catch reductions
11901       // that feed into PHIs.
11902       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11903         // Skip if the incoming block is the current BB for now. Also, bypass
11904         // unreachable IR for efficiency and to avoid crashing.
11905         // TODO: Collect the skipped incoming values and try to vectorize them
11906         // after processing BB.
11907         if (BB == P->getIncomingBlock(I) ||
11908             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11909           continue;
11910 
11911         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11912                                             P->getIncomingBlock(I), R, TTI);
11913       }
11914       continue;
11915     }
11916 
11917     // Ran into an instruction without users, like terminator, or function call
11918     // with ignored return value, store. Ignore unused instructions (basing on
11919     // instruction type, except for CallInst and InvokeInst).
11920     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11921                             isa<InvokeInst>(it))) {
11922       KeyNodes.insert(&*it);
11923       bool OpsChanged = false;
11924       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11925         for (auto *V : it->operand_values()) {
11926           // Try to match and vectorize a horizontal reduction.
11927           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11928         }
11929       }
11930       // Start vectorization of post-process list of instructions from the
11931       // top-tree instructions to try to vectorize as many instructions as
11932       // possible.
11933       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11934                                                 it->isTerminator());
11935       if (OpsChanged) {
11936         // We would like to start over since some instructions are deleted
11937         // and the iterator may become invalid value.
11938         Changed = true;
11939         it = BB->begin();
11940         e = BB->end();
11941         continue;
11942       }
11943     }
11944 
11945     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11946         isa<InsertValueInst>(it))
11947       PostProcessInstructions.push_back(&*it);
11948   }
11949 
11950   return Changed;
11951 }
11952 
11953 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11954   auto Changed = false;
11955   for (auto &Entry : GEPs) {
11956     // If the getelementptr list has fewer than two elements, there's nothing
11957     // to do.
11958     if (Entry.second.size() < 2)
11959       continue;
11960 
11961     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11962                       << Entry.second.size() << ".\n");
11963 
11964     // Process the GEP list in chunks suitable for the target's supported
11965     // vector size. If a vector register can't hold 1 element, we are done. We
11966     // are trying to vectorize the index computations, so the maximum number of
11967     // elements is based on the size of the index expression, rather than the
11968     // size of the GEP itself (the target's pointer size).
11969     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11970     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11971     if (MaxVecRegSize < EltSize)
11972       continue;
11973 
11974     unsigned MaxElts = MaxVecRegSize / EltSize;
11975     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11976       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11977       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11978 
11979       // Initialize a set a candidate getelementptrs. Note that we use a
11980       // SetVector here to preserve program order. If the index computations
11981       // are vectorizable and begin with loads, we want to minimize the chance
11982       // of having to reorder them later.
11983       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11984 
11985       // Some of the candidates may have already been vectorized after we
11986       // initially collected them. If so, they are marked as deleted, so remove
11987       // them from the set of candidates.
11988       Candidates.remove_if(
11989           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11990 
11991       // Remove from the set of candidates all pairs of getelementptrs with
11992       // constant differences. Such getelementptrs are likely not good
11993       // candidates for vectorization in a bottom-up phase since one can be
11994       // computed from the other. We also ensure all candidate getelementptr
11995       // indices are unique.
11996       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11997         auto *GEPI = GEPList[I];
11998         if (!Candidates.count(GEPI))
11999           continue;
12000         auto *SCEVI = SE->getSCEV(GEPList[I]);
12001         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
12002           auto *GEPJ = GEPList[J];
12003           auto *SCEVJ = SE->getSCEV(GEPList[J]);
12004           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
12005             Candidates.remove(GEPI);
12006             Candidates.remove(GEPJ);
12007           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
12008             Candidates.remove(GEPJ);
12009           }
12010         }
12011       }
12012 
12013       // We break out of the above computation as soon as we know there are
12014       // fewer than two candidates remaining.
12015       if (Candidates.size() < 2)
12016         continue;
12017 
12018       // Add the single, non-constant index of each candidate to the bundle. We
12019       // ensured the indices met these constraints when we originally collected
12020       // the getelementptrs.
12021       SmallVector<Value *, 16> Bundle(Candidates.size());
12022       auto BundleIndex = 0u;
12023       for (auto *V : Candidates) {
12024         auto *GEP = cast<GetElementPtrInst>(V);
12025         auto *GEPIdx = GEP->idx_begin()->get();
12026         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
12027         Bundle[BundleIndex++] = GEPIdx;
12028       }
12029 
12030       // Try and vectorize the indices. We are currently only interested in
12031       // gather-like cases of the form:
12032       //
12033       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
12034       //
12035       // where the loads of "a", the loads of "b", and the subtractions can be
12036       // performed in parallel. It's likely that detecting this pattern in a
12037       // bottom-up phase will be simpler and less costly than building a
12038       // full-blown top-down phase beginning at the consecutive loads.
12039       Changed |= tryToVectorizeList(Bundle, R);
12040     }
12041   }
12042   return Changed;
12043 }
12044 
12045 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
12046   bool Changed = false;
12047   // Sort by type, base pointers and values operand. Value operands must be
12048   // compatible (have the same opcode, same parent), otherwise it is
12049   // definitely not profitable to try to vectorize them.
12050   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
12051     if (V->getPointerOperandType()->getTypeID() <
12052         V2->getPointerOperandType()->getTypeID())
12053       return true;
12054     if (V->getPointerOperandType()->getTypeID() >
12055         V2->getPointerOperandType()->getTypeID())
12056       return false;
12057     // UndefValues are compatible with all other values.
12058     if (isa<UndefValue>(V->getValueOperand()) ||
12059         isa<UndefValue>(V2->getValueOperand()))
12060       return false;
12061     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
12062       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
12063         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
12064             DT->getNode(I1->getParent());
12065         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
12066             DT->getNode(I2->getParent());
12067         assert(NodeI1 && "Should only process reachable instructions");
12068         assert(NodeI2 && "Should only process reachable instructions");
12069         assert((NodeI1 == NodeI2) ==
12070                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
12071                "Different nodes should have different DFS numbers");
12072         if (NodeI1 != NodeI2)
12073           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
12074         InstructionsState S = getSameOpcode({I1, I2});
12075         if (S.getOpcode())
12076           return false;
12077         return I1->getOpcode() < I2->getOpcode();
12078       }
12079     if (isa<Constant>(V->getValueOperand()) &&
12080         isa<Constant>(V2->getValueOperand()))
12081       return false;
12082     return V->getValueOperand()->getValueID() <
12083            V2->getValueOperand()->getValueID();
12084   };
12085 
12086   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
12087     if (V1 == V2)
12088       return true;
12089     if (V1->getPointerOperandType() != V2->getPointerOperandType())
12090       return false;
12091     // Undefs are compatible with any other value.
12092     if (isa<UndefValue>(V1->getValueOperand()) ||
12093         isa<UndefValue>(V2->getValueOperand()))
12094       return true;
12095     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
12096       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
12097         if (I1->getParent() != I2->getParent())
12098           return false;
12099         InstructionsState S = getSameOpcode({I1, I2});
12100         return S.getOpcode() > 0;
12101       }
12102     if (isa<Constant>(V1->getValueOperand()) &&
12103         isa<Constant>(V2->getValueOperand()))
12104       return true;
12105     return V1->getValueOperand()->getValueID() ==
12106            V2->getValueOperand()->getValueID();
12107   };
12108   auto Limit = [&R, this](StoreInst *SI) {
12109     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
12110     return R.getMinVF(EltSize);
12111   };
12112 
12113   // Attempt to sort and vectorize each of the store-groups.
12114   for (auto &Pair : Stores) {
12115     if (Pair.second.size() < 2)
12116       continue;
12117 
12118     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
12119                       << Pair.second.size() << ".\n");
12120 
12121     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
12122       continue;
12123 
12124     Changed |= tryToVectorizeSequence<StoreInst>(
12125         Pair.second, Limit, StoreSorter, AreCompatibleStores,
12126         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
12127           return vectorizeStores(Candidates, R);
12128         },
12129         /*LimitForRegisterSize=*/false);
12130   }
12131   return Changed;
12132 }
12133 
12134 char SLPVectorizer::ID = 0;
12135 
12136 static const char lv_name[] = "SLP Vectorizer";
12137 
12138 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
12139 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
12140 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
12141 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12142 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
12143 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
12144 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
12145 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
12146 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
12147 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
12148 
12149 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
12150