1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The maximum depth that the look-ahead score heuristic will explore
168 // when it probing among candidates for vectorization tree roots.
169 // The higher this value, the higher the compilation time overhead but unlike
170 // similar limit for operands ordering this is less frequently used, hence
171 // impact of higher value is less noticeable.
172 static cl::opt<int> RootLookAheadMaxDepth(
173     "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174     cl::desc("The maximum look-ahead depth for searching best rooting option"));
175 
176 static cl::opt<bool>
177     ViewSLPTree("view-slp-tree", cl::Hidden,
178                 cl::desc("Display the SLP trees with Graphviz"));
179 
180 // Limit the number of alias checks. The limit is chosen so that
181 // it has no negative effect on the llvm benchmarks.
182 static const unsigned AliasedCheckLimit = 10;
183 
184 // Another limit for the alias checks: The maximum distance between load/store
185 // instructions where alias checks are done.
186 // This limit is useful for very large basic blocks.
187 static const unsigned MaxMemDepDistance = 160;
188 
189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190 /// regions to be handled.
191 static const int MinScheduleRegionSize = 16;
192 
193 /// Predicate for the element types that the SLP vectorizer supports.
194 ///
195 /// The most important thing to filter here are types which are invalid in LLVM
196 /// vectors. We also filter target specific types which have absolutely no
197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198 /// avoids spending time checking the cost model and realizing that they will
199 /// be inevitably scalarized.
200 static bool isValidElementType(Type *Ty) {
201   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202          !Ty->isPPC_FP128Ty();
203 }
204 
205 /// \returns True if the value is a constant (but not globals/constant
206 /// expressions).
207 static bool isConstant(Value *V) {
208   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
209 }
210 
211 /// Checks if \p V is one of vector-like instructions, i.e. undef,
212 /// insertelement/extractelement with constant indices for fixed vector type or
213 /// extractvalue instruction.
214 static bool isVectorLikeInstWithConstOps(Value *V) {
215   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216       !isa<ExtractValueInst, UndefValue>(V))
217     return false;
218   auto *I = dyn_cast<Instruction>(V);
219   if (!I || isa<ExtractValueInst>(I))
220     return true;
221   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222     return false;
223   if (isa<ExtractElementInst>(I))
224     return isConstant(I->getOperand(1));
225   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226   return isConstant(I->getOperand(2));
227 }
228 
229 /// \returns true if all of the instructions in \p VL are in the same block or
230 /// false otherwise.
231 static bool allSameBlock(ArrayRef<Value *> VL) {
232   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233   if (!I0)
234     return false;
235   if (all_of(VL, isVectorLikeInstWithConstOps))
236     return true;
237 
238   BasicBlock *BB = I0->getParent();
239   for (int I = 1, E = VL.size(); I < E; I++) {
240     auto *II = dyn_cast<Instruction>(VL[I]);
241     if (!II)
242       return false;
243 
244     if (BB != II->getParent())
245       return false;
246   }
247   return true;
248 }
249 
250 /// \returns True if all of the values in \p VL are constants (but not
251 /// globals/constant expressions).
252 static bool allConstant(ArrayRef<Value *> VL) {
253   // Constant expressions and globals can't be vectorized like normal integer/FP
254   // constants.
255   return all_of(VL, isConstant);
256 }
257 
258 /// \returns True if all of the values in \p VL are identical or some of them
259 /// are UndefValue.
260 static bool isSplat(ArrayRef<Value *> VL) {
261   Value *FirstNonUndef = nullptr;
262   for (Value *V : VL) {
263     if (isa<UndefValue>(V))
264       continue;
265     if (!FirstNonUndef) {
266       FirstNonUndef = V;
267       continue;
268     }
269     if (V != FirstNonUndef)
270       return false;
271   }
272   return FirstNonUndef != nullptr;
273 }
274 
275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
276 static bool isCommutative(Instruction *I) {
277   if (auto *Cmp = dyn_cast<CmpInst>(I))
278     return Cmp->isCommutative();
279   if (auto *BO = dyn_cast<BinaryOperator>(I))
280     return BO->isCommutative();
281   // TODO: This should check for generic Instruction::isCommutative(), but
282   //       we need to confirm that the caller code correctly handles Intrinsics
283   //       for example (does not have 2 operands).
284   return false;
285 }
286 
287 /// Checks if the given value is actually an undefined constant vector.
288 static bool isUndefVector(const Value *V) {
289   if (isa<UndefValue>(V))
290     return true;
291   auto *C = dyn_cast<Constant>(V);
292   if (!C)
293     return false;
294   if (!C->containsUndefOrPoisonElement())
295     return false;
296   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
297   if (!VecTy)
298     return false;
299   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
300     if (Constant *Elem = C->getAggregateElement(I))
301       if (!isa<UndefValue>(Elem))
302         return false;
303   }
304   return true;
305 }
306 
307 /// Checks if the vector of instructions can be represented as a shuffle, like:
308 /// %x0 = extractelement <4 x i8> %x, i32 0
309 /// %x3 = extractelement <4 x i8> %x, i32 3
310 /// %y1 = extractelement <4 x i8> %y, i32 1
311 /// %y2 = extractelement <4 x i8> %y, i32 2
312 /// %x0x0 = mul i8 %x0, %x0
313 /// %x3x3 = mul i8 %x3, %x3
314 /// %y1y1 = mul i8 %y1, %y1
315 /// %y2y2 = mul i8 %y2, %y2
316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
320 /// ret <4 x i8> %ins4
321 /// can be transformed into:
322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
323 ///                                                         i32 6>
324 /// %2 = mul <4 x i8> %1, %1
325 /// ret <4 x i8> %2
326 /// We convert this initially to something like:
327 /// %x0 = extractelement <4 x i8> %x, i32 0
328 /// %x3 = extractelement <4 x i8> %x, i32 3
329 /// %y1 = extractelement <4 x i8> %y, i32 1
330 /// %y2 = extractelement <4 x i8> %y, i32 2
331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
335 /// %5 = mul <4 x i8> %4, %4
336 /// %6 = extractelement <4 x i8> %5, i32 0
337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
338 /// %7 = extractelement <4 x i8> %5, i32 1
339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
340 /// %8 = extractelement <4 x i8> %5, i32 2
341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
342 /// %9 = extractelement <4 x i8> %5, i32 3
343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
344 /// ret <4 x i8> %ins4
345 /// InstCombiner transforms this into a shuffle and vector mul
346 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
347 /// TODO: Can we split off and reuse the shuffle mask detection from
348 /// TargetTransformInfo::getInstructionThroughput?
349 static Optional<TargetTransformInfo::ShuffleKind>
350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
351   const auto *It =
352       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
353   if (It == VL.end())
354     return None;
355   auto *EI0 = cast<ExtractElementInst>(*It);
356   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
357     return None;
358   unsigned Size =
359       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
360   Value *Vec1 = nullptr;
361   Value *Vec2 = nullptr;
362   enum ShuffleMode { Unknown, Select, Permute };
363   ShuffleMode CommonShuffleMode = Unknown;
364   Mask.assign(VL.size(), UndefMaskElem);
365   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
366     // Undef can be represented as an undef element in a vector.
367     if (isa<UndefValue>(VL[I]))
368       continue;
369     auto *EI = cast<ExtractElementInst>(VL[I]);
370     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
371       return None;
372     auto *Vec = EI->getVectorOperand();
373     // We can extractelement from undef or poison vector.
374     if (isUndefVector(Vec))
375       continue;
376     // All vector operands must have the same number of vector elements.
377     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
378       return None;
379     if (isa<UndefValue>(EI->getIndexOperand()))
380       continue;
381     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
382     if (!Idx)
383       return None;
384     // Undefined behavior if Idx is negative or >= Size.
385     if (Idx->getValue().uge(Size))
386       continue;
387     unsigned IntIdx = Idx->getValue().getZExtValue();
388     Mask[I] = IntIdx;
389     // For correct shuffling we have to have at most 2 different vector operands
390     // in all extractelement instructions.
391     if (!Vec1 || Vec1 == Vec) {
392       Vec1 = Vec;
393     } else if (!Vec2 || Vec2 == Vec) {
394       Vec2 = Vec;
395       Mask[I] += Size;
396     } else {
397       return None;
398     }
399     if (CommonShuffleMode == Permute)
400       continue;
401     // If the extract index is not the same as the operation number, it is a
402     // permutation.
403     if (IntIdx != I) {
404       CommonShuffleMode = Permute;
405       continue;
406     }
407     CommonShuffleMode = Select;
408   }
409   // If we're not crossing lanes in different vectors, consider it as blending.
410   if (CommonShuffleMode == Select && Vec2)
411     return TargetTransformInfo::SK_Select;
412   // If Vec2 was never used, we have a permutation of a single vector, otherwise
413   // we have permutation of 2 vectors.
414   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
415               : TargetTransformInfo::SK_PermuteSingleSrc;
416 }
417 
418 namespace {
419 
420 /// Main data required for vectorization of instructions.
421 struct InstructionsState {
422   /// The very first instruction in the list with the main opcode.
423   Value *OpValue = nullptr;
424 
425   /// The main/alternate instruction.
426   Instruction *MainOp = nullptr;
427   Instruction *AltOp = nullptr;
428 
429   /// The main/alternate opcodes for the list of instructions.
430   unsigned getOpcode() const {
431     return MainOp ? MainOp->getOpcode() : 0;
432   }
433 
434   unsigned getAltOpcode() const {
435     return AltOp ? AltOp->getOpcode() : 0;
436   }
437 
438   /// Some of the instructions in the list have alternate opcodes.
439   bool isAltShuffle() const { return AltOp != MainOp; }
440 
441   bool isOpcodeOrAlt(Instruction *I) const {
442     unsigned CheckedOpcode = I->getOpcode();
443     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
444   }
445 
446   InstructionsState() = delete;
447   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
448       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
449 };
450 
451 } // end anonymous namespace
452 
453 /// Chooses the correct key for scheduling data. If \p Op has the same (or
454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
455 /// OpValue.
456 static Value *isOneOf(const InstructionsState &S, Value *Op) {
457   auto *I = dyn_cast<Instruction>(Op);
458   if (I && S.isOpcodeOrAlt(I))
459     return Op;
460   return S.OpValue;
461 }
462 
463 /// \returns true if \p Opcode is allowed as part of of the main/alternate
464 /// instruction for SLP vectorization.
465 ///
466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
467 /// "shuffled out" lane would result in division by zero.
468 static bool isValidForAlternation(unsigned Opcode) {
469   if (Instruction::isIntDivRem(Opcode))
470     return false;
471 
472   return true;
473 }
474 
475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
476                                        unsigned BaseIndex = 0);
477 
478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
479 /// compatible instructions or constants, or just some other regular values.
480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
481                                 Value *Op1) {
482   return (isConstant(BaseOp0) && isConstant(Op0)) ||
483          (isConstant(BaseOp1) && isConstant(Op1)) ||
484          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
485           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
486          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
487          getSameOpcode({BaseOp1, Op1}).getOpcode();
488 }
489 
490 /// \returns analysis of the Instructions in \p VL described in
491 /// InstructionsState, the Opcode that we suppose the whole list
492 /// could be vectorized even if its structure is diverse.
493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
494                                        unsigned BaseIndex) {
495   // Make sure these are all Instructions.
496   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
497     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
498 
499   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
500   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
501   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
502   CmpInst::Predicate BasePred =
503       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
504               : CmpInst::BAD_ICMP_PREDICATE;
505   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
506   unsigned AltOpcode = Opcode;
507   unsigned AltIndex = BaseIndex;
508 
509   // Check for one alternate opcode from another BinaryOperator.
510   // TODO - generalize to support all operators (types, calls etc.).
511   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
512     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
513     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
514       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
515         continue;
516       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
517           isValidForAlternation(Opcode)) {
518         AltOpcode = InstOpcode;
519         AltIndex = Cnt;
520         continue;
521       }
522     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
523       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
524       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
525       if (Ty0 == Ty1) {
526         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
527           continue;
528         if (Opcode == AltOpcode) {
529           assert(isValidForAlternation(Opcode) &&
530                  isValidForAlternation(InstOpcode) &&
531                  "Cast isn't safe for alternation, logic needs to be updated!");
532           AltOpcode = InstOpcode;
533           AltIndex = Cnt;
534           continue;
535         }
536       }
537     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
538       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
539       auto *Inst = cast<Instruction>(VL[Cnt]);
540       Type *Ty0 = BaseInst->getOperand(0)->getType();
541       Type *Ty1 = Inst->getOperand(0)->getType();
542       if (Ty0 == Ty1) {
543         Value *BaseOp0 = BaseInst->getOperand(0);
544         Value *BaseOp1 = BaseInst->getOperand(1);
545         Value *Op0 = Inst->getOperand(0);
546         Value *Op1 = Inst->getOperand(1);
547         CmpInst::Predicate CurrentPred =
548             cast<CmpInst>(VL[Cnt])->getPredicate();
549         CmpInst::Predicate SwappedCurrentPred =
550             CmpInst::getSwappedPredicate(CurrentPred);
551         // Check for compatible operands. If the corresponding operands are not
552         // compatible - need to perform alternate vectorization.
553         if (InstOpcode == Opcode) {
554           if (BasePred == CurrentPred &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
556             continue;
557           if (BasePred == SwappedCurrentPred &&
558               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
559             continue;
560           if (E == 2 &&
561               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
562             continue;
563           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
564           CmpInst::Predicate AltPred = AltInst->getPredicate();
565           Value *AltOp0 = AltInst->getOperand(0);
566           Value *AltOp1 = AltInst->getOperand(1);
567           // Check if operands are compatible with alternate operands.
568           if (AltPred == CurrentPred &&
569               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
570             continue;
571           if (AltPred == SwappedCurrentPred &&
572               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
573             continue;
574         }
575         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
576           assert(isValidForAlternation(Opcode) &&
577                  isValidForAlternation(InstOpcode) &&
578                  "Cast isn't safe for alternation, logic needs to be updated!");
579           AltIndex = Cnt;
580           continue;
581         }
582         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
583         CmpInst::Predicate AltPred = AltInst->getPredicate();
584         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
585             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
586           continue;
587       }
588     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
589       continue;
590     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
591   }
592 
593   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
594                            cast<Instruction>(VL[AltIndex]));
595 }
596 
597 /// \returns true if all of the values in \p VL have the same type or false
598 /// otherwise.
599 static bool allSameType(ArrayRef<Value *> VL) {
600   Type *Ty = VL[0]->getType();
601   for (int i = 1, e = VL.size(); i < e; i++)
602     if (VL[i]->getType() != Ty)
603       return false;
604 
605   return true;
606 }
607 
608 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
609 static Optional<unsigned> getExtractIndex(Instruction *E) {
610   unsigned Opcode = E->getOpcode();
611   assert((Opcode == Instruction::ExtractElement ||
612           Opcode == Instruction::ExtractValue) &&
613          "Expected extractelement or extractvalue instruction.");
614   if (Opcode == Instruction::ExtractElement) {
615     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
616     if (!CI)
617       return None;
618     return CI->getZExtValue();
619   }
620   ExtractValueInst *EI = cast<ExtractValueInst>(E);
621   if (EI->getNumIndices() != 1)
622     return None;
623   return *EI->idx_begin();
624 }
625 
626 /// \returns True if in-tree use also needs extract. This refers to
627 /// possible scalar operand in vectorized instruction.
628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
629                                     TargetLibraryInfo *TLI) {
630   unsigned Opcode = UserInst->getOpcode();
631   switch (Opcode) {
632   case Instruction::Load: {
633     LoadInst *LI = cast<LoadInst>(UserInst);
634     return (LI->getPointerOperand() == Scalar);
635   }
636   case Instruction::Store: {
637     StoreInst *SI = cast<StoreInst>(UserInst);
638     return (SI->getPointerOperand() == Scalar);
639   }
640   case Instruction::Call: {
641     CallInst *CI = cast<CallInst>(UserInst);
642     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
643     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
644       if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
645         return (CI->getArgOperand(i) == Scalar);
646     }
647     LLVM_FALLTHROUGH;
648   }
649   default:
650     return false;
651   }
652 }
653 
654 /// \returns the AA location that is being access by the instruction.
655 static MemoryLocation getLocation(Instruction *I) {
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return MemoryLocation::get(SI);
658   if (LoadInst *LI = dyn_cast<LoadInst>(I))
659     return MemoryLocation::get(LI);
660   return MemoryLocation();
661 }
662 
663 /// \returns True if the instruction is not a volatile or atomic load/store.
664 static bool isSimple(Instruction *I) {
665   if (LoadInst *LI = dyn_cast<LoadInst>(I))
666     return LI->isSimple();
667   if (StoreInst *SI = dyn_cast<StoreInst>(I))
668     return SI->isSimple();
669   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
670     return !MI->isVolatile();
671   return true;
672 }
673 
674 /// Shuffles \p Mask in accordance with the given \p SubMask.
675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
676   if (SubMask.empty())
677     return;
678   if (Mask.empty()) {
679     Mask.append(SubMask.begin(), SubMask.end());
680     return;
681   }
682   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
683   int TermValue = std::min(Mask.size(), SubMask.size());
684   for (int I = 0, E = SubMask.size(); I < E; ++I) {
685     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
686         Mask[SubMask[I]] >= TermValue)
687       continue;
688     NewMask[I] = Mask[SubMask[I]];
689   }
690   Mask.swap(NewMask);
691 }
692 
693 /// Order may have elements assigned special value (size) which is out of
694 /// bounds. Such indices only appear on places which correspond to undef values
695 /// (see canReuseExtract for details) and used in order to avoid undef values
696 /// have effect on operands ordering.
697 /// The first loop below simply finds all unused indices and then the next loop
698 /// nest assigns these indices for undef values positions.
699 /// As an example below Order has two undef positions and they have assigned
700 /// values 3 and 7 respectively:
701 /// before:  6 9 5 4 9 2 1 0
702 /// after:   6 3 5 4 7 2 1 0
703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
704   const unsigned Sz = Order.size();
705   SmallBitVector UnusedIndices(Sz, /*t=*/true);
706   SmallBitVector MaskedIndices(Sz);
707   for (unsigned I = 0; I < Sz; ++I) {
708     if (Order[I] < Sz)
709       UnusedIndices.reset(Order[I]);
710     else
711       MaskedIndices.set(I);
712   }
713   if (MaskedIndices.none())
714     return;
715   assert(UnusedIndices.count() == MaskedIndices.count() &&
716          "Non-synced masked/available indices.");
717   int Idx = UnusedIndices.find_first();
718   int MIdx = MaskedIndices.find_first();
719   while (MIdx >= 0) {
720     assert(Idx >= 0 && "Indices must be synced.");
721     Order[MIdx] = Idx;
722     Idx = UnusedIndices.find_next(Idx);
723     MIdx = MaskedIndices.find_next(MIdx);
724   }
725 }
726 
727 namespace llvm {
728 
729 static void inversePermutation(ArrayRef<unsigned> Indices,
730                                SmallVectorImpl<int> &Mask) {
731   Mask.clear();
732   const unsigned E = Indices.size();
733   Mask.resize(E, UndefMaskElem);
734   for (unsigned I = 0; I < E; ++I)
735     Mask[Indices[I]] = I;
736 }
737 
738 /// \returns inserting index of InsertElement or InsertValue instruction,
739 /// using Offset as base offset for index.
740 static Optional<unsigned> getInsertIndex(Value *InsertInst,
741                                          unsigned Offset = 0) {
742   int Index = Offset;
743   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
744     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
745       auto *VT = cast<FixedVectorType>(IE->getType());
746       if (CI->getValue().uge(VT->getNumElements()))
747         return None;
748       Index *= VT->getNumElements();
749       Index += CI->getZExtValue();
750       return Index;
751     }
752     return None;
753   }
754 
755   auto *IV = cast<InsertValueInst>(InsertInst);
756   Type *CurrentType = IV->getType();
757   for (unsigned I : IV->indices()) {
758     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
759       Index *= ST->getNumElements();
760       CurrentType = ST->getElementType(I);
761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
762       Index *= AT->getNumElements();
763       CurrentType = AT->getElementType();
764     } else {
765       return None;
766     }
767     Index += I;
768   }
769   return Index;
770 }
771 
772 /// Reorders the list of scalars in accordance with the given \p Mask.
773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
774                            ArrayRef<int> Mask) {
775   assert(!Mask.empty() && "Expected non-empty mask.");
776   SmallVector<Value *> Prev(Scalars.size(),
777                             UndefValue::get(Scalars.front()->getType()));
778   Prev.swap(Scalars);
779   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
780     if (Mask[I] != UndefMaskElem)
781       Scalars[Mask[I]] = Prev[I];
782 }
783 
784 /// Checks if the provided value does not require scheduling. It does not
785 /// require scheduling if this is not an instruction or it is an instruction
786 /// that does not read/write memory and all operands are either not instructions
787 /// or phi nodes or instructions from different blocks.
788 static bool areAllOperandsNonInsts(Value *V) {
789   auto *I = dyn_cast<Instruction>(V);
790   if (!I)
791     return true;
792   return !mayHaveNonDefUseDependency(*I) &&
793     all_of(I->operands(), [I](Value *V) {
794       auto *IO = dyn_cast<Instruction>(V);
795       if (!IO)
796         return true;
797       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
798     });
799 }
800 
801 /// Checks if the provided value does not require scheduling. It does not
802 /// require scheduling if this is not an instruction or it is an instruction
803 /// that does not read/write memory and all users are phi nodes or instructions
804 /// from the different blocks.
805 static bool isUsedOutsideBlock(Value *V) {
806   auto *I = dyn_cast<Instruction>(V);
807   if (!I)
808     return true;
809   // Limits the number of uses to save compile time.
810   constexpr int UsesLimit = 8;
811   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
812          all_of(I->users(), [I](User *U) {
813            auto *IU = dyn_cast<Instruction>(U);
814            if (!IU)
815              return true;
816            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
817          });
818 }
819 
820 /// Checks if the specified value does not require scheduling. It does not
821 /// require scheduling if all operands and all users do not need to be scheduled
822 /// in the current basic block.
823 static bool doesNotNeedToBeScheduled(Value *V) {
824   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
825 }
826 
827 /// Checks if the specified array of instructions does not require scheduling.
828 /// It is so if all either instructions have operands that do not require
829 /// scheduling or their users do not require scheduling since they are phis or
830 /// in other basic blocks.
831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
832   return !VL.empty() &&
833          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
834 }
835 
836 namespace slpvectorizer {
837 
838 /// Bottom Up SLP Vectorizer.
839 class BoUpSLP {
840   struct TreeEntry;
841   struct ScheduleData;
842 
843 public:
844   using ValueList = SmallVector<Value *, 8>;
845   using InstrList = SmallVector<Instruction *, 16>;
846   using ValueSet = SmallPtrSet<Value *, 16>;
847   using StoreList = SmallVector<StoreInst *, 8>;
848   using ExtraValueToDebugLocsMap =
849       MapVector<Value *, SmallVector<Instruction *, 2>>;
850   using OrdersType = SmallVector<unsigned, 4>;
851 
852   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
853           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
854           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
855           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
856       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
857         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
858     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
859     // Use the vector register size specified by the target unless overridden
860     // by a command-line option.
861     // TODO: It would be better to limit the vectorization factor based on
862     //       data type rather than just register size. For example, x86 AVX has
863     //       256-bit registers, but it does not support integer operations
864     //       at that width (that requires AVX2).
865     if (MaxVectorRegSizeOption.getNumOccurrences())
866       MaxVecRegSize = MaxVectorRegSizeOption;
867     else
868       MaxVecRegSize =
869           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
870               .getFixedSize();
871 
872     if (MinVectorRegSizeOption.getNumOccurrences())
873       MinVecRegSize = MinVectorRegSizeOption;
874     else
875       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
876   }
877 
878   /// Vectorize the tree that starts with the elements in \p VL.
879   /// Returns the vectorized root.
880   Value *vectorizeTree();
881 
882   /// Vectorize the tree but with the list of externally used values \p
883   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
884   /// generated extractvalue instructions.
885   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
886 
887   /// \returns the cost incurred by unwanted spills and fills, caused by
888   /// holding live values over call sites.
889   InstructionCost getSpillCost() const;
890 
891   /// \returns the vectorization cost of the subtree that starts at \p VL.
892   /// A negative number means that this is profitable.
893   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
894 
895   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
896   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
897   void buildTree(ArrayRef<Value *> Roots,
898                  ArrayRef<Value *> UserIgnoreLst = None);
899 
900   /// Builds external uses of the vectorized scalars, i.e. the list of
901   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
902   /// ExternallyUsedValues contains additional list of external uses to handle
903   /// vectorization of reductions.
904   void
905   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
906 
907   /// Clear the internal data structures that are created by 'buildTree'.
908   void deleteTree() {
909     VectorizableTree.clear();
910     ScalarToTreeEntry.clear();
911     MustGather.clear();
912     ExternalUses.clear();
913     for (auto &Iter : BlocksSchedules) {
914       BlockScheduling *BS = Iter.second.get();
915       BS->clear();
916     }
917     MinBWs.clear();
918     InstrElementSize.clear();
919   }
920 
921   unsigned getTreeSize() const { return VectorizableTree.size(); }
922 
923   /// Perform LICM and CSE on the newly generated gather sequences.
924   void optimizeGatherSequence();
925 
926   /// Checks if the specified gather tree entry \p TE can be represented as a
927   /// shuffled vector entry + (possibly) permutation with other gathers. It
928   /// implements the checks only for possibly ordered scalars (Loads,
929   /// ExtractElement, ExtractValue), which can be part of the graph.
930   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
931 
932   /// Gets reordering data for the given tree entry. If the entry is vectorized
933   /// - just return ReorderIndices, otherwise check if the scalars can be
934   /// reordered and return the most optimal order.
935   /// \param TopToBottom If true, include the order of vectorized stores and
936   /// insertelement nodes, otherwise skip them.
937   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
938 
939   /// Reorders the current graph to the most profitable order starting from the
940   /// root node to the leaf nodes. The best order is chosen only from the nodes
941   /// of the same size (vectorization factor). Smaller nodes are considered
942   /// parts of subgraph with smaller VF and they are reordered independently. We
943   /// can make it because we still need to extend smaller nodes to the wider VF
944   /// and we can merge reordering shuffles with the widening shuffles.
945   void reorderTopToBottom();
946 
947   /// Reorders the current graph to the most profitable order starting from
948   /// leaves to the root. It allows to rotate small subgraphs and reduce the
949   /// number of reshuffles if the leaf nodes use the same order. In this case we
950   /// can merge the orders and just shuffle user node instead of shuffling its
951   /// operands. Plus, even the leaf nodes have different orders, it allows to
952   /// sink reordering in the graph closer to the root node and merge it later
953   /// during analysis.
954   void reorderBottomToTop(bool IgnoreReorder = false);
955 
956   /// \return The vector element size in bits to use when vectorizing the
957   /// expression tree ending at \p V. If V is a store, the size is the width of
958   /// the stored value. Otherwise, the size is the width of the largest loaded
959   /// value reaching V. This method is used by the vectorizer to calculate
960   /// vectorization factors.
961   unsigned getVectorElementSize(Value *V);
962 
963   /// Compute the minimum type sizes required to represent the entries in a
964   /// vectorizable tree.
965   void computeMinimumValueSizes();
966 
967   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
968   unsigned getMaxVecRegSize() const {
969     return MaxVecRegSize;
970   }
971 
972   // \returns minimum vector register size as set by cl::opt.
973   unsigned getMinVecRegSize() const {
974     return MinVecRegSize;
975   }
976 
977   unsigned getMinVF(unsigned Sz) const {
978     return std::max(2U, getMinVecRegSize() / Sz);
979   }
980 
981   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
982     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
983       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
984     return MaxVF ? MaxVF : UINT_MAX;
985   }
986 
987   /// Check if homogeneous aggregate is isomorphic to some VectorType.
988   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
989   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
990   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
991   ///
992   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
993   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
994 
995   /// \returns True if the VectorizableTree is both tiny and not fully
996   /// vectorizable. We do not vectorize such trees.
997   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
998 
999   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1007 
1008   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1009   /// can be load combined in the backend. Load combining may not be allowed in
1010   /// the IR optimizer, so we do not want to alter the pattern. For example,
1011   /// partially transforming a scalar bswap() pattern into vector code is
1012   /// effectively impossible for the backend to undo.
1013   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1014   ///       may not be necessary.
1015   bool isLoadCombineCandidate() const;
1016 
1017   OptimizationRemarkEmitter *getORE() { return ORE; }
1018 
1019   /// This structure holds any data we need about the edges being traversed
1020   /// during buildTree_rec(). We keep track of:
1021   /// (i) the user TreeEntry index, and
1022   /// (ii) the index of the edge.
1023   struct EdgeInfo {
1024     EdgeInfo() = default;
1025     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1026         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1027     /// The user TreeEntry.
1028     TreeEntry *UserTE = nullptr;
1029     /// The operand index of the use.
1030     unsigned EdgeIdx = UINT_MAX;
1031 #ifndef NDEBUG
1032     friend inline raw_ostream &operator<<(raw_ostream &OS,
1033                                           const BoUpSLP::EdgeInfo &EI) {
1034       EI.dump(OS);
1035       return OS;
1036     }
1037     /// Debug print.
1038     void dump(raw_ostream &OS) const {
1039       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1040          << " EdgeIdx:" << EdgeIdx << "}";
1041     }
1042     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1043 #endif
1044   };
1045 
1046   /// A helper class used for scoring candidates for two consecutive lanes.
1047   class LookAheadHeuristics {
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051     int NumLanes; // Total number of lanes (aka vectorization factor).
1052     int MaxLevel; // The maximum recursion depth for accumulating score.
1053 
1054   public:
1055     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1056                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1057         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1058 
1059     // The hard-coded scores listed here are not very important, though it shall
1060     // be higher for better matches to improve the resulting cost. When
1061     // computing the scores of matching one sub-tree with another, we are
1062     // basically counting the number of values that are matching. So even if all
1063     // scores are set to 1, we would still get a decent matching result.
1064     // However, sometimes we have to break ties. For example we may have to
1065     // choose between matching loads vs matching opcodes. This is what these
1066     // scores are helping us with: they provide the order of preference. Also,
1067     // this is important if the scalar is externally used or used in another
1068     // tree entry node in the different lane.
1069 
1070     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1071     static const int ScoreConsecutiveLoads = 4;
1072     /// The same load multiple times. This should have a better score than
1073     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1074     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1075     /// a vector load and 1.0 for a broadcast.
1076     static const int ScoreSplatLoads = 3;
1077     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1078     static const int ScoreReversedLoads = 3;
1079     /// ExtractElementInst from same vector and consecutive indexes.
1080     static const int ScoreConsecutiveExtracts = 4;
1081     /// ExtractElementInst from same vector and reversed indices.
1082     static const int ScoreReversedExtracts = 3;
1083     /// Constants.
1084     static const int ScoreConstants = 2;
1085     /// Instructions with the same opcode.
1086     static const int ScoreSameOpcode = 2;
1087     /// Instructions with alt opcodes (e.g, add + sub).
1088     static const int ScoreAltOpcodes = 1;
1089     /// Identical instructions (a.k.a. splat or broadcast).
1090     static const int ScoreSplat = 1;
1091     /// Matching with an undef is preferable to failing.
1092     static const int ScoreUndef = 1;
1093     /// Score for failing to find a decent match.
1094     static const int ScoreFail = 0;
1095     /// Score if all users are vectorized.
1096     static const int ScoreAllUserVectorized = 1;
1097 
1098     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1099     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1100     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1101     /// MainAltOps.
1102     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1103                         ArrayRef<Value *> MainAltOps) const {
1104       if (V1 == V2) {
1105         if (isa<LoadInst>(V1)) {
1106           // Retruns true if the users of V1 and V2 won't need to be extracted.
1107           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1108             // Bail out if we have too many uses to save compilation time.
1109             static constexpr unsigned Limit = 8;
1110             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1111               return false;
1112 
1113             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1114               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1115                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1116               });
1117             };
1118             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1119           };
1120           // A broadcast of a load can be cheaper on some targets.
1121           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1122                                           ElementCount::getFixed(NumLanes)) &&
1123               ((int)V1->getNumUses() == NumLanes ||
1124                AllUsersAreInternal(V1, V2)))
1125             return LookAheadHeuristics::ScoreSplatLoads;
1126         }
1127         return LookAheadHeuristics::ScoreSplat;
1128       }
1129 
1130       auto *LI1 = dyn_cast<LoadInst>(V1);
1131       auto *LI2 = dyn_cast<LoadInst>(V2);
1132       if (LI1 && LI2) {
1133         if (LI1->getParent() != LI2->getParent())
1134           return LookAheadHeuristics::ScoreFail;
1135 
1136         Optional<int> Dist = getPointersDiff(
1137             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1138             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1139         if (!Dist || *Dist == 0)
1140           return LookAheadHeuristics::ScoreFail;
1141         // The distance is too large - still may be profitable to use masked
1142         // loads/gathers.
1143         if (std::abs(*Dist) > NumLanes / 2)
1144           return LookAheadHeuristics::ScoreAltOpcodes;
1145         // This still will detect consecutive loads, but we might have "holes"
1146         // in some cases. It is ok for non-power-2 vectorization and may produce
1147         // better results. It should not affect current vectorization.
1148         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1149                            : LookAheadHeuristics::ScoreReversedLoads;
1150       }
1151 
1152       auto *C1 = dyn_cast<Constant>(V1);
1153       auto *C2 = dyn_cast<Constant>(V2);
1154       if (C1 && C2)
1155         return LookAheadHeuristics::ScoreConstants;
1156 
1157       // Extracts from consecutive indexes of the same vector better score as
1158       // the extracts could be optimized away.
1159       Value *EV1;
1160       ConstantInt *Ex1Idx;
1161       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1162         // Undefs are always profitable for extractelements.
1163         if (isa<UndefValue>(V2))
1164           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1165         Value *EV2 = nullptr;
1166         ConstantInt *Ex2Idx = nullptr;
1167         if (match(V2,
1168                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1169                                                          m_Undef())))) {
1170           // Undefs are always profitable for extractelements.
1171           if (!Ex2Idx)
1172             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1173           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1174             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1175           if (EV2 == EV1) {
1176             int Idx1 = Ex1Idx->getZExtValue();
1177             int Idx2 = Ex2Idx->getZExtValue();
1178             int Dist = Idx2 - Idx1;
1179             // The distance is too large - still may be profitable to use
1180             // shuffles.
1181             if (std::abs(Dist) == 0)
1182               return LookAheadHeuristics::ScoreSplat;
1183             if (std::abs(Dist) > NumLanes / 2)
1184               return LookAheadHeuristics::ScoreSameOpcode;
1185             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1186                               : LookAheadHeuristics::ScoreReversedExtracts;
1187           }
1188           return LookAheadHeuristics::ScoreAltOpcodes;
1189         }
1190         return LookAheadHeuristics::ScoreFail;
1191       }
1192 
1193       auto *I1 = dyn_cast<Instruction>(V1);
1194       auto *I2 = dyn_cast<Instruction>(V2);
1195       if (I1 && I2) {
1196         if (I1->getParent() != I2->getParent())
1197           return LookAheadHeuristics::ScoreFail;
1198         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1199         Ops.push_back(I1);
1200         Ops.push_back(I2);
1201         InstructionsState S = getSameOpcode(Ops);
1202         // Note: Only consider instructions with <= 2 operands to avoid
1203         // complexity explosion.
1204         if (S.getOpcode() &&
1205             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1206              !S.isAltShuffle()) &&
1207             all_of(Ops, [&S](Value *V) {
1208               return cast<Instruction>(V)->getNumOperands() ==
1209                      S.MainOp->getNumOperands();
1210             }))
1211           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1212                                   : LookAheadHeuristics::ScoreSameOpcode;
1213       }
1214 
1215       if (isa<UndefValue>(V2))
1216         return LookAheadHeuristics::ScoreUndef;
1217 
1218       return LookAheadHeuristics::ScoreFail;
1219     }
1220 
1221     /// Go through the operands of \p LHS and \p RHS recursively until
1222     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1223     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1224     /// of \p U1 and \p U2), except at the beginning of the recursion where
1225     /// these are set to nullptr.
1226     ///
1227     /// For example:
1228     /// \verbatim
1229     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1230     ///     \ /         \ /         \ /        \ /
1231     ///      +           +           +          +
1232     ///     G1          G2          G3         G4
1233     /// \endverbatim
1234     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1235     /// each level recursively, accumulating the score. It starts from matching
1236     /// the additions at level 0, then moves on to the loads (level 1). The
1237     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1238     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1239     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1240     /// Please note that the order of the operands does not matter, as we
1241     /// evaluate the score of all profitable combinations of operands. In
1242     /// other words the score of G1 and G4 is the same as G1 and G2. This
1243     /// heuristic is based on ideas described in:
1244     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1245     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1246     ///   Luís F. W. Góes
1247     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1248                            Instruction *U2, int CurrLevel,
1249                            ArrayRef<Value *> MainAltOps) const {
1250 
1251       // Get the shallow score of V1 and V2.
1252       int ShallowScoreAtThisLevel =
1253           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1254 
1255       // If reached MaxLevel,
1256       //  or if V1 and V2 are not instructions,
1257       //  or if they are SPLAT,
1258       //  or if they are not consecutive,
1259       //  or if profitable to vectorize loads or extractelements, early return
1260       //  the current cost.
1261       auto *I1 = dyn_cast<Instruction>(LHS);
1262       auto *I2 = dyn_cast<Instruction>(RHS);
1263       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1264           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1265           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1266             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1267             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1268            ShallowScoreAtThisLevel))
1269         return ShallowScoreAtThisLevel;
1270       assert(I1 && I2 && "Should have early exited.");
1271 
1272       // Contains the I2 operand indexes that got matched with I1 operands.
1273       SmallSet<unsigned, 4> Op2Used;
1274 
1275       // Recursion towards the operands of I1 and I2. We are trying all possible
1276       // operand pairs, and keeping track of the best score.
1277       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1278            OpIdx1 != NumOperands1; ++OpIdx1) {
1279         // Try to pair op1I with the best operand of I2.
1280         int MaxTmpScore = 0;
1281         unsigned MaxOpIdx2 = 0;
1282         bool FoundBest = false;
1283         // If I2 is commutative try all combinations.
1284         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1285         unsigned ToIdx = isCommutative(I2)
1286                              ? I2->getNumOperands()
1287                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1288         assert(FromIdx <= ToIdx && "Bad index");
1289         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1290           // Skip operands already paired with OpIdx1.
1291           if (Op2Used.count(OpIdx2))
1292             continue;
1293           // Recursively calculate the cost at each level
1294           int TmpScore =
1295               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1296                                  I1, I2, CurrLevel + 1, None);
1297           // Look for the best score.
1298           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1299               TmpScore > MaxTmpScore) {
1300             MaxTmpScore = TmpScore;
1301             MaxOpIdx2 = OpIdx2;
1302             FoundBest = true;
1303           }
1304         }
1305         if (FoundBest) {
1306           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1307           Op2Used.insert(MaxOpIdx2);
1308           ShallowScoreAtThisLevel += MaxTmpScore;
1309         }
1310       }
1311       return ShallowScoreAtThisLevel;
1312     }
1313   };
1314   /// A helper data structure to hold the operands of a vector of instructions.
1315   /// This supports a fixed vector length for all operand vectors.
1316   class VLOperands {
1317     /// For each operand we need (i) the value, and (ii) the opcode that it
1318     /// would be attached to if the expression was in a left-linearized form.
1319     /// This is required to avoid illegal operand reordering.
1320     /// For example:
1321     /// \verbatim
1322     ///                         0 Op1
1323     ///                         |/
1324     /// Op1 Op2   Linearized    + Op2
1325     ///   \ /     ---------->   |/
1326     ///    -                    -
1327     ///
1328     /// Op1 - Op2            (0 + Op1) - Op2
1329     /// \endverbatim
1330     ///
1331     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1332     ///
1333     /// Another way to think of this is to track all the operations across the
1334     /// path from the operand all the way to the root of the tree and to
1335     /// calculate the operation that corresponds to this path. For example, the
1336     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1337     /// corresponding operation is a '-' (which matches the one in the
1338     /// linearized tree, as shown above).
1339     ///
1340     /// For lack of a better term, we refer to this operation as Accumulated
1341     /// Path Operation (APO).
1342     struct OperandData {
1343       OperandData() = default;
1344       OperandData(Value *V, bool APO, bool IsUsed)
1345           : V(V), APO(APO), IsUsed(IsUsed) {}
1346       /// The operand value.
1347       Value *V = nullptr;
1348       /// TreeEntries only allow a single opcode, or an alternate sequence of
1349       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1350       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1351       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1352       /// (e.g., Add/Mul)
1353       bool APO = false;
1354       /// Helper data for the reordering function.
1355       bool IsUsed = false;
1356     };
1357 
1358     /// During operand reordering, we are trying to select the operand at lane
1359     /// that matches best with the operand at the neighboring lane. Our
1360     /// selection is based on the type of value we are looking for. For example,
1361     /// if the neighboring lane has a load, we need to look for a load that is
1362     /// accessing a consecutive address. These strategies are summarized in the
1363     /// 'ReorderingMode' enumerator.
1364     enum class ReorderingMode {
1365       Load,     ///< Matching loads to consecutive memory addresses
1366       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1367       Constant, ///< Matching constants
1368       Splat,    ///< Matching the same instruction multiple times (broadcast)
1369       Failed,   ///< We failed to create a vectorizable group
1370     };
1371 
1372     using OperandDataVec = SmallVector<OperandData, 2>;
1373 
1374     /// A vector of operand vectors.
1375     SmallVector<OperandDataVec, 4> OpsVec;
1376 
1377     const DataLayout &DL;
1378     ScalarEvolution &SE;
1379     const BoUpSLP &R;
1380 
1381     /// \returns the operand data at \p OpIdx and \p Lane.
1382     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1383       return OpsVec[OpIdx][Lane];
1384     }
1385 
1386     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1387     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1388       return OpsVec[OpIdx][Lane];
1389     }
1390 
1391     /// Clears the used flag for all entries.
1392     void clearUsed() {
1393       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1394            OpIdx != NumOperands; ++OpIdx)
1395         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1396              ++Lane)
1397           OpsVec[OpIdx][Lane].IsUsed = false;
1398     }
1399 
1400     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1401     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1402       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1403     }
1404 
1405     /// \param Lane lane of the operands under analysis.
1406     /// \param OpIdx operand index in \p Lane lane we're looking the best
1407     /// candidate for.
1408     /// \param Idx operand index of the current candidate value.
1409     /// \returns The additional score due to possible broadcasting of the
1410     /// elements in the lane. It is more profitable to have power-of-2 unique
1411     /// elements in the lane, it will be vectorized with higher probability
1412     /// after removing duplicates. Currently the SLP vectorizer supports only
1413     /// vectorization of the power-of-2 number of unique scalars.
1414     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1415       Value *IdxLaneV = getData(Idx, Lane).V;
1416       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1417         return 0;
1418       SmallPtrSet<Value *, 4> Uniques;
1419       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1420         if (Ln == Lane)
1421           continue;
1422         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1423         if (!isa<Instruction>(OpIdxLnV))
1424           return 0;
1425         Uniques.insert(OpIdxLnV);
1426       }
1427       int UniquesCount = Uniques.size();
1428       int UniquesCntWithIdxLaneV =
1429           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1430       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1431       int UniquesCntWithOpIdxLaneV =
1432           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1433       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1434         return 0;
1435       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1436               UniquesCntWithOpIdxLaneV) -
1437              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1438     }
1439 
1440     /// \param Lane lane of the operands under analysis.
1441     /// \param OpIdx operand index in \p Lane lane we're looking the best
1442     /// candidate for.
1443     /// \param Idx operand index of the current candidate value.
1444     /// \returns The additional score for the scalar which users are all
1445     /// vectorized.
1446     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1447       Value *IdxLaneV = getData(Idx, Lane).V;
1448       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1449       // Do not care about number of uses for vector-like instructions
1450       // (extractelement/extractvalue with constant indices), they are extracts
1451       // themselves and already externally used. Vectorization of such
1452       // instructions does not add extra extractelement instruction, just may
1453       // remove it.
1454       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1455           isVectorLikeInstWithConstOps(OpIdxLaneV))
1456         return LookAheadHeuristics::ScoreAllUserVectorized;
1457       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1458       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1459         return 0;
1460       return R.areAllUsersVectorized(IdxLaneI, None)
1461                  ? LookAheadHeuristics::ScoreAllUserVectorized
1462                  : 0;
1463     }
1464 
1465     /// Score scaling factor for fully compatible instructions but with
1466     /// different number of external uses. Allows better selection of the
1467     /// instructions with less external uses.
1468     static const int ScoreScaleFactor = 10;
1469 
1470     /// \Returns the look-ahead score, which tells us how much the sub-trees
1471     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1472     /// score. This helps break ties in an informed way when we cannot decide on
1473     /// the order of the operands by just considering the immediate
1474     /// predecessors.
1475     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1476                           int Lane, unsigned OpIdx, unsigned Idx,
1477                           bool &IsUsed) {
1478       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1479                                     LookAheadMaxDepth);
1480       // Keep track of the instruction stack as we recurse into the operands
1481       // during the look-ahead score exploration.
1482       int Score =
1483           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1484                                        /*CurrLevel=*/1, MainAltOps);
1485       if (Score) {
1486         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1487         if (Score <= -SplatScore) {
1488           // Set the minimum score for splat-like sequence to avoid setting
1489           // failed state.
1490           Score = 1;
1491         } else {
1492           Score += SplatScore;
1493           // Scale score to see the difference between different operands
1494           // and similar operands but all vectorized/not all vectorized
1495           // uses. It does not affect actual selection of the best
1496           // compatible operand in general, just allows to select the
1497           // operand with all vectorized uses.
1498           Score *= ScoreScaleFactor;
1499           Score += getExternalUseScore(Lane, OpIdx, Idx);
1500           IsUsed = true;
1501         }
1502       }
1503       return Score;
1504     }
1505 
1506     /// Best defined scores per lanes between the passes. Used to choose the
1507     /// best operand (with the highest score) between the passes.
1508     /// The key - {Operand Index, Lane}.
1509     /// The value - the best score between the passes for the lane and the
1510     /// operand.
1511     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1512         BestScoresPerLanes;
1513 
1514     // Search all operands in Ops[*][Lane] for the one that matches best
1515     // Ops[OpIdx][LastLane] and return its opreand index.
1516     // If no good match can be found, return None.
1517     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1518                                       ArrayRef<ReorderingMode> ReorderingModes,
1519                                       ArrayRef<Value *> MainAltOps) {
1520       unsigned NumOperands = getNumOperands();
1521 
1522       // The operand of the previous lane at OpIdx.
1523       Value *OpLastLane = getData(OpIdx, LastLane).V;
1524 
1525       // Our strategy mode for OpIdx.
1526       ReorderingMode RMode = ReorderingModes[OpIdx];
1527       if (RMode == ReorderingMode::Failed)
1528         return None;
1529 
1530       // The linearized opcode of the operand at OpIdx, Lane.
1531       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1532 
1533       // The best operand index and its score.
1534       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1535       // are using the score to differentiate between the two.
1536       struct BestOpData {
1537         Optional<unsigned> Idx = None;
1538         unsigned Score = 0;
1539       } BestOp;
1540       BestOp.Score =
1541           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1542               .first->second;
1543 
1544       // Track if the operand must be marked as used. If the operand is set to
1545       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1546       // want to reestimate the operands again on the following iterations).
1547       bool IsUsed =
1548           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1549       // Iterate through all unused operands and look for the best.
1550       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1551         // Get the operand at Idx and Lane.
1552         OperandData &OpData = getData(Idx, Lane);
1553         Value *Op = OpData.V;
1554         bool OpAPO = OpData.APO;
1555 
1556         // Skip already selected operands.
1557         if (OpData.IsUsed)
1558           continue;
1559 
1560         // Skip if we are trying to move the operand to a position with a
1561         // different opcode in the linearized tree form. This would break the
1562         // semantics.
1563         if (OpAPO != OpIdxAPO)
1564           continue;
1565 
1566         // Look for an operand that matches the current mode.
1567         switch (RMode) {
1568         case ReorderingMode::Load:
1569         case ReorderingMode::Constant:
1570         case ReorderingMode::Opcode: {
1571           bool LeftToRight = Lane > LastLane;
1572           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1573           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1574           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1575                                         OpIdx, Idx, IsUsed);
1576           if (Score > static_cast<int>(BestOp.Score)) {
1577             BestOp.Idx = Idx;
1578             BestOp.Score = Score;
1579             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1580           }
1581           break;
1582         }
1583         case ReorderingMode::Splat:
1584           if (Op == OpLastLane)
1585             BestOp.Idx = Idx;
1586           break;
1587         case ReorderingMode::Failed:
1588           llvm_unreachable("Not expected Failed reordering mode.");
1589         }
1590       }
1591 
1592       if (BestOp.Idx) {
1593         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1594         return BestOp.Idx;
1595       }
1596       // If we could not find a good match return None.
1597       return None;
1598     }
1599 
1600     /// Helper for reorderOperandVecs.
1601     /// \returns the lane that we should start reordering from. This is the one
1602     /// which has the least number of operands that can freely move about or
1603     /// less profitable because it already has the most optimal set of operands.
1604     unsigned getBestLaneToStartReordering() const {
1605       unsigned Min = UINT_MAX;
1606       unsigned SameOpNumber = 0;
1607       // std::pair<unsigned, unsigned> is used to implement a simple voting
1608       // algorithm and choose the lane with the least number of operands that
1609       // can freely move about or less profitable because it already has the
1610       // most optimal set of operands. The first unsigned is a counter for
1611       // voting, the second unsigned is the counter of lanes with instructions
1612       // with same/alternate opcodes and same parent basic block.
1613       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1614       // Try to be closer to the original results, if we have multiple lanes
1615       // with same cost. If 2 lanes have the same cost, use the one with the
1616       // lowest index.
1617       for (int I = getNumLanes(); I > 0; --I) {
1618         unsigned Lane = I - 1;
1619         OperandsOrderData NumFreeOpsHash =
1620             getMaxNumOperandsThatCanBeReordered(Lane);
1621         // Compare the number of operands that can move and choose the one with
1622         // the least number.
1623         if (NumFreeOpsHash.NumOfAPOs < Min) {
1624           Min = NumFreeOpsHash.NumOfAPOs;
1625           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1626           HashMap.clear();
1627           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1628         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1629                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1630           // Select the most optimal lane in terms of number of operands that
1631           // should be moved around.
1632           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1633           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1634         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1635                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1636           auto It = HashMap.find(NumFreeOpsHash.Hash);
1637           if (It == HashMap.end())
1638             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1639           else
1640             ++It->second.first;
1641         }
1642       }
1643       // Select the lane with the minimum counter.
1644       unsigned BestLane = 0;
1645       unsigned CntMin = UINT_MAX;
1646       for (const auto &Data : reverse(HashMap)) {
1647         if (Data.second.first < CntMin) {
1648           CntMin = Data.second.first;
1649           BestLane = Data.second.second;
1650         }
1651       }
1652       return BestLane;
1653     }
1654 
1655     /// Data structure that helps to reorder operands.
1656     struct OperandsOrderData {
1657       /// The best number of operands with the same APOs, which can be
1658       /// reordered.
1659       unsigned NumOfAPOs = UINT_MAX;
1660       /// Number of operands with the same/alternate instruction opcode and
1661       /// parent.
1662       unsigned NumOpsWithSameOpcodeParent = 0;
1663       /// Hash for the actual operands ordering.
1664       /// Used to count operands, actually their position id and opcode
1665       /// value. It is used in the voting mechanism to find the lane with the
1666       /// least number of operands that can freely move about or less profitable
1667       /// because it already has the most optimal set of operands. Can be
1668       /// replaced with SmallVector<unsigned> instead but hash code is faster
1669       /// and requires less memory.
1670       unsigned Hash = 0;
1671     };
1672     /// \returns the maximum number of operands that are allowed to be reordered
1673     /// for \p Lane and the number of compatible instructions(with the same
1674     /// parent/opcode). This is used as a heuristic for selecting the first lane
1675     /// to start operand reordering.
1676     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1677       unsigned CntTrue = 0;
1678       unsigned NumOperands = getNumOperands();
1679       // Operands with the same APO can be reordered. We therefore need to count
1680       // how many of them we have for each APO, like this: Cnt[APO] = x.
1681       // Since we only have two APOs, namely true and false, we can avoid using
1682       // a map. Instead we can simply count the number of operands that
1683       // correspond to one of them (in this case the 'true' APO), and calculate
1684       // the other by subtracting it from the total number of operands.
1685       // Operands with the same instruction opcode and parent are more
1686       // profitable since we don't need to move them in many cases, with a high
1687       // probability such lane already can be vectorized effectively.
1688       bool AllUndefs = true;
1689       unsigned NumOpsWithSameOpcodeParent = 0;
1690       Instruction *OpcodeI = nullptr;
1691       BasicBlock *Parent = nullptr;
1692       unsigned Hash = 0;
1693       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1694         const OperandData &OpData = getData(OpIdx, Lane);
1695         if (OpData.APO)
1696           ++CntTrue;
1697         // Use Boyer-Moore majority voting for finding the majority opcode and
1698         // the number of times it occurs.
1699         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1700           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1701               I->getParent() != Parent) {
1702             if (NumOpsWithSameOpcodeParent == 0) {
1703               NumOpsWithSameOpcodeParent = 1;
1704               OpcodeI = I;
1705               Parent = I->getParent();
1706             } else {
1707               --NumOpsWithSameOpcodeParent;
1708             }
1709           } else {
1710             ++NumOpsWithSameOpcodeParent;
1711           }
1712         }
1713         Hash = hash_combine(
1714             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1715         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1716       }
1717       if (AllUndefs)
1718         return {};
1719       OperandsOrderData Data;
1720       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1721       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1722       Data.Hash = Hash;
1723       return Data;
1724     }
1725 
1726     /// Go through the instructions in VL and append their operands.
1727     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1728       assert(!VL.empty() && "Bad VL");
1729       assert((empty() || VL.size() == getNumLanes()) &&
1730              "Expected same number of lanes");
1731       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1732       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1733       OpsVec.resize(NumOperands);
1734       unsigned NumLanes = VL.size();
1735       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1736         OpsVec[OpIdx].resize(NumLanes);
1737         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1738           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1739           // Our tree has just 3 nodes: the root and two operands.
1740           // It is therefore trivial to get the APO. We only need to check the
1741           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1742           // RHS operand. The LHS operand of both add and sub is never attached
1743           // to an inversese operation in the linearized form, therefore its APO
1744           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1745 
1746           // Since operand reordering is performed on groups of commutative
1747           // operations or alternating sequences (e.g., +, -), we can safely
1748           // tell the inverse operations by checking commutativity.
1749           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1750           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1751           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1752                                  APO, false};
1753         }
1754       }
1755     }
1756 
1757     /// \returns the number of operands.
1758     unsigned getNumOperands() const { return OpsVec.size(); }
1759 
1760     /// \returns the number of lanes.
1761     unsigned getNumLanes() const { return OpsVec[0].size(); }
1762 
1763     /// \returns the operand value at \p OpIdx and \p Lane.
1764     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1765       return getData(OpIdx, Lane).V;
1766     }
1767 
1768     /// \returns true if the data structure is empty.
1769     bool empty() const { return OpsVec.empty(); }
1770 
1771     /// Clears the data.
1772     void clear() { OpsVec.clear(); }
1773 
1774     /// \Returns true if there are enough operands identical to \p Op to fill
1775     /// the whole vector.
1776     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1777     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1778       bool OpAPO = getData(OpIdx, Lane).APO;
1779       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1780         if (Ln == Lane)
1781           continue;
1782         // This is set to true if we found a candidate for broadcast at Lane.
1783         bool FoundCandidate = false;
1784         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1785           OperandData &Data = getData(OpI, Ln);
1786           if (Data.APO != OpAPO || Data.IsUsed)
1787             continue;
1788           if (Data.V == Op) {
1789             FoundCandidate = true;
1790             Data.IsUsed = true;
1791             break;
1792           }
1793         }
1794         if (!FoundCandidate)
1795           return false;
1796       }
1797       return true;
1798     }
1799 
1800   public:
1801     /// Initialize with all the operands of the instruction vector \p RootVL.
1802     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1803                ScalarEvolution &SE, const BoUpSLP &R)
1804         : DL(DL), SE(SE), R(R) {
1805       // Append all the operands of RootVL.
1806       appendOperandsOfVL(RootVL);
1807     }
1808 
1809     /// \Returns a value vector with the operands across all lanes for the
1810     /// opearnd at \p OpIdx.
1811     ValueList getVL(unsigned OpIdx) const {
1812       ValueList OpVL(OpsVec[OpIdx].size());
1813       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1814              "Expected same num of lanes across all operands");
1815       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1816         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1817       return OpVL;
1818     }
1819 
1820     // Performs operand reordering for 2 or more operands.
1821     // The original operands are in OrigOps[OpIdx][Lane].
1822     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1823     void reorder() {
1824       unsigned NumOperands = getNumOperands();
1825       unsigned NumLanes = getNumLanes();
1826       // Each operand has its own mode. We are using this mode to help us select
1827       // the instructions for each lane, so that they match best with the ones
1828       // we have selected so far.
1829       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1830 
1831       // This is a greedy single-pass algorithm. We are going over each lane
1832       // once and deciding on the best order right away with no back-tracking.
1833       // However, in order to increase its effectiveness, we start with the lane
1834       // that has operands that can move the least. For example, given the
1835       // following lanes:
1836       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1837       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1838       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1839       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1840       // we will start at Lane 1, since the operands of the subtraction cannot
1841       // be reordered. Then we will visit the rest of the lanes in a circular
1842       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1843 
1844       // Find the first lane that we will start our search from.
1845       unsigned FirstLane = getBestLaneToStartReordering();
1846 
1847       // Initialize the modes.
1848       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1849         Value *OpLane0 = getValue(OpIdx, FirstLane);
1850         // Keep track if we have instructions with all the same opcode on one
1851         // side.
1852         if (isa<LoadInst>(OpLane0))
1853           ReorderingModes[OpIdx] = ReorderingMode::Load;
1854         else if (isa<Instruction>(OpLane0)) {
1855           // Check if OpLane0 should be broadcast.
1856           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1857             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1858           else
1859             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1860         }
1861         else if (isa<Constant>(OpLane0))
1862           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1863         else if (isa<Argument>(OpLane0))
1864           // Our best hope is a Splat. It may save some cost in some cases.
1865           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1866         else
1867           // NOTE: This should be unreachable.
1868           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1869       }
1870 
1871       // Check that we don't have same operands. No need to reorder if operands
1872       // are just perfect diamond or shuffled diamond match. Do not do it only
1873       // for possible broadcasts or non-power of 2 number of scalars (just for
1874       // now).
1875       auto &&SkipReordering = [this]() {
1876         SmallPtrSet<Value *, 4> UniqueValues;
1877         ArrayRef<OperandData> Op0 = OpsVec.front();
1878         for (const OperandData &Data : Op0)
1879           UniqueValues.insert(Data.V);
1880         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1881           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1882                 return !UniqueValues.contains(Data.V);
1883               }))
1884             return false;
1885         }
1886         // TODO: Check if we can remove a check for non-power-2 number of
1887         // scalars after full support of non-power-2 vectorization.
1888         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1889       };
1890 
1891       // If the initial strategy fails for any of the operand indexes, then we
1892       // perform reordering again in a second pass. This helps avoid assigning
1893       // high priority to the failed strategy, and should improve reordering for
1894       // the non-failed operand indexes.
1895       for (int Pass = 0; Pass != 2; ++Pass) {
1896         // Check if no need to reorder operands since they're are perfect or
1897         // shuffled diamond match.
1898         // Need to to do it to avoid extra external use cost counting for
1899         // shuffled matches, which may cause regressions.
1900         if (SkipReordering())
1901           break;
1902         // Skip the second pass if the first pass did not fail.
1903         bool StrategyFailed = false;
1904         // Mark all operand data as free to use.
1905         clearUsed();
1906         // We keep the original operand order for the FirstLane, so reorder the
1907         // rest of the lanes. We are visiting the nodes in a circular fashion,
1908         // using FirstLane as the center point and increasing the radius
1909         // distance.
1910         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1911         for (unsigned I = 0; I < NumOperands; ++I)
1912           MainAltOps[I].push_back(getData(I, FirstLane).V);
1913 
1914         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1915           // Visit the lane on the right and then the lane on the left.
1916           for (int Direction : {+1, -1}) {
1917             int Lane = FirstLane + Direction * Distance;
1918             if (Lane < 0 || Lane >= (int)NumLanes)
1919               continue;
1920             int LastLane = Lane - Direction;
1921             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1922                    "Out of bounds");
1923             // Look for a good match for each operand.
1924             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1925               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1926               Optional<unsigned> BestIdx = getBestOperand(
1927                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1928               // By not selecting a value, we allow the operands that follow to
1929               // select a better matching value. We will get a non-null value in
1930               // the next run of getBestOperand().
1931               if (BestIdx) {
1932                 // Swap the current operand with the one returned by
1933                 // getBestOperand().
1934                 swap(OpIdx, BestIdx.getValue(), Lane);
1935               } else {
1936                 // We failed to find a best operand, set mode to 'Failed'.
1937                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1938                 // Enable the second pass.
1939                 StrategyFailed = true;
1940               }
1941               // Try to get the alternate opcode and follow it during analysis.
1942               if (MainAltOps[OpIdx].size() != 2) {
1943                 OperandData &AltOp = getData(OpIdx, Lane);
1944                 InstructionsState OpS =
1945                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1946                 if (OpS.getOpcode() && OpS.isAltShuffle())
1947                   MainAltOps[OpIdx].push_back(AltOp.V);
1948               }
1949             }
1950           }
1951         }
1952         // Skip second pass if the strategy did not fail.
1953         if (!StrategyFailed)
1954           break;
1955       }
1956     }
1957 
1958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1959     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1960       switch (RMode) {
1961       case ReorderingMode::Load:
1962         return "Load";
1963       case ReorderingMode::Opcode:
1964         return "Opcode";
1965       case ReorderingMode::Constant:
1966         return "Constant";
1967       case ReorderingMode::Splat:
1968         return "Splat";
1969       case ReorderingMode::Failed:
1970         return "Failed";
1971       }
1972       llvm_unreachable("Unimplemented Reordering Type");
1973     }
1974 
1975     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1976                                                    raw_ostream &OS) {
1977       return OS << getModeStr(RMode);
1978     }
1979 
1980     /// Debug print.
1981     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1982       printMode(RMode, dbgs());
1983     }
1984 
1985     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1986       return printMode(RMode, OS);
1987     }
1988 
1989     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1990       const unsigned Indent = 2;
1991       unsigned Cnt = 0;
1992       for (const OperandDataVec &OpDataVec : OpsVec) {
1993         OS << "Operand " << Cnt++ << "\n";
1994         for (const OperandData &OpData : OpDataVec) {
1995           OS.indent(Indent) << "{";
1996           if (Value *V = OpData.V)
1997             OS << *V;
1998           else
1999             OS << "null";
2000           OS << ", APO:" << OpData.APO << "}\n";
2001         }
2002         OS << "\n";
2003       }
2004       return OS;
2005     }
2006 
2007     /// Debug print.
2008     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2009 #endif
2010   };
2011 
2012   /// Evaluate each pair in \p Candidates and return index into \p Candidates
2013   /// for a pair which have highest score deemed to have best chance to form
2014   /// root of profitable tree to vectorize. Return None if no candidate scored
2015   /// above the LookAheadHeuristics::ScoreFail.
2016   Optional<int>
2017   findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates) {
2018     LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2,
2019                                   RootLookAheadMaxDepth);
2020     int BestScore = LookAheadHeuristics::ScoreFail;
2021     Optional<int> Index = None;
2022     for (int I : seq<int>(0, Candidates.size())) {
2023       int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2024                                                Candidates[I].second,
2025                                                /*U1=*/nullptr, /*U2=*/nullptr,
2026                                                /*Level=*/1, None);
2027       if (Score > BestScore) {
2028         BestScore = Score;
2029         Index = I;
2030       }
2031     }
2032     return Index;
2033   }
2034 
2035   /// Checks if the instruction is marked for deletion.
2036   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2037 
2038   /// Removes an instruction from its block and eventually deletes it.
2039   /// It's like Instruction::eraseFromParent() except that the actual deletion
2040   /// is delayed until BoUpSLP is destructed.
2041   void eraseInstruction(Instruction *I) {
2042     DeletedInstructions.insert(I);
2043   }
2044 
2045   /// Checks if the instruction was already analyzed for being possible
2046   /// reduction root.
2047   bool isAnalizedReductionRoot(Instruction *I) const {
2048     return AnalizedReductionsRoots.count(I);
2049   }
2050   /// Register given instruction as already analyzed for being possible
2051   /// reduction root.
2052   void analyzedReductionRoot(Instruction *I) {
2053     AnalizedReductionsRoots.insert(I);
2054   }
2055   /// Checks if the provided list of reduced values was checked already for
2056   /// vectorization.
2057   bool areAnalyzedReductionVals(ArrayRef<Value *> VL) {
2058     return AnalyzedReductionVals.contains(hash_value(VL));
2059   }
2060   /// Adds the list of reduced values to list of already checked values for the
2061   /// vectorization.
2062   void analyzedReductionVals(ArrayRef<Value *> VL) {
2063     AnalyzedReductionVals.insert(hash_value(VL));
2064   }
2065   /// Clear the list of the analyzed reduction root instructions.
2066   void clearReductionData() {
2067     AnalizedReductionsRoots.clear();
2068     AnalyzedReductionVals.clear();
2069   }
2070   /// Checks if the given value is gathered in one of the nodes.
2071   bool isGathered(Value *V) const {
2072     return MustGather.contains(V);
2073   }
2074 
2075   ~BoUpSLP();
2076 
2077 private:
2078   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2079   /// reordering (i.e. the operands can be reordered because they have only one
2080   /// user and reordarable).
2081   /// \param ReorderableGathers List of all gather nodes that require reordering
2082   /// (e.g., gather of extractlements or partially vectorizable loads).
2083   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2084   /// reordering, subset of \p NonVectorized.
2085   bool
2086   canReorderOperands(TreeEntry *UserTE,
2087                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2088                      ArrayRef<TreeEntry *> ReorderableGathers,
2089                      SmallVectorImpl<TreeEntry *> &GatherOps);
2090 
2091   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2092   /// if any. If it is not vectorized (gather node), returns nullptr.
2093   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2094     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2095     TreeEntry *TE = nullptr;
2096     const auto *It = find_if(VL, [this, &TE](Value *V) {
2097       TE = getTreeEntry(V);
2098       return TE;
2099     });
2100     if (It != VL.end() && TE->isSame(VL))
2101       return TE;
2102     return nullptr;
2103   }
2104 
2105   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2106   /// if any. If it is not vectorized (gather node), returns nullptr.
2107   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2108                                         unsigned OpIdx) const {
2109     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2110         const_cast<TreeEntry *>(UserTE), OpIdx);
2111   }
2112 
2113   /// Checks if all users of \p I are the part of the vectorization tree.
2114   bool areAllUsersVectorized(Instruction *I,
2115                              ArrayRef<Value *> VectorizedVals) const;
2116 
2117   /// \returns the cost of the vectorizable entry.
2118   InstructionCost getEntryCost(const TreeEntry *E,
2119                                ArrayRef<Value *> VectorizedVals);
2120 
2121   /// This is the recursive part of buildTree.
2122   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2123                      const EdgeInfo &EI);
2124 
2125   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2126   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2127   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2128   /// returns false, setting \p CurrentOrder to either an empty vector or a
2129   /// non-identity permutation that allows to reuse extract instructions.
2130   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2131                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2132 
2133   /// Vectorize a single entry in the tree.
2134   Value *vectorizeTree(TreeEntry *E);
2135 
2136   /// Vectorize a single entry in the tree, starting in \p VL.
2137   Value *vectorizeTree(ArrayRef<Value *> VL);
2138 
2139   /// Create a new vector from a list of scalar values.  Produces a sequence
2140   /// which exploits values reused across lanes, and arranges the inserts
2141   /// for ease of later optimization.
2142   Value *createBuildVector(ArrayRef<Value *> VL);
2143 
2144   /// \returns the scalarization cost for this type. Scalarization in this
2145   /// context means the creation of vectors from a group of scalars. If \p
2146   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2147   /// vector elements.
2148   InstructionCost getGatherCost(FixedVectorType *Ty,
2149                                 const APInt &ShuffledIndices,
2150                                 bool NeedToShuffle) const;
2151 
2152   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2153   /// tree entries.
2154   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2155   /// previous tree entries. \p Mask is filled with the shuffle mask.
2156   Optional<TargetTransformInfo::ShuffleKind>
2157   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2158                         SmallVectorImpl<const TreeEntry *> &Entries);
2159 
2160   /// \returns the scalarization cost for this list of values. Assuming that
2161   /// this subtree gets vectorized, we may need to extract the values from the
2162   /// roots. This method calculates the cost of extracting the values.
2163   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2164 
2165   /// Set the Builder insert point to one after the last instruction in
2166   /// the bundle
2167   void setInsertPointAfterBundle(const TreeEntry *E);
2168 
2169   /// \returns a vector from a collection of scalars in \p VL.
2170   Value *gather(ArrayRef<Value *> VL);
2171 
2172   /// \returns whether the VectorizableTree is fully vectorizable and will
2173   /// be beneficial even the tree height is tiny.
2174   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2175 
2176   /// Reorder commutative or alt operands to get better probability of
2177   /// generating vectorized code.
2178   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2179                                              SmallVectorImpl<Value *> &Left,
2180                                              SmallVectorImpl<Value *> &Right,
2181                                              const DataLayout &DL,
2182                                              ScalarEvolution &SE,
2183                                              const BoUpSLP &R);
2184   struct TreeEntry {
2185     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2186     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2187 
2188     /// \returns true if the scalars in VL are equal to this entry.
2189     bool isSame(ArrayRef<Value *> VL) const {
2190       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2191         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2192           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2193         return VL.size() == Mask.size() &&
2194                std::equal(VL.begin(), VL.end(), Mask.begin(),
2195                           [Scalars](Value *V, int Idx) {
2196                             return (isa<UndefValue>(V) &&
2197                                     Idx == UndefMaskElem) ||
2198                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2199                           });
2200       };
2201       if (!ReorderIndices.empty()) {
2202         // TODO: implement matching if the nodes are just reordered, still can
2203         // treat the vector as the same if the list of scalars matches VL
2204         // directly, without reordering.
2205         SmallVector<int> Mask;
2206         inversePermutation(ReorderIndices, Mask);
2207         if (VL.size() == Scalars.size())
2208           return IsSame(Scalars, Mask);
2209         if (VL.size() == ReuseShuffleIndices.size()) {
2210           ::addMask(Mask, ReuseShuffleIndices);
2211           return IsSame(Scalars, Mask);
2212         }
2213         return false;
2214       }
2215       return IsSame(Scalars, ReuseShuffleIndices);
2216     }
2217 
2218     /// \returns true if current entry has same operands as \p TE.
2219     bool hasEqualOperands(const TreeEntry &TE) const {
2220       if (TE.getNumOperands() != getNumOperands())
2221         return false;
2222       SmallBitVector Used(getNumOperands());
2223       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2224         unsigned PrevCount = Used.count();
2225         for (unsigned K = 0; K < E; ++K) {
2226           if (Used.test(K))
2227             continue;
2228           if (getOperand(K) == TE.getOperand(I)) {
2229             Used.set(K);
2230             break;
2231           }
2232         }
2233         // Check if we actually found the matching operand.
2234         if (PrevCount == Used.count())
2235           return false;
2236       }
2237       return true;
2238     }
2239 
2240     /// \return Final vectorization factor for the node. Defined by the total
2241     /// number of vectorized scalars, including those, used several times in the
2242     /// entry and counted in the \a ReuseShuffleIndices, if any.
2243     unsigned getVectorFactor() const {
2244       if (!ReuseShuffleIndices.empty())
2245         return ReuseShuffleIndices.size();
2246       return Scalars.size();
2247     };
2248 
2249     /// A vector of scalars.
2250     ValueList Scalars;
2251 
2252     /// The Scalars are vectorized into this value. It is initialized to Null.
2253     Value *VectorizedValue = nullptr;
2254 
2255     /// Do we need to gather this sequence or vectorize it
2256     /// (either with vector instruction or with scatter/gather
2257     /// intrinsics for store/load)?
2258     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2259     EntryState State;
2260 
2261     /// Does this sequence require some shuffling?
2262     SmallVector<int, 4> ReuseShuffleIndices;
2263 
2264     /// Does this entry require reordering?
2265     SmallVector<unsigned, 4> ReorderIndices;
2266 
2267     /// Points back to the VectorizableTree.
2268     ///
2269     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2270     /// to be a pointer and needs to be able to initialize the child iterator.
2271     /// Thus we need a reference back to the container to translate the indices
2272     /// to entries.
2273     VecTreeTy &Container;
2274 
2275     /// The TreeEntry index containing the user of this entry.  We can actually
2276     /// have multiple users so the data structure is not truly a tree.
2277     SmallVector<EdgeInfo, 1> UserTreeIndices;
2278 
2279     /// The index of this treeEntry in VectorizableTree.
2280     int Idx = -1;
2281 
2282   private:
2283     /// The operands of each instruction in each lane Operands[op_index][lane].
2284     /// Note: This helps avoid the replication of the code that performs the
2285     /// reordering of operands during buildTree_rec() and vectorizeTree().
2286     SmallVector<ValueList, 2> Operands;
2287 
2288     /// The main/alternate instruction.
2289     Instruction *MainOp = nullptr;
2290     Instruction *AltOp = nullptr;
2291 
2292   public:
2293     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2294     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2295       if (Operands.size() < OpIdx + 1)
2296         Operands.resize(OpIdx + 1);
2297       assert(Operands[OpIdx].empty() && "Already resized?");
2298       assert(OpVL.size() <= Scalars.size() &&
2299              "Number of operands is greater than the number of scalars.");
2300       Operands[OpIdx].resize(OpVL.size());
2301       copy(OpVL, Operands[OpIdx].begin());
2302     }
2303 
2304     /// Set the operands of this bundle in their original order.
2305     void setOperandsInOrder() {
2306       assert(Operands.empty() && "Already initialized?");
2307       auto *I0 = cast<Instruction>(Scalars[0]);
2308       Operands.resize(I0->getNumOperands());
2309       unsigned NumLanes = Scalars.size();
2310       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2311            OpIdx != NumOperands; ++OpIdx) {
2312         Operands[OpIdx].resize(NumLanes);
2313         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2314           auto *I = cast<Instruction>(Scalars[Lane]);
2315           assert(I->getNumOperands() == NumOperands &&
2316                  "Expected same number of operands");
2317           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2318         }
2319       }
2320     }
2321 
2322     /// Reorders operands of the node to the given mask \p Mask.
2323     void reorderOperands(ArrayRef<int> Mask) {
2324       for (ValueList &Operand : Operands)
2325         reorderScalars(Operand, Mask);
2326     }
2327 
2328     /// \returns the \p OpIdx operand of this TreeEntry.
2329     ValueList &getOperand(unsigned OpIdx) {
2330       assert(OpIdx < Operands.size() && "Off bounds");
2331       return Operands[OpIdx];
2332     }
2333 
2334     /// \returns the \p OpIdx operand of this TreeEntry.
2335     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2336       assert(OpIdx < Operands.size() && "Off bounds");
2337       return Operands[OpIdx];
2338     }
2339 
2340     /// \returns the number of operands.
2341     unsigned getNumOperands() const { return Operands.size(); }
2342 
2343     /// \return the single \p OpIdx operand.
2344     Value *getSingleOperand(unsigned OpIdx) const {
2345       assert(OpIdx < Operands.size() && "Off bounds");
2346       assert(!Operands[OpIdx].empty() && "No operand available");
2347       return Operands[OpIdx][0];
2348     }
2349 
2350     /// Some of the instructions in the list have alternate opcodes.
2351     bool isAltShuffle() const { return MainOp != AltOp; }
2352 
2353     bool isOpcodeOrAlt(Instruction *I) const {
2354       unsigned CheckedOpcode = I->getOpcode();
2355       return (getOpcode() == CheckedOpcode ||
2356               getAltOpcode() == CheckedOpcode);
2357     }
2358 
2359     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2360     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2361     /// \p OpValue.
2362     Value *isOneOf(Value *Op) const {
2363       auto *I = dyn_cast<Instruction>(Op);
2364       if (I && isOpcodeOrAlt(I))
2365         return Op;
2366       return MainOp;
2367     }
2368 
2369     void setOperations(const InstructionsState &S) {
2370       MainOp = S.MainOp;
2371       AltOp = S.AltOp;
2372     }
2373 
2374     Instruction *getMainOp() const {
2375       return MainOp;
2376     }
2377 
2378     Instruction *getAltOp() const {
2379       return AltOp;
2380     }
2381 
2382     /// The main/alternate opcodes for the list of instructions.
2383     unsigned getOpcode() const {
2384       return MainOp ? MainOp->getOpcode() : 0;
2385     }
2386 
2387     unsigned getAltOpcode() const {
2388       return AltOp ? AltOp->getOpcode() : 0;
2389     }
2390 
2391     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2392     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2393     int findLaneForValue(Value *V) const {
2394       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2395       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2396       if (!ReorderIndices.empty())
2397         FoundLane = ReorderIndices[FoundLane];
2398       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2399       if (!ReuseShuffleIndices.empty()) {
2400         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2401                                   find(ReuseShuffleIndices, FoundLane));
2402       }
2403       return FoundLane;
2404     }
2405 
2406 #ifndef NDEBUG
2407     /// Debug printer.
2408     LLVM_DUMP_METHOD void dump() const {
2409       dbgs() << Idx << ".\n";
2410       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2411         dbgs() << "Operand " << OpI << ":\n";
2412         for (const Value *V : Operands[OpI])
2413           dbgs().indent(2) << *V << "\n";
2414       }
2415       dbgs() << "Scalars: \n";
2416       for (Value *V : Scalars)
2417         dbgs().indent(2) << *V << "\n";
2418       dbgs() << "State: ";
2419       switch (State) {
2420       case Vectorize:
2421         dbgs() << "Vectorize\n";
2422         break;
2423       case ScatterVectorize:
2424         dbgs() << "ScatterVectorize\n";
2425         break;
2426       case NeedToGather:
2427         dbgs() << "NeedToGather\n";
2428         break;
2429       }
2430       dbgs() << "MainOp: ";
2431       if (MainOp)
2432         dbgs() << *MainOp << "\n";
2433       else
2434         dbgs() << "NULL\n";
2435       dbgs() << "AltOp: ";
2436       if (AltOp)
2437         dbgs() << *AltOp << "\n";
2438       else
2439         dbgs() << "NULL\n";
2440       dbgs() << "VectorizedValue: ";
2441       if (VectorizedValue)
2442         dbgs() << *VectorizedValue << "\n";
2443       else
2444         dbgs() << "NULL\n";
2445       dbgs() << "ReuseShuffleIndices: ";
2446       if (ReuseShuffleIndices.empty())
2447         dbgs() << "Empty";
2448       else
2449         for (int ReuseIdx : ReuseShuffleIndices)
2450           dbgs() << ReuseIdx << ", ";
2451       dbgs() << "\n";
2452       dbgs() << "ReorderIndices: ";
2453       for (unsigned ReorderIdx : ReorderIndices)
2454         dbgs() << ReorderIdx << ", ";
2455       dbgs() << "\n";
2456       dbgs() << "UserTreeIndices: ";
2457       for (const auto &EInfo : UserTreeIndices)
2458         dbgs() << EInfo << ", ";
2459       dbgs() << "\n";
2460     }
2461 #endif
2462   };
2463 
2464 #ifndef NDEBUG
2465   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2466                      InstructionCost VecCost,
2467                      InstructionCost ScalarCost) const {
2468     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2469     dbgs() << "SLP: Costs:\n";
2470     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2471     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2472     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2473     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2474                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2475   }
2476 #endif
2477 
2478   /// Create a new VectorizableTree entry.
2479   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2480                           const InstructionsState &S,
2481                           const EdgeInfo &UserTreeIdx,
2482                           ArrayRef<int> ReuseShuffleIndices = None,
2483                           ArrayRef<unsigned> ReorderIndices = None) {
2484     TreeEntry::EntryState EntryState =
2485         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2486     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2487                         ReuseShuffleIndices, ReorderIndices);
2488   }
2489 
2490   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2491                           TreeEntry::EntryState EntryState,
2492                           Optional<ScheduleData *> Bundle,
2493                           const InstructionsState &S,
2494                           const EdgeInfo &UserTreeIdx,
2495                           ArrayRef<int> ReuseShuffleIndices = None,
2496                           ArrayRef<unsigned> ReorderIndices = None) {
2497     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2498             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2499            "Need to vectorize gather entry?");
2500     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2501     TreeEntry *Last = VectorizableTree.back().get();
2502     Last->Idx = VectorizableTree.size() - 1;
2503     Last->State = EntryState;
2504     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2505                                      ReuseShuffleIndices.end());
2506     if (ReorderIndices.empty()) {
2507       Last->Scalars.assign(VL.begin(), VL.end());
2508       Last->setOperations(S);
2509     } else {
2510       // Reorder scalars and build final mask.
2511       Last->Scalars.assign(VL.size(), nullptr);
2512       transform(ReorderIndices, Last->Scalars.begin(),
2513                 [VL](unsigned Idx) -> Value * {
2514                   if (Idx >= VL.size())
2515                     return UndefValue::get(VL.front()->getType());
2516                   return VL[Idx];
2517                 });
2518       InstructionsState S = getSameOpcode(Last->Scalars);
2519       Last->setOperations(S);
2520       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2521     }
2522     if (Last->State != TreeEntry::NeedToGather) {
2523       for (Value *V : VL) {
2524         assert(!getTreeEntry(V) && "Scalar already in tree!");
2525         ScalarToTreeEntry[V] = Last;
2526       }
2527       // Update the scheduler bundle to point to this TreeEntry.
2528       ScheduleData *BundleMember = Bundle.getValue();
2529       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2530               isVectorLikeInstWithConstOps(S.MainOp) ||
2531               doesNotNeedToSchedule(VL)) &&
2532              "Bundle and VL out of sync");
2533       if (BundleMember) {
2534         for (Value *V : VL) {
2535           if (doesNotNeedToBeScheduled(V))
2536             continue;
2537           assert(BundleMember && "Unexpected end of bundle.");
2538           BundleMember->TE = Last;
2539           BundleMember = BundleMember->NextInBundle;
2540         }
2541       }
2542       assert(!BundleMember && "Bundle and VL out of sync");
2543     } else {
2544       MustGather.insert(VL.begin(), VL.end());
2545     }
2546 
2547     if (UserTreeIdx.UserTE)
2548       Last->UserTreeIndices.push_back(UserTreeIdx);
2549 
2550     return Last;
2551   }
2552 
2553   /// -- Vectorization State --
2554   /// Holds all of the tree entries.
2555   TreeEntry::VecTreeTy VectorizableTree;
2556 
2557 #ifndef NDEBUG
2558   /// Debug printer.
2559   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2560     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2561       VectorizableTree[Id]->dump();
2562       dbgs() << "\n";
2563     }
2564   }
2565 #endif
2566 
2567   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2568 
2569   const TreeEntry *getTreeEntry(Value *V) const {
2570     return ScalarToTreeEntry.lookup(V);
2571   }
2572 
2573   /// Maps a specific scalar to its tree entry.
2574   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2575 
2576   /// Maps a value to the proposed vectorizable size.
2577   SmallDenseMap<Value *, unsigned> InstrElementSize;
2578 
2579   /// A list of scalars that we found that we need to keep as scalars.
2580   ValueSet MustGather;
2581 
2582   /// This POD struct describes one external user in the vectorized tree.
2583   struct ExternalUser {
2584     ExternalUser(Value *S, llvm::User *U, int L)
2585         : Scalar(S), User(U), Lane(L) {}
2586 
2587     // Which scalar in our function.
2588     Value *Scalar;
2589 
2590     // Which user that uses the scalar.
2591     llvm::User *User;
2592 
2593     // Which lane does the scalar belong to.
2594     int Lane;
2595   };
2596   using UserList = SmallVector<ExternalUser, 16>;
2597 
2598   /// Checks if two instructions may access the same memory.
2599   ///
2600   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2601   /// is invariant in the calling loop.
2602   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2603                  Instruction *Inst2) {
2604     // First check if the result is already in the cache.
2605     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2606     Optional<bool> &result = AliasCache[key];
2607     if (result.hasValue()) {
2608       return result.getValue();
2609     }
2610     bool aliased = true;
2611     if (Loc1.Ptr && isSimple(Inst1))
2612       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2613     // Store the result in the cache.
2614     result = aliased;
2615     return aliased;
2616   }
2617 
2618   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2619 
2620   /// Cache for alias results.
2621   /// TODO: consider moving this to the AliasAnalysis itself.
2622   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2623 
2624   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2625   // globally through SLP because we don't perform any action which
2626   // invalidates capture results.
2627   BatchAAResults BatchAA;
2628 
2629   /// Temporary store for deleted instructions. Instructions will be deleted
2630   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2631   /// ensure that there are no incorrect collisions in the AliasCache, which
2632   /// can happen if a new instruction is allocated at the same address as a
2633   /// previously deleted instruction.
2634   DenseSet<Instruction *> DeletedInstructions;
2635 
2636   /// Set of the instruction, being analyzed already for reductions.
2637   SmallPtrSet<Instruction *, 16> AnalizedReductionsRoots;
2638 
2639   /// Set of hashes for the list of reduction values already being analyzed.
2640   DenseSet<size_t> AnalyzedReductionVals;
2641 
2642   /// A list of values that need to extracted out of the tree.
2643   /// This list holds pairs of (Internal Scalar : External User). External User
2644   /// can be nullptr, it means that this Internal Scalar will be used later,
2645   /// after vectorization.
2646   UserList ExternalUses;
2647 
2648   /// Values used only by @llvm.assume calls.
2649   SmallPtrSet<const Value *, 32> EphValues;
2650 
2651   /// Holds all of the instructions that we gathered.
2652   SetVector<Instruction *> GatherShuffleSeq;
2653 
2654   /// A list of blocks that we are going to CSE.
2655   SetVector<BasicBlock *> CSEBlocks;
2656 
2657   /// Contains all scheduling relevant data for an instruction.
2658   /// A ScheduleData either represents a single instruction or a member of an
2659   /// instruction bundle (= a group of instructions which is combined into a
2660   /// vector instruction).
2661   struct ScheduleData {
2662     // The initial value for the dependency counters. It means that the
2663     // dependencies are not calculated yet.
2664     enum { InvalidDeps = -1 };
2665 
2666     ScheduleData() = default;
2667 
2668     void init(int BlockSchedulingRegionID, Value *OpVal) {
2669       FirstInBundle = this;
2670       NextInBundle = nullptr;
2671       NextLoadStore = nullptr;
2672       IsScheduled = false;
2673       SchedulingRegionID = BlockSchedulingRegionID;
2674       clearDependencies();
2675       OpValue = OpVal;
2676       TE = nullptr;
2677     }
2678 
2679     /// Verify basic self consistency properties
2680     void verify() {
2681       if (hasValidDependencies()) {
2682         assert(UnscheduledDeps <= Dependencies && "invariant");
2683       } else {
2684         assert(UnscheduledDeps == Dependencies && "invariant");
2685       }
2686 
2687       if (IsScheduled) {
2688         assert(isSchedulingEntity() &&
2689                 "unexpected scheduled state");
2690         for (const ScheduleData *BundleMember = this; BundleMember;
2691              BundleMember = BundleMember->NextInBundle) {
2692           assert(BundleMember->hasValidDependencies() &&
2693                  BundleMember->UnscheduledDeps == 0 &&
2694                  "unexpected scheduled state");
2695           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2696                  "only bundle is marked scheduled");
2697         }
2698       }
2699 
2700       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2701              "all bundle members must be in same basic block");
2702     }
2703 
2704     /// Returns true if the dependency information has been calculated.
2705     /// Note that depenendency validity can vary between instructions within
2706     /// a single bundle.
2707     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2708 
2709     /// Returns true for single instructions and for bundle representatives
2710     /// (= the head of a bundle).
2711     bool isSchedulingEntity() const { return FirstInBundle == this; }
2712 
2713     /// Returns true if it represents an instruction bundle and not only a
2714     /// single instruction.
2715     bool isPartOfBundle() const {
2716       return NextInBundle != nullptr || FirstInBundle != this || TE;
2717     }
2718 
2719     /// Returns true if it is ready for scheduling, i.e. it has no more
2720     /// unscheduled depending instructions/bundles.
2721     bool isReady() const {
2722       assert(isSchedulingEntity() &&
2723              "can't consider non-scheduling entity for ready list");
2724       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2725     }
2726 
2727     /// Modifies the number of unscheduled dependencies for this instruction,
2728     /// and returns the number of remaining dependencies for the containing
2729     /// bundle.
2730     int incrementUnscheduledDeps(int Incr) {
2731       assert(hasValidDependencies() &&
2732              "increment of unscheduled deps would be meaningless");
2733       UnscheduledDeps += Incr;
2734       return FirstInBundle->unscheduledDepsInBundle();
2735     }
2736 
2737     /// Sets the number of unscheduled dependencies to the number of
2738     /// dependencies.
2739     void resetUnscheduledDeps() {
2740       UnscheduledDeps = Dependencies;
2741     }
2742 
2743     /// Clears all dependency information.
2744     void clearDependencies() {
2745       Dependencies = InvalidDeps;
2746       resetUnscheduledDeps();
2747       MemoryDependencies.clear();
2748       ControlDependencies.clear();
2749     }
2750 
2751     int unscheduledDepsInBundle() const {
2752       assert(isSchedulingEntity() && "only meaningful on the bundle");
2753       int Sum = 0;
2754       for (const ScheduleData *BundleMember = this; BundleMember;
2755            BundleMember = BundleMember->NextInBundle) {
2756         if (BundleMember->UnscheduledDeps == InvalidDeps)
2757           return InvalidDeps;
2758         Sum += BundleMember->UnscheduledDeps;
2759       }
2760       return Sum;
2761     }
2762 
2763     void dump(raw_ostream &os) const {
2764       if (!isSchedulingEntity()) {
2765         os << "/ " << *Inst;
2766       } else if (NextInBundle) {
2767         os << '[' << *Inst;
2768         ScheduleData *SD = NextInBundle;
2769         while (SD) {
2770           os << ';' << *SD->Inst;
2771           SD = SD->NextInBundle;
2772         }
2773         os << ']';
2774       } else {
2775         os << *Inst;
2776       }
2777     }
2778 
2779     Instruction *Inst = nullptr;
2780 
2781     /// Opcode of the current instruction in the schedule data.
2782     Value *OpValue = nullptr;
2783 
2784     /// The TreeEntry that this instruction corresponds to.
2785     TreeEntry *TE = nullptr;
2786 
2787     /// Points to the head in an instruction bundle (and always to this for
2788     /// single instructions).
2789     ScheduleData *FirstInBundle = nullptr;
2790 
2791     /// Single linked list of all instructions in a bundle. Null if it is a
2792     /// single instruction.
2793     ScheduleData *NextInBundle = nullptr;
2794 
2795     /// Single linked list of all memory instructions (e.g. load, store, call)
2796     /// in the block - until the end of the scheduling region.
2797     ScheduleData *NextLoadStore = nullptr;
2798 
2799     /// The dependent memory instructions.
2800     /// This list is derived on demand in calculateDependencies().
2801     SmallVector<ScheduleData *, 4> MemoryDependencies;
2802 
2803     /// List of instructions which this instruction could be control dependent
2804     /// on.  Allowing such nodes to be scheduled below this one could introduce
2805     /// a runtime fault which didn't exist in the original program.
2806     /// ex: this is a load or udiv following a readonly call which inf loops
2807     SmallVector<ScheduleData *, 4> ControlDependencies;
2808 
2809     /// This ScheduleData is in the current scheduling region if this matches
2810     /// the current SchedulingRegionID of BlockScheduling.
2811     int SchedulingRegionID = 0;
2812 
2813     /// Used for getting a "good" final ordering of instructions.
2814     int SchedulingPriority = 0;
2815 
2816     /// The number of dependencies. Constitutes of the number of users of the
2817     /// instruction plus the number of dependent memory instructions (if any).
2818     /// This value is calculated on demand.
2819     /// If InvalidDeps, the number of dependencies is not calculated yet.
2820     int Dependencies = InvalidDeps;
2821 
2822     /// The number of dependencies minus the number of dependencies of scheduled
2823     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2824     /// for scheduling.
2825     /// Note that this is negative as long as Dependencies is not calculated.
2826     int UnscheduledDeps = InvalidDeps;
2827 
2828     /// True if this instruction is scheduled (or considered as scheduled in the
2829     /// dry-run).
2830     bool IsScheduled = false;
2831   };
2832 
2833 #ifndef NDEBUG
2834   friend inline raw_ostream &operator<<(raw_ostream &os,
2835                                         const BoUpSLP::ScheduleData &SD) {
2836     SD.dump(os);
2837     return os;
2838   }
2839 #endif
2840 
2841   friend struct GraphTraits<BoUpSLP *>;
2842   friend struct DOTGraphTraits<BoUpSLP *>;
2843 
2844   /// Contains all scheduling data for a basic block.
2845   /// It does not schedules instructions, which are not memory read/write
2846   /// instructions and their operands are either constants, or arguments, or
2847   /// phis, or instructions from others blocks, or their users are phis or from
2848   /// the other blocks. The resulting vector instructions can be placed at the
2849   /// beginning of the basic block without scheduling (if operands does not need
2850   /// to be scheduled) or at the end of the block (if users are outside of the
2851   /// block). It allows to save some compile time and memory used by the
2852   /// compiler.
2853   /// ScheduleData is assigned for each instruction in between the boundaries of
2854   /// the tree entry, even for those, which are not part of the graph. It is
2855   /// required to correctly follow the dependencies between the instructions and
2856   /// their correct scheduling. The ScheduleData is not allocated for the
2857   /// instructions, which do not require scheduling, like phis, nodes with
2858   /// extractelements/insertelements only or nodes with instructions, with
2859   /// uses/operands outside of the block.
2860   struct BlockScheduling {
2861     BlockScheduling(BasicBlock *BB)
2862         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2863 
2864     void clear() {
2865       ReadyInsts.clear();
2866       ScheduleStart = nullptr;
2867       ScheduleEnd = nullptr;
2868       FirstLoadStoreInRegion = nullptr;
2869       LastLoadStoreInRegion = nullptr;
2870       RegionHasStackSave = false;
2871 
2872       // Reduce the maximum schedule region size by the size of the
2873       // previous scheduling run.
2874       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2875       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2876         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2877       ScheduleRegionSize = 0;
2878 
2879       // Make a new scheduling region, i.e. all existing ScheduleData is not
2880       // in the new region yet.
2881       ++SchedulingRegionID;
2882     }
2883 
2884     ScheduleData *getScheduleData(Instruction *I) {
2885       if (BB != I->getParent())
2886         // Avoid lookup if can't possibly be in map.
2887         return nullptr;
2888       ScheduleData *SD = ScheduleDataMap.lookup(I);
2889       if (SD && isInSchedulingRegion(SD))
2890         return SD;
2891       return nullptr;
2892     }
2893 
2894     ScheduleData *getScheduleData(Value *V) {
2895       if (auto *I = dyn_cast<Instruction>(V))
2896         return getScheduleData(I);
2897       return nullptr;
2898     }
2899 
2900     ScheduleData *getScheduleData(Value *V, Value *Key) {
2901       if (V == Key)
2902         return getScheduleData(V);
2903       auto I = ExtraScheduleDataMap.find(V);
2904       if (I != ExtraScheduleDataMap.end()) {
2905         ScheduleData *SD = I->second.lookup(Key);
2906         if (SD && isInSchedulingRegion(SD))
2907           return SD;
2908       }
2909       return nullptr;
2910     }
2911 
2912     bool isInSchedulingRegion(ScheduleData *SD) const {
2913       return SD->SchedulingRegionID == SchedulingRegionID;
2914     }
2915 
2916     /// Marks an instruction as scheduled and puts all dependent ready
2917     /// instructions into the ready-list.
2918     template <typename ReadyListType>
2919     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2920       SD->IsScheduled = true;
2921       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2922 
2923       for (ScheduleData *BundleMember = SD; BundleMember;
2924            BundleMember = BundleMember->NextInBundle) {
2925         if (BundleMember->Inst != BundleMember->OpValue)
2926           continue;
2927 
2928         // Handle the def-use chain dependencies.
2929 
2930         // Decrement the unscheduled counter and insert to ready list if ready.
2931         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2932           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2933             if (OpDef && OpDef->hasValidDependencies() &&
2934                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2935               // There are no more unscheduled dependencies after
2936               // decrementing, so we can put the dependent instruction
2937               // into the ready list.
2938               ScheduleData *DepBundle = OpDef->FirstInBundle;
2939               assert(!DepBundle->IsScheduled &&
2940                      "already scheduled bundle gets ready");
2941               ReadyList.insert(DepBundle);
2942               LLVM_DEBUG(dbgs()
2943                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2944             }
2945           });
2946         };
2947 
2948         // If BundleMember is a vector bundle, its operands may have been
2949         // reordered during buildTree(). We therefore need to get its operands
2950         // through the TreeEntry.
2951         if (TreeEntry *TE = BundleMember->TE) {
2952           // Need to search for the lane since the tree entry can be reordered.
2953           int Lane = std::distance(TE->Scalars.begin(),
2954                                    find(TE->Scalars, BundleMember->Inst));
2955           assert(Lane >= 0 && "Lane not set");
2956 
2957           // Since vectorization tree is being built recursively this assertion
2958           // ensures that the tree entry has all operands set before reaching
2959           // this code. Couple of exceptions known at the moment are extracts
2960           // where their second (immediate) operand is not added. Since
2961           // immediates do not affect scheduler behavior this is considered
2962           // okay.
2963           auto *In = BundleMember->Inst;
2964           assert(In &&
2965                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2966                   In->getNumOperands() == TE->getNumOperands()) &&
2967                  "Missed TreeEntry operands?");
2968           (void)In; // fake use to avoid build failure when assertions disabled
2969 
2970           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2971                OpIdx != NumOperands; ++OpIdx)
2972             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2973               DecrUnsched(I);
2974         } else {
2975           // If BundleMember is a stand-alone instruction, no operand reordering
2976           // has taken place, so we directly access its operands.
2977           for (Use &U : BundleMember->Inst->operands())
2978             if (auto *I = dyn_cast<Instruction>(U.get()))
2979               DecrUnsched(I);
2980         }
2981         // Handle the memory dependencies.
2982         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2983           if (MemoryDepSD->hasValidDependencies() &&
2984               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2985             // There are no more unscheduled dependencies after decrementing,
2986             // so we can put the dependent instruction into the ready list.
2987             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2988             assert(!DepBundle->IsScheduled &&
2989                    "already scheduled bundle gets ready");
2990             ReadyList.insert(DepBundle);
2991             LLVM_DEBUG(dbgs()
2992                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2993           }
2994         }
2995         // Handle the control dependencies.
2996         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2997           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2998             // There are no more unscheduled dependencies after decrementing,
2999             // so we can put the dependent instruction into the ready list.
3000             ScheduleData *DepBundle = DepSD->FirstInBundle;
3001             assert(!DepBundle->IsScheduled &&
3002                    "already scheduled bundle gets ready");
3003             ReadyList.insert(DepBundle);
3004             LLVM_DEBUG(dbgs()
3005                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
3006           }
3007         }
3008 
3009       }
3010     }
3011 
3012     /// Verify basic self consistency properties of the data structure.
3013     void verify() {
3014       if (!ScheduleStart)
3015         return;
3016 
3017       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3018              ScheduleStart->comesBefore(ScheduleEnd) &&
3019              "Not a valid scheduling region?");
3020 
3021       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3022         auto *SD = getScheduleData(I);
3023         if (!SD)
3024           continue;
3025         assert(isInSchedulingRegion(SD) &&
3026                "primary schedule data not in window?");
3027         assert(isInSchedulingRegion(SD->FirstInBundle) &&
3028                "entire bundle in window!");
3029         (void)SD;
3030         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3031       }
3032 
3033       for (auto *SD : ReadyInsts) {
3034         assert(SD->isSchedulingEntity() && SD->isReady() &&
3035                "item in ready list not ready?");
3036         (void)SD;
3037       }
3038     }
3039 
3040     void doForAllOpcodes(Value *V,
3041                          function_ref<void(ScheduleData *SD)> Action) {
3042       if (ScheduleData *SD = getScheduleData(V))
3043         Action(SD);
3044       auto I = ExtraScheduleDataMap.find(V);
3045       if (I != ExtraScheduleDataMap.end())
3046         for (auto &P : I->second)
3047           if (isInSchedulingRegion(P.second))
3048             Action(P.second);
3049     }
3050 
3051     /// Put all instructions into the ReadyList which are ready for scheduling.
3052     template <typename ReadyListType>
3053     void initialFillReadyList(ReadyListType &ReadyList) {
3054       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3055         doForAllOpcodes(I, [&](ScheduleData *SD) {
3056           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3057               SD->isReady()) {
3058             ReadyList.insert(SD);
3059             LLVM_DEBUG(dbgs()
3060                        << "SLP:    initially in ready list: " << *SD << "\n");
3061           }
3062         });
3063       }
3064     }
3065 
3066     /// Build a bundle from the ScheduleData nodes corresponding to the
3067     /// scalar instruction for each lane.
3068     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3069 
3070     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3071     /// cyclic dependencies. This is only a dry-run, no instructions are
3072     /// actually moved at this stage.
3073     /// \returns the scheduling bundle. The returned Optional value is non-None
3074     /// if \p VL is allowed to be scheduled.
3075     Optional<ScheduleData *>
3076     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3077                       const InstructionsState &S);
3078 
3079     /// Un-bundles a group of instructions.
3080     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3081 
3082     /// Allocates schedule data chunk.
3083     ScheduleData *allocateScheduleDataChunks();
3084 
3085     /// Extends the scheduling region so that V is inside the region.
3086     /// \returns true if the region size is within the limit.
3087     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3088 
3089     /// Initialize the ScheduleData structures for new instructions in the
3090     /// scheduling region.
3091     void initScheduleData(Instruction *FromI, Instruction *ToI,
3092                           ScheduleData *PrevLoadStore,
3093                           ScheduleData *NextLoadStore);
3094 
3095     /// Updates the dependency information of a bundle and of all instructions/
3096     /// bundles which depend on the original bundle.
3097     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3098                                BoUpSLP *SLP);
3099 
3100     /// Sets all instruction in the scheduling region to un-scheduled.
3101     void resetSchedule();
3102 
3103     BasicBlock *BB;
3104 
3105     /// Simple memory allocation for ScheduleData.
3106     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3107 
3108     /// The size of a ScheduleData array in ScheduleDataChunks.
3109     int ChunkSize;
3110 
3111     /// The allocator position in the current chunk, which is the last entry
3112     /// of ScheduleDataChunks.
3113     int ChunkPos;
3114 
3115     /// Attaches ScheduleData to Instruction.
3116     /// Note that the mapping survives during all vectorization iterations, i.e.
3117     /// ScheduleData structures are recycled.
3118     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3119 
3120     /// Attaches ScheduleData to Instruction with the leading key.
3121     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3122         ExtraScheduleDataMap;
3123 
3124     /// The ready-list for scheduling (only used for the dry-run).
3125     SetVector<ScheduleData *> ReadyInsts;
3126 
3127     /// The first instruction of the scheduling region.
3128     Instruction *ScheduleStart = nullptr;
3129 
3130     /// The first instruction _after_ the scheduling region.
3131     Instruction *ScheduleEnd = nullptr;
3132 
3133     /// The first memory accessing instruction in the scheduling region
3134     /// (can be null).
3135     ScheduleData *FirstLoadStoreInRegion = nullptr;
3136 
3137     /// The last memory accessing instruction in the scheduling region
3138     /// (can be null).
3139     ScheduleData *LastLoadStoreInRegion = nullptr;
3140 
3141     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3142     /// region?  Used to optimize the dependence calculation for the
3143     /// common case where there isn't.
3144     bool RegionHasStackSave = false;
3145 
3146     /// The current size of the scheduling region.
3147     int ScheduleRegionSize = 0;
3148 
3149     /// The maximum size allowed for the scheduling region.
3150     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3151 
3152     /// The ID of the scheduling region. For a new vectorization iteration this
3153     /// is incremented which "removes" all ScheduleData from the region.
3154     /// Make sure that the initial SchedulingRegionID is greater than the
3155     /// initial SchedulingRegionID in ScheduleData (which is 0).
3156     int SchedulingRegionID = 1;
3157   };
3158 
3159   /// Attaches the BlockScheduling structures to basic blocks.
3160   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3161 
3162   /// Performs the "real" scheduling. Done before vectorization is actually
3163   /// performed in a basic block.
3164   void scheduleBlock(BlockScheduling *BS);
3165 
3166   /// List of users to ignore during scheduling and that don't need extracting.
3167   ArrayRef<Value *> UserIgnoreList;
3168 
3169   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3170   /// sorted SmallVectors of unsigned.
3171   struct OrdersTypeDenseMapInfo {
3172     static OrdersType getEmptyKey() {
3173       OrdersType V;
3174       V.push_back(~1U);
3175       return V;
3176     }
3177 
3178     static OrdersType getTombstoneKey() {
3179       OrdersType V;
3180       V.push_back(~2U);
3181       return V;
3182     }
3183 
3184     static unsigned getHashValue(const OrdersType &V) {
3185       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3186     }
3187 
3188     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3189       return LHS == RHS;
3190     }
3191   };
3192 
3193   // Analysis and block reference.
3194   Function *F;
3195   ScalarEvolution *SE;
3196   TargetTransformInfo *TTI;
3197   TargetLibraryInfo *TLI;
3198   LoopInfo *LI;
3199   DominatorTree *DT;
3200   AssumptionCache *AC;
3201   DemandedBits *DB;
3202   const DataLayout *DL;
3203   OptimizationRemarkEmitter *ORE;
3204 
3205   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3206   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3207 
3208   /// Instruction builder to construct the vectorized tree.
3209   IRBuilder<> Builder;
3210 
3211   /// A map of scalar integer values to the smallest bit width with which they
3212   /// can legally be represented. The values map to (width, signed) pairs,
3213   /// where "width" indicates the minimum bit width and "signed" is True if the
3214   /// value must be signed-extended, rather than zero-extended, back to its
3215   /// original width.
3216   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3217 };
3218 
3219 } // end namespace slpvectorizer
3220 
3221 template <> struct GraphTraits<BoUpSLP *> {
3222   using TreeEntry = BoUpSLP::TreeEntry;
3223 
3224   /// NodeRef has to be a pointer per the GraphWriter.
3225   using NodeRef = TreeEntry *;
3226 
3227   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3228 
3229   /// Add the VectorizableTree to the index iterator to be able to return
3230   /// TreeEntry pointers.
3231   struct ChildIteratorType
3232       : public iterator_adaptor_base<
3233             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3234     ContainerTy &VectorizableTree;
3235 
3236     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3237                       ContainerTy &VT)
3238         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3239 
3240     NodeRef operator*() { return I->UserTE; }
3241   };
3242 
3243   static NodeRef getEntryNode(BoUpSLP &R) {
3244     return R.VectorizableTree[0].get();
3245   }
3246 
3247   static ChildIteratorType child_begin(NodeRef N) {
3248     return {N->UserTreeIndices.begin(), N->Container};
3249   }
3250 
3251   static ChildIteratorType child_end(NodeRef N) {
3252     return {N->UserTreeIndices.end(), N->Container};
3253   }
3254 
3255   /// For the node iterator we just need to turn the TreeEntry iterator into a
3256   /// TreeEntry* iterator so that it dereferences to NodeRef.
3257   class nodes_iterator {
3258     using ItTy = ContainerTy::iterator;
3259     ItTy It;
3260 
3261   public:
3262     nodes_iterator(const ItTy &It2) : It(It2) {}
3263     NodeRef operator*() { return It->get(); }
3264     nodes_iterator operator++() {
3265       ++It;
3266       return *this;
3267     }
3268     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3269   };
3270 
3271   static nodes_iterator nodes_begin(BoUpSLP *R) {
3272     return nodes_iterator(R->VectorizableTree.begin());
3273   }
3274 
3275   static nodes_iterator nodes_end(BoUpSLP *R) {
3276     return nodes_iterator(R->VectorizableTree.end());
3277   }
3278 
3279   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3280 };
3281 
3282 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3283   using TreeEntry = BoUpSLP::TreeEntry;
3284 
3285   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3286 
3287   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3288     std::string Str;
3289     raw_string_ostream OS(Str);
3290     if (isSplat(Entry->Scalars))
3291       OS << "<splat> ";
3292     for (auto V : Entry->Scalars) {
3293       OS << *V;
3294       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3295             return EU.Scalar == V;
3296           }))
3297         OS << " <extract>";
3298       OS << "\n";
3299     }
3300     return Str;
3301   }
3302 
3303   static std::string getNodeAttributes(const TreeEntry *Entry,
3304                                        const BoUpSLP *) {
3305     if (Entry->State == TreeEntry::NeedToGather)
3306       return "color=red";
3307     return "";
3308   }
3309 };
3310 
3311 } // end namespace llvm
3312 
3313 BoUpSLP::~BoUpSLP() {
3314   SmallVector<WeakTrackingVH> DeadInsts;
3315   for (auto *I : DeletedInstructions) {
3316     for (Use &U : I->operands()) {
3317       auto *Op = dyn_cast<Instruction>(U.get());
3318       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3319           wouldInstructionBeTriviallyDead(Op, TLI))
3320         DeadInsts.emplace_back(Op);
3321     }
3322     I->dropAllReferences();
3323   }
3324   for (auto *I : DeletedInstructions) {
3325     assert(I->use_empty() &&
3326            "trying to erase instruction with users.");
3327     I->eraseFromParent();
3328   }
3329 
3330   // Cleanup any dead scalar code feeding the vectorized instructions
3331   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3332 
3333 #ifdef EXPENSIVE_CHECKS
3334   // If we could guarantee that this call is not extremely slow, we could
3335   // remove the ifdef limitation (see PR47712).
3336   assert(!verifyFunction(*F, &dbgs()));
3337 #endif
3338 }
3339 
3340 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3341 /// contains original mask for the scalars reused in the node. Procedure
3342 /// transform this mask in accordance with the given \p Mask.
3343 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3344   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3345          "Expected non-empty mask.");
3346   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3347   Prev.swap(Reuses);
3348   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3349     if (Mask[I] != UndefMaskElem)
3350       Reuses[Mask[I]] = Prev[I];
3351 }
3352 
3353 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3354 /// the original order of the scalars. Procedure transforms the provided order
3355 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3356 /// identity order, \p Order is cleared.
3357 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3358   assert(!Mask.empty() && "Expected non-empty mask.");
3359   SmallVector<int> MaskOrder;
3360   if (Order.empty()) {
3361     MaskOrder.resize(Mask.size());
3362     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3363   } else {
3364     inversePermutation(Order, MaskOrder);
3365   }
3366   reorderReuses(MaskOrder, Mask);
3367   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3368     Order.clear();
3369     return;
3370   }
3371   Order.assign(Mask.size(), Mask.size());
3372   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3373     if (MaskOrder[I] != UndefMaskElem)
3374       Order[MaskOrder[I]] = I;
3375   fixupOrderingIndices(Order);
3376 }
3377 
3378 Optional<BoUpSLP::OrdersType>
3379 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3380   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3381   unsigned NumScalars = TE.Scalars.size();
3382   OrdersType CurrentOrder(NumScalars, NumScalars);
3383   SmallVector<int> Positions;
3384   SmallBitVector UsedPositions(NumScalars);
3385   const TreeEntry *STE = nullptr;
3386   // Try to find all gathered scalars that are gets vectorized in other
3387   // vectorize node. Here we can have only one single tree vector node to
3388   // correctly identify order of the gathered scalars.
3389   for (unsigned I = 0; I < NumScalars; ++I) {
3390     Value *V = TE.Scalars[I];
3391     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3392       continue;
3393     if (const auto *LocalSTE = getTreeEntry(V)) {
3394       if (!STE)
3395         STE = LocalSTE;
3396       else if (STE != LocalSTE)
3397         // Take the order only from the single vector node.
3398         return None;
3399       unsigned Lane =
3400           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3401       if (Lane >= NumScalars)
3402         return None;
3403       if (CurrentOrder[Lane] != NumScalars) {
3404         if (Lane != I)
3405           continue;
3406         UsedPositions.reset(CurrentOrder[Lane]);
3407       }
3408       // The partial identity (where only some elements of the gather node are
3409       // in the identity order) is good.
3410       CurrentOrder[Lane] = I;
3411       UsedPositions.set(I);
3412     }
3413   }
3414   // Need to keep the order if we have a vector entry and at least 2 scalars or
3415   // the vectorized entry has just 2 scalars.
3416   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3417     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3418       for (unsigned I = 0; I < NumScalars; ++I)
3419         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3420           return false;
3421       return true;
3422     };
3423     if (IsIdentityOrder(CurrentOrder)) {
3424       CurrentOrder.clear();
3425       return CurrentOrder;
3426     }
3427     auto *It = CurrentOrder.begin();
3428     for (unsigned I = 0; I < NumScalars;) {
3429       if (UsedPositions.test(I)) {
3430         ++I;
3431         continue;
3432       }
3433       if (*It == NumScalars) {
3434         *It = I;
3435         ++I;
3436       }
3437       ++It;
3438     }
3439     return CurrentOrder;
3440   }
3441   return None;
3442 }
3443 
3444 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3445                                                          bool TopToBottom) {
3446   // No need to reorder if need to shuffle reuses, still need to shuffle the
3447   // node.
3448   if (!TE.ReuseShuffleIndices.empty())
3449     return None;
3450   if (TE.State == TreeEntry::Vectorize &&
3451       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3452        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3453       !TE.isAltShuffle())
3454     return TE.ReorderIndices;
3455   if (TE.State == TreeEntry::NeedToGather) {
3456     // TODO: add analysis of other gather nodes with extractelement
3457     // instructions and other values/instructions, not only undefs.
3458     if (((TE.getOpcode() == Instruction::ExtractElement &&
3459           !TE.isAltShuffle()) ||
3460          (all_of(TE.Scalars,
3461                  [](Value *V) {
3462                    return isa<UndefValue, ExtractElementInst>(V);
3463                  }) &&
3464           any_of(TE.Scalars,
3465                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3466         all_of(TE.Scalars,
3467                [](Value *V) {
3468                  auto *EE = dyn_cast<ExtractElementInst>(V);
3469                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3470                }) &&
3471         allSameType(TE.Scalars)) {
3472       // Check that gather of extractelements can be represented as
3473       // just a shuffle of a single vector.
3474       OrdersType CurrentOrder;
3475       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3476       if (Reuse || !CurrentOrder.empty()) {
3477         if (!CurrentOrder.empty())
3478           fixupOrderingIndices(CurrentOrder);
3479         return CurrentOrder;
3480       }
3481     }
3482     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3483       return CurrentOrder;
3484   }
3485   return None;
3486 }
3487 
3488 void BoUpSLP::reorderTopToBottom() {
3489   // Maps VF to the graph nodes.
3490   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3491   // ExtractElement gather nodes which can be vectorized and need to handle
3492   // their ordering.
3493   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3494   // Find all reorderable nodes with the given VF.
3495   // Currently the are vectorized stores,loads,extracts + some gathering of
3496   // extracts.
3497   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3498                                  const std::unique_ptr<TreeEntry> &TE) {
3499     if (Optional<OrdersType> CurrentOrder =
3500             getReorderingData(*TE, /*TopToBottom=*/true)) {
3501       // Do not include ordering for nodes used in the alt opcode vectorization,
3502       // better to reorder them during bottom-to-top stage. If follow the order
3503       // here, it causes reordering of the whole graph though actually it is
3504       // profitable just to reorder the subgraph that starts from the alternate
3505       // opcode vectorization node. Such nodes already end-up with the shuffle
3506       // instruction and it is just enough to change this shuffle rather than
3507       // rotate the scalars for the whole graph.
3508       unsigned Cnt = 0;
3509       const TreeEntry *UserTE = TE.get();
3510       while (UserTE && Cnt < RecursionMaxDepth) {
3511         if (UserTE->UserTreeIndices.size() != 1)
3512           break;
3513         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3514               return EI.UserTE->State == TreeEntry::Vectorize &&
3515                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3516             }))
3517           return;
3518         if (UserTE->UserTreeIndices.empty())
3519           UserTE = nullptr;
3520         else
3521           UserTE = UserTE->UserTreeIndices.back().UserTE;
3522         ++Cnt;
3523       }
3524       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3525       if (TE->State != TreeEntry::Vectorize)
3526         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3527     }
3528   });
3529 
3530   // Reorder the graph nodes according to their vectorization factor.
3531   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3532        VF /= 2) {
3533     auto It = VFToOrderedEntries.find(VF);
3534     if (It == VFToOrderedEntries.end())
3535       continue;
3536     // Try to find the most profitable order. We just are looking for the most
3537     // used order and reorder scalar elements in the nodes according to this
3538     // mostly used order.
3539     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3540     // All operands are reordered and used only in this node - propagate the
3541     // most used order to the user node.
3542     MapVector<OrdersType, unsigned,
3543               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3544         OrdersUses;
3545     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3546     for (const TreeEntry *OpTE : OrderedEntries) {
3547       // No need to reorder this nodes, still need to extend and to use shuffle,
3548       // just need to merge reordering shuffle and the reuse shuffle.
3549       if (!OpTE->ReuseShuffleIndices.empty())
3550         continue;
3551       // Count number of orders uses.
3552       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3553         if (OpTE->State == TreeEntry::NeedToGather)
3554           return GathersToOrders.find(OpTE)->second;
3555         return OpTE->ReorderIndices;
3556       }();
3557       // Stores actually store the mask, not the order, need to invert.
3558       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3559           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3560         SmallVector<int> Mask;
3561         inversePermutation(Order, Mask);
3562         unsigned E = Order.size();
3563         OrdersType CurrentOrder(E, E);
3564         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3565           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3566         });
3567         fixupOrderingIndices(CurrentOrder);
3568         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3569       } else {
3570         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3571       }
3572     }
3573     // Set order of the user node.
3574     if (OrdersUses.empty())
3575       continue;
3576     // Choose the most used order.
3577     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3578     unsigned Cnt = OrdersUses.front().second;
3579     for (const auto &Pair : drop_begin(OrdersUses)) {
3580       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3581         BestOrder = Pair.first;
3582         Cnt = Pair.second;
3583       }
3584     }
3585     // Set order of the user node.
3586     if (BestOrder.empty())
3587       continue;
3588     SmallVector<int> Mask;
3589     inversePermutation(BestOrder, Mask);
3590     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3591     unsigned E = BestOrder.size();
3592     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3593       return I < E ? static_cast<int>(I) : UndefMaskElem;
3594     });
3595     // Do an actual reordering, if profitable.
3596     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3597       // Just do the reordering for the nodes with the given VF.
3598       if (TE->Scalars.size() != VF) {
3599         if (TE->ReuseShuffleIndices.size() == VF) {
3600           // Need to reorder the reuses masks of the operands with smaller VF to
3601           // be able to find the match between the graph nodes and scalar
3602           // operands of the given node during vectorization/cost estimation.
3603           assert(all_of(TE->UserTreeIndices,
3604                         [VF, &TE](const EdgeInfo &EI) {
3605                           return EI.UserTE->Scalars.size() == VF ||
3606                                  EI.UserTE->Scalars.size() ==
3607                                      TE->Scalars.size();
3608                         }) &&
3609                  "All users must be of VF size.");
3610           // Update ordering of the operands with the smaller VF than the given
3611           // one.
3612           reorderReuses(TE->ReuseShuffleIndices, Mask);
3613         }
3614         continue;
3615       }
3616       if (TE->State == TreeEntry::Vectorize &&
3617           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3618               InsertElementInst>(TE->getMainOp()) &&
3619           !TE->isAltShuffle()) {
3620         // Build correct orders for extract{element,value}, loads and
3621         // stores.
3622         reorderOrder(TE->ReorderIndices, Mask);
3623         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3624           TE->reorderOperands(Mask);
3625       } else {
3626         // Reorder the node and its operands.
3627         TE->reorderOperands(Mask);
3628         assert(TE->ReorderIndices.empty() &&
3629                "Expected empty reorder sequence.");
3630         reorderScalars(TE->Scalars, Mask);
3631       }
3632       if (!TE->ReuseShuffleIndices.empty()) {
3633         // Apply reversed order to keep the original ordering of the reused
3634         // elements to avoid extra reorder indices shuffling.
3635         OrdersType CurrentOrder;
3636         reorderOrder(CurrentOrder, MaskOrder);
3637         SmallVector<int> NewReuses;
3638         inversePermutation(CurrentOrder, NewReuses);
3639         addMask(NewReuses, TE->ReuseShuffleIndices);
3640         TE->ReuseShuffleIndices.swap(NewReuses);
3641       }
3642     }
3643   }
3644 }
3645 
3646 bool BoUpSLP::canReorderOperands(
3647     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3648     ArrayRef<TreeEntry *> ReorderableGathers,
3649     SmallVectorImpl<TreeEntry *> &GatherOps) {
3650   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3651     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3652           return OpData.first == I &&
3653                  OpData.second->State == TreeEntry::Vectorize;
3654         }))
3655       continue;
3656     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3657       // Do not reorder if operand node is used by many user nodes.
3658       if (any_of(TE->UserTreeIndices,
3659                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3660         return false;
3661       // Add the node to the list of the ordered nodes with the identity
3662       // order.
3663       Edges.emplace_back(I, TE);
3664       continue;
3665     }
3666     ArrayRef<Value *> VL = UserTE->getOperand(I);
3667     TreeEntry *Gather = nullptr;
3668     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3669           assert(TE->State != TreeEntry::Vectorize &&
3670                  "Only non-vectorized nodes are expected.");
3671           if (TE->isSame(VL)) {
3672             Gather = TE;
3673             return true;
3674           }
3675           return false;
3676         }) > 1)
3677       return false;
3678     if (Gather)
3679       GatherOps.push_back(Gather);
3680   }
3681   return true;
3682 }
3683 
3684 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3685   SetVector<TreeEntry *> OrderedEntries;
3686   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3687   // Find all reorderable leaf nodes with the given VF.
3688   // Currently the are vectorized loads,extracts without alternate operands +
3689   // some gathering of extracts.
3690   SmallVector<TreeEntry *> NonVectorized;
3691   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3692                               &NonVectorized](
3693                                  const std::unique_ptr<TreeEntry> &TE) {
3694     if (TE->State != TreeEntry::Vectorize)
3695       NonVectorized.push_back(TE.get());
3696     if (Optional<OrdersType> CurrentOrder =
3697             getReorderingData(*TE, /*TopToBottom=*/false)) {
3698       OrderedEntries.insert(TE.get());
3699       if (TE->State != TreeEntry::Vectorize)
3700         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3701     }
3702   });
3703 
3704   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3705   // I.e., if the node has operands, that are reordered, try to make at least
3706   // one operand order in the natural order and reorder others + reorder the
3707   // user node itself.
3708   SmallPtrSet<const TreeEntry *, 4> Visited;
3709   while (!OrderedEntries.empty()) {
3710     // 1. Filter out only reordered nodes.
3711     // 2. If the entry has multiple uses - skip it and jump to the next node.
3712     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3713     SmallVector<TreeEntry *> Filtered;
3714     for (TreeEntry *TE : OrderedEntries) {
3715       if (!(TE->State == TreeEntry::Vectorize ||
3716             (TE->State == TreeEntry::NeedToGather &&
3717              GathersToOrders.count(TE))) ||
3718           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3719           !all_of(drop_begin(TE->UserTreeIndices),
3720                   [TE](const EdgeInfo &EI) {
3721                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3722                   }) ||
3723           !Visited.insert(TE).second) {
3724         Filtered.push_back(TE);
3725         continue;
3726       }
3727       // Build a map between user nodes and their operands order to speedup
3728       // search. The graph currently does not provide this dependency directly.
3729       for (EdgeInfo &EI : TE->UserTreeIndices) {
3730         TreeEntry *UserTE = EI.UserTE;
3731         auto It = Users.find(UserTE);
3732         if (It == Users.end())
3733           It = Users.insert({UserTE, {}}).first;
3734         It->second.emplace_back(EI.EdgeIdx, TE);
3735       }
3736     }
3737     // Erase filtered entries.
3738     for_each(Filtered,
3739              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3740     for (auto &Data : Users) {
3741       // Check that operands are used only in the User node.
3742       SmallVector<TreeEntry *> GatherOps;
3743       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3744                               GatherOps)) {
3745         for_each(Data.second,
3746                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3747                    OrderedEntries.remove(Op.second);
3748                  });
3749         continue;
3750       }
3751       // All operands are reordered and used only in this node - propagate the
3752       // most used order to the user node.
3753       MapVector<OrdersType, unsigned,
3754                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3755           OrdersUses;
3756       // Do the analysis for each tree entry only once, otherwise the order of
3757       // the same node my be considered several times, though might be not
3758       // profitable.
3759       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3760       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3761       for (const auto &Op : Data.second) {
3762         TreeEntry *OpTE = Op.second;
3763         if (!VisitedOps.insert(OpTE).second)
3764           continue;
3765         if (!OpTE->ReuseShuffleIndices.empty() ||
3766             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3767           continue;
3768         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3769           if (OpTE->State == TreeEntry::NeedToGather)
3770             return GathersToOrders.find(OpTE)->second;
3771           return OpTE->ReorderIndices;
3772         }();
3773         unsigned NumOps = count_if(
3774             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3775               return P.second == OpTE;
3776             });
3777         // Stores actually store the mask, not the order, need to invert.
3778         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3779             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3780           SmallVector<int> Mask;
3781           inversePermutation(Order, Mask);
3782           unsigned E = Order.size();
3783           OrdersType CurrentOrder(E, E);
3784           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3785             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3786           });
3787           fixupOrderingIndices(CurrentOrder);
3788           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3789               NumOps;
3790         } else {
3791           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3792         }
3793         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3794         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3795                                             const TreeEntry *TE) {
3796           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3797               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3798               (IgnoreReorder && TE->Idx == 0))
3799             return true;
3800           if (TE->State == TreeEntry::NeedToGather) {
3801             auto It = GathersToOrders.find(TE);
3802             if (It != GathersToOrders.end())
3803               return !It->second.empty();
3804             return true;
3805           }
3806           return false;
3807         };
3808         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3809           TreeEntry *UserTE = EI.UserTE;
3810           if (!VisitedUsers.insert(UserTE).second)
3811             continue;
3812           // May reorder user node if it requires reordering, has reused
3813           // scalars, is an alternate op vectorize node or its op nodes require
3814           // reordering.
3815           if (AllowsReordering(UserTE))
3816             continue;
3817           // Check if users allow reordering.
3818           // Currently look up just 1 level of operands to avoid increase of
3819           // the compile time.
3820           // Profitable to reorder if definitely more operands allow
3821           // reordering rather than those with natural order.
3822           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3823           if (static_cast<unsigned>(count_if(
3824                   Ops, [UserTE, &AllowsReordering](
3825                            const std::pair<unsigned, TreeEntry *> &Op) {
3826                     return AllowsReordering(Op.second) &&
3827                            all_of(Op.second->UserTreeIndices,
3828                                   [UserTE](const EdgeInfo &EI) {
3829                                     return EI.UserTE == UserTE;
3830                                   });
3831                   })) <= Ops.size() / 2)
3832             ++Res.first->second;
3833         }
3834       }
3835       // If no orders - skip current nodes and jump to the next one, if any.
3836       if (OrdersUses.empty()) {
3837         for_each(Data.second,
3838                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3839                    OrderedEntries.remove(Op.second);
3840                  });
3841         continue;
3842       }
3843       // Choose the best order.
3844       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3845       unsigned Cnt = OrdersUses.front().second;
3846       for (const auto &Pair : drop_begin(OrdersUses)) {
3847         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3848           BestOrder = Pair.first;
3849           Cnt = Pair.second;
3850         }
3851       }
3852       // Set order of the user node (reordering of operands and user nodes).
3853       if (BestOrder.empty()) {
3854         for_each(Data.second,
3855                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3856                    OrderedEntries.remove(Op.second);
3857                  });
3858         continue;
3859       }
3860       // Erase operands from OrderedEntries list and adjust their orders.
3861       VisitedOps.clear();
3862       SmallVector<int> Mask;
3863       inversePermutation(BestOrder, Mask);
3864       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3865       unsigned E = BestOrder.size();
3866       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3867         return I < E ? static_cast<int>(I) : UndefMaskElem;
3868       });
3869       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3870         TreeEntry *TE = Op.second;
3871         OrderedEntries.remove(TE);
3872         if (!VisitedOps.insert(TE).second)
3873           continue;
3874         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3875           // Just reorder reuses indices.
3876           reorderReuses(TE->ReuseShuffleIndices, Mask);
3877           continue;
3878         }
3879         // Gathers are processed separately.
3880         if (TE->State != TreeEntry::Vectorize)
3881           continue;
3882         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3883                 TE->ReorderIndices.empty()) &&
3884                "Non-matching sizes of user/operand entries.");
3885         reorderOrder(TE->ReorderIndices, Mask);
3886       }
3887       // For gathers just need to reorder its scalars.
3888       for (TreeEntry *Gather : GatherOps) {
3889         assert(Gather->ReorderIndices.empty() &&
3890                "Unexpected reordering of gathers.");
3891         if (!Gather->ReuseShuffleIndices.empty()) {
3892           // Just reorder reuses indices.
3893           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3894           continue;
3895         }
3896         reorderScalars(Gather->Scalars, Mask);
3897         OrderedEntries.remove(Gather);
3898       }
3899       // Reorder operands of the user node and set the ordering for the user
3900       // node itself.
3901       if (Data.first->State != TreeEntry::Vectorize ||
3902           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3903               Data.first->getMainOp()) ||
3904           Data.first->isAltShuffle())
3905         Data.first->reorderOperands(Mask);
3906       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3907           Data.first->isAltShuffle()) {
3908         reorderScalars(Data.first->Scalars, Mask);
3909         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3910         if (Data.first->ReuseShuffleIndices.empty() &&
3911             !Data.first->ReorderIndices.empty() &&
3912             !Data.first->isAltShuffle()) {
3913           // Insert user node to the list to try to sink reordering deeper in
3914           // the graph.
3915           OrderedEntries.insert(Data.first);
3916         }
3917       } else {
3918         reorderOrder(Data.first->ReorderIndices, Mask);
3919       }
3920     }
3921   }
3922   // If the reordering is unnecessary, just remove the reorder.
3923   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3924       VectorizableTree.front()->ReuseShuffleIndices.empty())
3925     VectorizableTree.front()->ReorderIndices.clear();
3926 }
3927 
3928 void BoUpSLP::buildExternalUses(
3929     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3930   // Collect the values that we need to extract from the tree.
3931   for (auto &TEPtr : VectorizableTree) {
3932     TreeEntry *Entry = TEPtr.get();
3933 
3934     // No need to handle users of gathered values.
3935     if (Entry->State == TreeEntry::NeedToGather)
3936       continue;
3937 
3938     // For each lane:
3939     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3940       Value *Scalar = Entry->Scalars[Lane];
3941       int FoundLane = Entry->findLaneForValue(Scalar);
3942 
3943       // Check if the scalar is externally used as an extra arg.
3944       auto ExtI = ExternallyUsedValues.find(Scalar);
3945       if (ExtI != ExternallyUsedValues.end()) {
3946         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3947                           << Lane << " from " << *Scalar << ".\n");
3948         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3949       }
3950       for (User *U : Scalar->users()) {
3951         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3952 
3953         Instruction *UserInst = dyn_cast<Instruction>(U);
3954         if (!UserInst)
3955           continue;
3956 
3957         if (isDeleted(UserInst))
3958           continue;
3959 
3960         // Skip in-tree scalars that become vectors
3961         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3962           Value *UseScalar = UseEntry->Scalars[0];
3963           // Some in-tree scalars will remain as scalar in vectorized
3964           // instructions. If that is the case, the one in Lane 0 will
3965           // be used.
3966           if (UseScalar != U ||
3967               UseEntry->State == TreeEntry::ScatterVectorize ||
3968               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3969             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3970                               << ".\n");
3971             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3972             continue;
3973           }
3974         }
3975 
3976         // Ignore users in the user ignore list.
3977         if (is_contained(UserIgnoreList, UserInst))
3978           continue;
3979 
3980         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3981                           << Lane << " from " << *Scalar << ".\n");
3982         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3983       }
3984     }
3985   }
3986 }
3987 
3988 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3989                         ArrayRef<Value *> UserIgnoreLst) {
3990   deleteTree();
3991   UserIgnoreList = UserIgnoreLst;
3992   if (!allSameType(Roots))
3993     return;
3994   buildTree_rec(Roots, 0, EdgeInfo());
3995 }
3996 
3997 namespace {
3998 /// Tracks the state we can represent the loads in the given sequence.
3999 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
4000 } // anonymous namespace
4001 
4002 /// Checks if the given array of loads can be represented as a vectorized,
4003 /// scatter or just simple gather.
4004 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
4005                                     const TargetTransformInfo &TTI,
4006                                     const DataLayout &DL, ScalarEvolution &SE,
4007                                     SmallVectorImpl<unsigned> &Order,
4008                                     SmallVectorImpl<Value *> &PointerOps) {
4009   // Check that a vectorized load would load the same memory as a scalar
4010   // load. For example, we don't want to vectorize loads that are smaller
4011   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4012   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4013   // from such a struct, we read/write packed bits disagreeing with the
4014   // unvectorized version.
4015   Type *ScalarTy = VL0->getType();
4016 
4017   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
4018     return LoadsState::Gather;
4019 
4020   // Make sure all loads in the bundle are simple - we can't vectorize
4021   // atomic or volatile loads.
4022   PointerOps.clear();
4023   PointerOps.resize(VL.size());
4024   auto *POIter = PointerOps.begin();
4025   for (Value *V : VL) {
4026     auto *L = cast<LoadInst>(V);
4027     if (!L->isSimple())
4028       return LoadsState::Gather;
4029     *POIter = L->getPointerOperand();
4030     ++POIter;
4031   }
4032 
4033   Order.clear();
4034   // Check the order of pointer operands.
4035   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
4036     Value *Ptr0;
4037     Value *PtrN;
4038     if (Order.empty()) {
4039       Ptr0 = PointerOps.front();
4040       PtrN = PointerOps.back();
4041     } else {
4042       Ptr0 = PointerOps[Order.front()];
4043       PtrN = PointerOps[Order.back()];
4044     }
4045     Optional<int> Diff =
4046         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
4047     // Check that the sorted loads are consecutive.
4048     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
4049       return LoadsState::Vectorize;
4050     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
4051     for (Value *V : VL)
4052       CommonAlignment =
4053           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4054     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
4055                                 CommonAlignment))
4056       return LoadsState::ScatterVectorize;
4057   }
4058 
4059   return LoadsState::Gather;
4060 }
4061 
4062 /// \return true if the specified list of values has only one instruction that
4063 /// requires scheduling, false otherwise.
4064 #ifndef NDEBUG
4065 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
4066   Value *NeedsScheduling = nullptr;
4067   for (Value *V : VL) {
4068     if (doesNotNeedToBeScheduled(V))
4069       continue;
4070     if (!NeedsScheduling) {
4071       NeedsScheduling = V;
4072       continue;
4073     }
4074     return false;
4075   }
4076   return NeedsScheduling;
4077 }
4078 #endif
4079 
4080 /// Generates key/subkey pair for the given value to provide effective sorting
4081 /// of the values and better detection of the vectorizable values sequences. The
4082 /// keys/subkeys can be used for better sorting of the values themselves (keys)
4083 /// and in values subgroups (subkeys).
4084 static std::pair<size_t, size_t> generateKeySubkey(
4085     Value *V, const TargetLibraryInfo *TLI,
4086     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4087     bool AllowAlternate) {
4088   hash_code Key = hash_value(V->getValueID() + 2);
4089   hash_code SubKey = hash_value(0);
4090   // Sort the loads by the distance between the pointers.
4091   if (auto *LI = dyn_cast<LoadInst>(V)) {
4092     Key = hash_combine(hash_value(Instruction::Load), Key);
4093     if (LI->isSimple())
4094       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4095     else
4096       SubKey = hash_value(LI);
4097   } else if (isVectorLikeInstWithConstOps(V)) {
4098     // Sort extracts by the vector operands.
4099     if (isa<ExtractElementInst, UndefValue>(V))
4100       Key = hash_value(Value::UndefValueVal + 1);
4101     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4102       if (!isUndefVector(EI->getVectorOperand()) &&
4103           !isa<UndefValue>(EI->getIndexOperand()))
4104         SubKey = hash_value(EI->getVectorOperand());
4105     }
4106   } else if (auto *I = dyn_cast<Instruction>(V)) {
4107     // Sort other instructions just by the opcodes except for CMPInst.
4108     // For CMP also sort by the predicate kind.
4109     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4110         isValidForAlternation(I->getOpcode())) {
4111       if (AllowAlternate)
4112         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4113       else
4114         Key = hash_combine(hash_value(I->getOpcode()), Key);
4115       SubKey = hash_combine(
4116           hash_value(I->getOpcode()), hash_value(I->getType()),
4117           hash_value(isa<BinaryOperator>(I)
4118                          ? I->getType()
4119                          : cast<CastInst>(I)->getOperand(0)->getType()));
4120     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4121       CmpInst::Predicate Pred = CI->getPredicate();
4122       if (CI->isCommutative())
4123         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4124       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4125       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4126                             hash_value(SwapPred),
4127                             hash_value(CI->getOperand(0)->getType()));
4128     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4129       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4130       if (isTriviallyVectorizable(ID))
4131         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4132       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4133         SubKey = hash_combine(hash_value(I->getOpcode()),
4134                               hash_value(Call->getCalledFunction()));
4135       else
4136         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4137       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4138         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4139                               hash_value(Op.Tag), SubKey);
4140     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4141       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4142         SubKey = hash_value(Gep->getPointerOperand());
4143       else
4144         SubKey = hash_value(Gep);
4145     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4146                !isa<ConstantInt>(I->getOperand(1))) {
4147       // Do not try to vectorize instructions with potentially high cost.
4148       SubKey = hash_value(I);
4149     } else {
4150       SubKey = hash_value(I->getOpcode());
4151     }
4152     Key = hash_combine(hash_value(I->getParent()), Key);
4153   }
4154   return std::make_pair(Key, SubKey);
4155 }
4156 
4157 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4158                             const EdgeInfo &UserTreeIdx) {
4159   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4160 
4161   SmallVector<int> ReuseShuffleIndicies;
4162   SmallVector<Value *> UniqueValues;
4163   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4164                                 &UserTreeIdx,
4165                                 this](const InstructionsState &S) {
4166     // Check that every instruction appears once in this bundle.
4167     DenseMap<Value *, unsigned> UniquePositions;
4168     for (Value *V : VL) {
4169       if (isConstant(V)) {
4170         ReuseShuffleIndicies.emplace_back(
4171             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4172         UniqueValues.emplace_back(V);
4173         continue;
4174       }
4175       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4176       ReuseShuffleIndicies.emplace_back(Res.first->second);
4177       if (Res.second)
4178         UniqueValues.emplace_back(V);
4179     }
4180     size_t NumUniqueScalarValues = UniqueValues.size();
4181     if (NumUniqueScalarValues == VL.size()) {
4182       ReuseShuffleIndicies.clear();
4183     } else {
4184       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4185       if (NumUniqueScalarValues <= 1 ||
4186           (UniquePositions.size() == 1 && all_of(UniqueValues,
4187                                                  [](Value *V) {
4188                                                    return isa<UndefValue>(V) ||
4189                                                           !isConstant(V);
4190                                                  })) ||
4191           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4192         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4193         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4194         return false;
4195       }
4196       VL = UniqueValues;
4197     }
4198     return true;
4199   };
4200 
4201   InstructionsState S = getSameOpcode(VL);
4202   if (Depth == RecursionMaxDepth) {
4203     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4204     if (TryToFindDuplicates(S))
4205       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4206                    ReuseShuffleIndicies);
4207     return;
4208   }
4209 
4210   // Don't handle scalable vectors
4211   if (S.getOpcode() == Instruction::ExtractElement &&
4212       isa<ScalableVectorType>(
4213           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4214     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4215     if (TryToFindDuplicates(S))
4216       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4217                    ReuseShuffleIndicies);
4218     return;
4219   }
4220 
4221   // Don't handle vectors.
4222   if (S.OpValue->getType()->isVectorTy() &&
4223       !isa<InsertElementInst>(S.OpValue)) {
4224     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4225     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4226     return;
4227   }
4228 
4229   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4230     if (SI->getValueOperand()->getType()->isVectorTy()) {
4231       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4232       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4233       return;
4234     }
4235 
4236   // If all of the operands are identical or constant we have a simple solution.
4237   // If we deal with insert/extract instructions, they all must have constant
4238   // indices, otherwise we should gather them, not try to vectorize.
4239   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4240       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4241        !all_of(VL, isVectorLikeInstWithConstOps))) {
4242     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4243     if (TryToFindDuplicates(S))
4244       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4245                    ReuseShuffleIndicies);
4246     return;
4247   }
4248 
4249   // We now know that this is a vector of instructions of the same type from
4250   // the same block.
4251 
4252   // Don't vectorize ephemeral values.
4253   for (Value *V : VL) {
4254     if (EphValues.count(V)) {
4255       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4256                         << ") is ephemeral.\n");
4257       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4258       return;
4259     }
4260   }
4261 
4262   // Check if this is a duplicate of another entry.
4263   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4264     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4265     if (!E->isSame(VL)) {
4266       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4267       if (TryToFindDuplicates(S))
4268         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4269                      ReuseShuffleIndicies);
4270       return;
4271     }
4272     // Record the reuse of the tree node.  FIXME, currently this is only used to
4273     // properly draw the graph rather than for the actual vectorization.
4274     E->UserTreeIndices.push_back(UserTreeIdx);
4275     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4276                       << ".\n");
4277     return;
4278   }
4279 
4280   // Check that none of the instructions in the bundle are already in the tree.
4281   for (Value *V : VL) {
4282     auto *I = dyn_cast<Instruction>(V);
4283     if (!I)
4284       continue;
4285     if (getTreeEntry(I)) {
4286       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4287                         << ") is already in tree.\n");
4288       if (TryToFindDuplicates(S))
4289         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4290                      ReuseShuffleIndicies);
4291       return;
4292     }
4293   }
4294 
4295   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4296   for (Value *V : VL) {
4297     if (is_contained(UserIgnoreList, V)) {
4298       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4299       if (TryToFindDuplicates(S))
4300         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4301                      ReuseShuffleIndicies);
4302       return;
4303     }
4304   }
4305 
4306   // Check that all of the users of the scalars that we want to vectorize are
4307   // schedulable.
4308   auto *VL0 = cast<Instruction>(S.OpValue);
4309   BasicBlock *BB = VL0->getParent();
4310 
4311   if (!DT->isReachableFromEntry(BB)) {
4312     // Don't go into unreachable blocks. They may contain instructions with
4313     // dependency cycles which confuse the final scheduling.
4314     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4315     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4316     return;
4317   }
4318 
4319   // Check that every instruction appears once in this bundle.
4320   if (!TryToFindDuplicates(S))
4321     return;
4322 
4323   auto &BSRef = BlocksSchedules[BB];
4324   if (!BSRef)
4325     BSRef = std::make_unique<BlockScheduling>(BB);
4326 
4327   BlockScheduling &BS = *BSRef;
4328 
4329   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4330 #ifdef EXPENSIVE_CHECKS
4331   // Make sure we didn't break any internal invariants
4332   BS.verify();
4333 #endif
4334   if (!Bundle) {
4335     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4336     assert((!BS.getScheduleData(VL0) ||
4337             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4338            "tryScheduleBundle should cancelScheduling on failure");
4339     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4340                  ReuseShuffleIndicies);
4341     return;
4342   }
4343   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4344 
4345   unsigned ShuffleOrOp = S.isAltShuffle() ?
4346                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4347   switch (ShuffleOrOp) {
4348     case Instruction::PHI: {
4349       auto *PH = cast<PHINode>(VL0);
4350 
4351       // Check for terminator values (e.g. invoke).
4352       for (Value *V : VL)
4353         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4354           Instruction *Term = dyn_cast<Instruction>(Incoming);
4355           if (Term && Term->isTerminator()) {
4356             LLVM_DEBUG(dbgs()
4357                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4358             BS.cancelScheduling(VL, VL0);
4359             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4360                          ReuseShuffleIndicies);
4361             return;
4362           }
4363         }
4364 
4365       TreeEntry *TE =
4366           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4367       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4368 
4369       // Keeps the reordered operands to avoid code duplication.
4370       SmallVector<ValueList, 2> OperandsVec;
4371       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4372         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4373           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4374           TE->setOperand(I, Operands);
4375           OperandsVec.push_back(Operands);
4376           continue;
4377         }
4378         ValueList Operands;
4379         // Prepare the operand vector.
4380         for (Value *V : VL)
4381           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4382               PH->getIncomingBlock(I)));
4383         TE->setOperand(I, Operands);
4384         OperandsVec.push_back(Operands);
4385       }
4386       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4387         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4388       return;
4389     }
4390     case Instruction::ExtractValue:
4391     case Instruction::ExtractElement: {
4392       OrdersType CurrentOrder;
4393       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4394       if (Reuse) {
4395         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4396         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4397                      ReuseShuffleIndicies);
4398         // This is a special case, as it does not gather, but at the same time
4399         // we are not extending buildTree_rec() towards the operands.
4400         ValueList Op0;
4401         Op0.assign(VL.size(), VL0->getOperand(0));
4402         VectorizableTree.back()->setOperand(0, Op0);
4403         return;
4404       }
4405       if (!CurrentOrder.empty()) {
4406         LLVM_DEBUG({
4407           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4408                     "with order";
4409           for (unsigned Idx : CurrentOrder)
4410             dbgs() << " " << Idx;
4411           dbgs() << "\n";
4412         });
4413         fixupOrderingIndices(CurrentOrder);
4414         // Insert new order with initial value 0, if it does not exist,
4415         // otherwise return the iterator to the existing one.
4416         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4417                      ReuseShuffleIndicies, CurrentOrder);
4418         // This is a special case, as it does not gather, but at the same time
4419         // we are not extending buildTree_rec() towards the operands.
4420         ValueList Op0;
4421         Op0.assign(VL.size(), VL0->getOperand(0));
4422         VectorizableTree.back()->setOperand(0, Op0);
4423         return;
4424       }
4425       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4426       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4427                    ReuseShuffleIndicies);
4428       BS.cancelScheduling(VL, VL0);
4429       return;
4430     }
4431     case Instruction::InsertElement: {
4432       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4433 
4434       // Check that we have a buildvector and not a shuffle of 2 or more
4435       // different vectors.
4436       ValueSet SourceVectors;
4437       for (Value *V : VL) {
4438         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4439         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4440       }
4441 
4442       if (count_if(VL, [&SourceVectors](Value *V) {
4443             return !SourceVectors.contains(V);
4444           }) >= 2) {
4445         // Found 2nd source vector - cancel.
4446         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4447                              "different source vectors.\n");
4448         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4449         BS.cancelScheduling(VL, VL0);
4450         return;
4451       }
4452 
4453       auto OrdCompare = [](const std::pair<int, int> &P1,
4454                            const std::pair<int, int> &P2) {
4455         return P1.first > P2.first;
4456       };
4457       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4458                     decltype(OrdCompare)>
4459           Indices(OrdCompare);
4460       for (int I = 0, E = VL.size(); I < E; ++I) {
4461         unsigned Idx = *getInsertIndex(VL[I]);
4462         Indices.emplace(Idx, I);
4463       }
4464       OrdersType CurrentOrder(VL.size(), VL.size());
4465       bool IsIdentity = true;
4466       for (int I = 0, E = VL.size(); I < E; ++I) {
4467         CurrentOrder[Indices.top().second] = I;
4468         IsIdentity &= Indices.top().second == I;
4469         Indices.pop();
4470       }
4471       if (IsIdentity)
4472         CurrentOrder.clear();
4473       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4474                                    None, CurrentOrder);
4475       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4476 
4477       constexpr int NumOps = 2;
4478       ValueList VectorOperands[NumOps];
4479       for (int I = 0; I < NumOps; ++I) {
4480         for (Value *V : VL)
4481           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4482 
4483         TE->setOperand(I, VectorOperands[I]);
4484       }
4485       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4486       return;
4487     }
4488     case Instruction::Load: {
4489       // Check that a vectorized load would load the same memory as a scalar
4490       // load. For example, we don't want to vectorize loads that are smaller
4491       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4492       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4493       // from such a struct, we read/write packed bits disagreeing with the
4494       // unvectorized version.
4495       SmallVector<Value *> PointerOps;
4496       OrdersType CurrentOrder;
4497       TreeEntry *TE = nullptr;
4498       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4499                                 PointerOps)) {
4500       case LoadsState::Vectorize:
4501         if (CurrentOrder.empty()) {
4502           // Original loads are consecutive and does not require reordering.
4503           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4504                             ReuseShuffleIndicies);
4505           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4506         } else {
4507           fixupOrderingIndices(CurrentOrder);
4508           // Need to reorder.
4509           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4510                             ReuseShuffleIndicies, CurrentOrder);
4511           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4512         }
4513         TE->setOperandsInOrder();
4514         break;
4515       case LoadsState::ScatterVectorize:
4516         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4517         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4518                           UserTreeIdx, ReuseShuffleIndicies);
4519         TE->setOperandsInOrder();
4520         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4521         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4522         break;
4523       case LoadsState::Gather:
4524         BS.cancelScheduling(VL, VL0);
4525         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4526                      ReuseShuffleIndicies);
4527 #ifndef NDEBUG
4528         Type *ScalarTy = VL0->getType();
4529         if (DL->getTypeSizeInBits(ScalarTy) !=
4530             DL->getTypeAllocSizeInBits(ScalarTy))
4531           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4532         else if (any_of(VL, [](Value *V) {
4533                    return !cast<LoadInst>(V)->isSimple();
4534                  }))
4535           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4536         else
4537           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4538 #endif // NDEBUG
4539         break;
4540       }
4541       return;
4542     }
4543     case Instruction::ZExt:
4544     case Instruction::SExt:
4545     case Instruction::FPToUI:
4546     case Instruction::FPToSI:
4547     case Instruction::FPExt:
4548     case Instruction::PtrToInt:
4549     case Instruction::IntToPtr:
4550     case Instruction::SIToFP:
4551     case Instruction::UIToFP:
4552     case Instruction::Trunc:
4553     case Instruction::FPTrunc:
4554     case Instruction::BitCast: {
4555       Type *SrcTy = VL0->getOperand(0)->getType();
4556       for (Value *V : VL) {
4557         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4558         if (Ty != SrcTy || !isValidElementType(Ty)) {
4559           BS.cancelScheduling(VL, VL0);
4560           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4561                        ReuseShuffleIndicies);
4562           LLVM_DEBUG(dbgs()
4563                      << "SLP: Gathering casts with different src types.\n");
4564           return;
4565         }
4566       }
4567       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4568                                    ReuseShuffleIndicies);
4569       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4570 
4571       TE->setOperandsInOrder();
4572       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4573         ValueList Operands;
4574         // Prepare the operand vector.
4575         for (Value *V : VL)
4576           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4577 
4578         buildTree_rec(Operands, Depth + 1, {TE, i});
4579       }
4580       return;
4581     }
4582     case Instruction::ICmp:
4583     case Instruction::FCmp: {
4584       // Check that all of the compares have the same predicate.
4585       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4586       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4587       Type *ComparedTy = VL0->getOperand(0)->getType();
4588       for (Value *V : VL) {
4589         CmpInst *Cmp = cast<CmpInst>(V);
4590         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4591             Cmp->getOperand(0)->getType() != ComparedTy) {
4592           BS.cancelScheduling(VL, VL0);
4593           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4594                        ReuseShuffleIndicies);
4595           LLVM_DEBUG(dbgs()
4596                      << "SLP: Gathering cmp with different predicate.\n");
4597           return;
4598         }
4599       }
4600 
4601       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4602                                    ReuseShuffleIndicies);
4603       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4604 
4605       ValueList Left, Right;
4606       if (cast<CmpInst>(VL0)->isCommutative()) {
4607         // Commutative predicate - collect + sort operands of the instructions
4608         // so that each side is more likely to have the same opcode.
4609         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4610         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4611       } else {
4612         // Collect operands - commute if it uses the swapped predicate.
4613         for (Value *V : VL) {
4614           auto *Cmp = cast<CmpInst>(V);
4615           Value *LHS = Cmp->getOperand(0);
4616           Value *RHS = Cmp->getOperand(1);
4617           if (Cmp->getPredicate() != P0)
4618             std::swap(LHS, RHS);
4619           Left.push_back(LHS);
4620           Right.push_back(RHS);
4621         }
4622       }
4623       TE->setOperand(0, Left);
4624       TE->setOperand(1, Right);
4625       buildTree_rec(Left, Depth + 1, {TE, 0});
4626       buildTree_rec(Right, Depth + 1, {TE, 1});
4627       return;
4628     }
4629     case Instruction::Select:
4630     case Instruction::FNeg:
4631     case Instruction::Add:
4632     case Instruction::FAdd:
4633     case Instruction::Sub:
4634     case Instruction::FSub:
4635     case Instruction::Mul:
4636     case Instruction::FMul:
4637     case Instruction::UDiv:
4638     case Instruction::SDiv:
4639     case Instruction::FDiv:
4640     case Instruction::URem:
4641     case Instruction::SRem:
4642     case Instruction::FRem:
4643     case Instruction::Shl:
4644     case Instruction::LShr:
4645     case Instruction::AShr:
4646     case Instruction::And:
4647     case Instruction::Or:
4648     case Instruction::Xor: {
4649       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4650                                    ReuseShuffleIndicies);
4651       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4652 
4653       // Sort operands of the instructions so that each side is more likely to
4654       // have the same opcode.
4655       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4656         ValueList Left, Right;
4657         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4658         TE->setOperand(0, Left);
4659         TE->setOperand(1, Right);
4660         buildTree_rec(Left, Depth + 1, {TE, 0});
4661         buildTree_rec(Right, Depth + 1, {TE, 1});
4662         return;
4663       }
4664 
4665       TE->setOperandsInOrder();
4666       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4667         ValueList Operands;
4668         // Prepare the operand vector.
4669         for (Value *V : VL)
4670           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4671 
4672         buildTree_rec(Operands, Depth + 1, {TE, i});
4673       }
4674       return;
4675     }
4676     case Instruction::GetElementPtr: {
4677       // We don't combine GEPs with complicated (nested) indexing.
4678       for (Value *V : VL) {
4679         if (cast<Instruction>(V)->getNumOperands() != 2) {
4680           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4681           BS.cancelScheduling(VL, VL0);
4682           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4683                        ReuseShuffleIndicies);
4684           return;
4685         }
4686       }
4687 
4688       // We can't combine several GEPs into one vector if they operate on
4689       // different types.
4690       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4691       for (Value *V : VL) {
4692         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4693         if (Ty0 != CurTy) {
4694           LLVM_DEBUG(dbgs()
4695                      << "SLP: not-vectorizable GEP (different types).\n");
4696           BS.cancelScheduling(VL, VL0);
4697           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4698                        ReuseShuffleIndicies);
4699           return;
4700         }
4701       }
4702 
4703       // We don't combine GEPs with non-constant indexes.
4704       Type *Ty1 = VL0->getOperand(1)->getType();
4705       for (Value *V : VL) {
4706         auto Op = cast<Instruction>(V)->getOperand(1);
4707         if (!isa<ConstantInt>(Op) ||
4708             (Op->getType() != Ty1 &&
4709              Op->getType()->getScalarSizeInBits() >
4710                  DL->getIndexSizeInBits(
4711                      V->getType()->getPointerAddressSpace()))) {
4712           LLVM_DEBUG(dbgs()
4713                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4714           BS.cancelScheduling(VL, VL0);
4715           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4716                        ReuseShuffleIndicies);
4717           return;
4718         }
4719       }
4720 
4721       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4722                                    ReuseShuffleIndicies);
4723       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4724       SmallVector<ValueList, 2> Operands(2);
4725       // Prepare the operand vector for pointer operands.
4726       for (Value *V : VL)
4727         Operands.front().push_back(
4728             cast<GetElementPtrInst>(V)->getPointerOperand());
4729       TE->setOperand(0, Operands.front());
4730       // Need to cast all indices to the same type before vectorization to
4731       // avoid crash.
4732       // Required to be able to find correct matches between different gather
4733       // nodes and reuse the vectorized values rather than trying to gather them
4734       // again.
4735       int IndexIdx = 1;
4736       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4737       Type *Ty = all_of(VL,
4738                         [VL0Ty, IndexIdx](Value *V) {
4739                           return VL0Ty == cast<GetElementPtrInst>(V)
4740                                               ->getOperand(IndexIdx)
4741                                               ->getType();
4742                         })
4743                      ? VL0Ty
4744                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4745                                             ->getPointerOperandType()
4746                                             ->getScalarType());
4747       // Prepare the operand vector.
4748       for (Value *V : VL) {
4749         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4750         auto *CI = cast<ConstantInt>(Op);
4751         Operands.back().push_back(ConstantExpr::getIntegerCast(
4752             CI, Ty, CI->getValue().isSignBitSet()));
4753       }
4754       TE->setOperand(IndexIdx, Operands.back());
4755 
4756       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4757         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4758       return;
4759     }
4760     case Instruction::Store: {
4761       // Check if the stores are consecutive or if we need to swizzle them.
4762       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4763       // Avoid types that are padded when being allocated as scalars, while
4764       // being packed together in a vector (such as i1).
4765       if (DL->getTypeSizeInBits(ScalarTy) !=
4766           DL->getTypeAllocSizeInBits(ScalarTy)) {
4767         BS.cancelScheduling(VL, VL0);
4768         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4769                      ReuseShuffleIndicies);
4770         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4771         return;
4772       }
4773       // Make sure all stores in the bundle are simple - we can't vectorize
4774       // atomic or volatile stores.
4775       SmallVector<Value *, 4> PointerOps(VL.size());
4776       ValueList Operands(VL.size());
4777       auto POIter = PointerOps.begin();
4778       auto OIter = Operands.begin();
4779       for (Value *V : VL) {
4780         auto *SI = cast<StoreInst>(V);
4781         if (!SI->isSimple()) {
4782           BS.cancelScheduling(VL, VL0);
4783           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4784                        ReuseShuffleIndicies);
4785           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4786           return;
4787         }
4788         *POIter = SI->getPointerOperand();
4789         *OIter = SI->getValueOperand();
4790         ++POIter;
4791         ++OIter;
4792       }
4793 
4794       OrdersType CurrentOrder;
4795       // Check the order of pointer operands.
4796       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4797         Value *Ptr0;
4798         Value *PtrN;
4799         if (CurrentOrder.empty()) {
4800           Ptr0 = PointerOps.front();
4801           PtrN = PointerOps.back();
4802         } else {
4803           Ptr0 = PointerOps[CurrentOrder.front()];
4804           PtrN = PointerOps[CurrentOrder.back()];
4805         }
4806         Optional<int> Dist =
4807             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4808         // Check that the sorted pointer operands are consecutive.
4809         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4810           if (CurrentOrder.empty()) {
4811             // Original stores are consecutive and does not require reordering.
4812             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4813                                          UserTreeIdx, ReuseShuffleIndicies);
4814             TE->setOperandsInOrder();
4815             buildTree_rec(Operands, Depth + 1, {TE, 0});
4816             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4817           } else {
4818             fixupOrderingIndices(CurrentOrder);
4819             TreeEntry *TE =
4820                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4821                              ReuseShuffleIndicies, CurrentOrder);
4822             TE->setOperandsInOrder();
4823             buildTree_rec(Operands, Depth + 1, {TE, 0});
4824             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4825           }
4826           return;
4827         }
4828       }
4829 
4830       BS.cancelScheduling(VL, VL0);
4831       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4832                    ReuseShuffleIndicies);
4833       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4834       return;
4835     }
4836     case Instruction::Call: {
4837       // Check if the calls are all to the same vectorizable intrinsic or
4838       // library function.
4839       CallInst *CI = cast<CallInst>(VL0);
4840       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4841 
4842       VFShape Shape = VFShape::get(
4843           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4844           false /*HasGlobalPred*/);
4845       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4846 
4847       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4848         BS.cancelScheduling(VL, VL0);
4849         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4850                      ReuseShuffleIndicies);
4851         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4852         return;
4853       }
4854       Function *F = CI->getCalledFunction();
4855       unsigned NumArgs = CI->arg_size();
4856       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4857       for (unsigned j = 0; j != NumArgs; ++j)
4858         if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
4859           ScalarArgs[j] = CI->getArgOperand(j);
4860       for (Value *V : VL) {
4861         CallInst *CI2 = dyn_cast<CallInst>(V);
4862         if (!CI2 || CI2->getCalledFunction() != F ||
4863             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4864             (VecFunc &&
4865              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4866             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4867           BS.cancelScheduling(VL, VL0);
4868           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4869                        ReuseShuffleIndicies);
4870           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4871                             << "\n");
4872           return;
4873         }
4874         // Some intrinsics have scalar arguments and should be same in order for
4875         // them to be vectorized.
4876         for (unsigned j = 0; j != NumArgs; ++j) {
4877           if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
4878             Value *A1J = CI2->getArgOperand(j);
4879             if (ScalarArgs[j] != A1J) {
4880               BS.cancelScheduling(VL, VL0);
4881               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4882                            ReuseShuffleIndicies);
4883               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4884                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4885                                 << "\n");
4886               return;
4887             }
4888           }
4889         }
4890         // Verify that the bundle operands are identical between the two calls.
4891         if (CI->hasOperandBundles() &&
4892             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4893                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4894                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4895           BS.cancelScheduling(VL, VL0);
4896           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4897                        ReuseShuffleIndicies);
4898           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4899                             << *CI << "!=" << *V << '\n');
4900           return;
4901         }
4902       }
4903 
4904       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4905                                    ReuseShuffleIndicies);
4906       TE->setOperandsInOrder();
4907       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4908         // For scalar operands no need to to create an entry since no need to
4909         // vectorize it.
4910         if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
4911           continue;
4912         ValueList Operands;
4913         // Prepare the operand vector.
4914         for (Value *V : VL) {
4915           auto *CI2 = cast<CallInst>(V);
4916           Operands.push_back(CI2->getArgOperand(i));
4917         }
4918         buildTree_rec(Operands, Depth + 1, {TE, i});
4919       }
4920       return;
4921     }
4922     case Instruction::ShuffleVector: {
4923       // If this is not an alternate sequence of opcode like add-sub
4924       // then do not vectorize this instruction.
4925       if (!S.isAltShuffle()) {
4926         BS.cancelScheduling(VL, VL0);
4927         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4928                      ReuseShuffleIndicies);
4929         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4930         return;
4931       }
4932       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4933                                    ReuseShuffleIndicies);
4934       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4935 
4936       // Reorder operands if reordering would enable vectorization.
4937       auto *CI = dyn_cast<CmpInst>(VL0);
4938       if (isa<BinaryOperator>(VL0) || CI) {
4939         ValueList Left, Right;
4940         if (!CI || all_of(VL, [](Value *V) {
4941               return cast<CmpInst>(V)->isCommutative();
4942             })) {
4943           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4944         } else {
4945           CmpInst::Predicate P0 = CI->getPredicate();
4946           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4947           assert(P0 != AltP0 &&
4948                  "Expected different main/alternate predicates.");
4949           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4950           Value *BaseOp0 = VL0->getOperand(0);
4951           Value *BaseOp1 = VL0->getOperand(1);
4952           // Collect operands - commute if it uses the swapped predicate or
4953           // alternate operation.
4954           for (Value *V : VL) {
4955             auto *Cmp = cast<CmpInst>(V);
4956             Value *LHS = Cmp->getOperand(0);
4957             Value *RHS = Cmp->getOperand(1);
4958             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4959             if (P0 == AltP0Swapped) {
4960               if (CI != Cmp && S.AltOp != Cmp &&
4961                   ((P0 == CurrentPred &&
4962                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4963                    (AltP0 == CurrentPred &&
4964                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4965                 std::swap(LHS, RHS);
4966             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4967               std::swap(LHS, RHS);
4968             }
4969             Left.push_back(LHS);
4970             Right.push_back(RHS);
4971           }
4972         }
4973         TE->setOperand(0, Left);
4974         TE->setOperand(1, Right);
4975         buildTree_rec(Left, Depth + 1, {TE, 0});
4976         buildTree_rec(Right, Depth + 1, {TE, 1});
4977         return;
4978       }
4979 
4980       TE->setOperandsInOrder();
4981       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4982         ValueList Operands;
4983         // Prepare the operand vector.
4984         for (Value *V : VL)
4985           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4986 
4987         buildTree_rec(Operands, Depth + 1, {TE, i});
4988       }
4989       return;
4990     }
4991     default:
4992       BS.cancelScheduling(VL, VL0);
4993       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4994                    ReuseShuffleIndicies);
4995       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4996       return;
4997   }
4998 }
4999 
5000 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
5001   unsigned N = 1;
5002   Type *EltTy = T;
5003 
5004   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
5005          isa<VectorType>(EltTy)) {
5006     if (auto *ST = dyn_cast<StructType>(EltTy)) {
5007       // Check that struct is homogeneous.
5008       for (const auto *Ty : ST->elements())
5009         if (Ty != *ST->element_begin())
5010           return 0;
5011       N *= ST->getNumElements();
5012       EltTy = *ST->element_begin();
5013     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
5014       N *= AT->getNumElements();
5015       EltTy = AT->getElementType();
5016     } else {
5017       auto *VT = cast<FixedVectorType>(EltTy);
5018       N *= VT->getNumElements();
5019       EltTy = VT->getElementType();
5020     }
5021   }
5022 
5023   if (!isValidElementType(EltTy))
5024     return 0;
5025   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
5026   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
5027     return 0;
5028   return N;
5029 }
5030 
5031 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
5032                               SmallVectorImpl<unsigned> &CurrentOrder) const {
5033   const auto *It = find_if(VL, [](Value *V) {
5034     return isa<ExtractElementInst, ExtractValueInst>(V);
5035   });
5036   assert(It != VL.end() && "Expected at least one extract instruction.");
5037   auto *E0 = cast<Instruction>(*It);
5038   assert(all_of(VL,
5039                 [](Value *V) {
5040                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
5041                       V);
5042                 }) &&
5043          "Invalid opcode");
5044   // Check if all of the extracts come from the same vector and from the
5045   // correct offset.
5046   Value *Vec = E0->getOperand(0);
5047 
5048   CurrentOrder.clear();
5049 
5050   // We have to extract from a vector/aggregate with the same number of elements.
5051   unsigned NElts;
5052   if (E0->getOpcode() == Instruction::ExtractValue) {
5053     const DataLayout &DL = E0->getModule()->getDataLayout();
5054     NElts = canMapToVector(Vec->getType(), DL);
5055     if (!NElts)
5056       return false;
5057     // Check if load can be rewritten as load of vector.
5058     LoadInst *LI = dyn_cast<LoadInst>(Vec);
5059     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
5060       return false;
5061   } else {
5062     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
5063   }
5064 
5065   if (NElts != VL.size())
5066     return false;
5067 
5068   // Check that all of the indices extract from the correct offset.
5069   bool ShouldKeepOrder = true;
5070   unsigned E = VL.size();
5071   // Assign to all items the initial value E + 1 so we can check if the extract
5072   // instruction index was used already.
5073   // Also, later we can check that all the indices are used and we have a
5074   // consecutive access in the extract instructions, by checking that no
5075   // element of CurrentOrder still has value E + 1.
5076   CurrentOrder.assign(E, E);
5077   unsigned I = 0;
5078   for (; I < E; ++I) {
5079     auto *Inst = dyn_cast<Instruction>(VL[I]);
5080     if (!Inst)
5081       continue;
5082     if (Inst->getOperand(0) != Vec)
5083       break;
5084     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
5085       if (isa<UndefValue>(EE->getIndexOperand()))
5086         continue;
5087     Optional<unsigned> Idx = getExtractIndex(Inst);
5088     if (!Idx)
5089       break;
5090     const unsigned ExtIdx = *Idx;
5091     if (ExtIdx != I) {
5092       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5093         break;
5094       ShouldKeepOrder = false;
5095       CurrentOrder[ExtIdx] = I;
5096     } else {
5097       if (CurrentOrder[I] != E)
5098         break;
5099       CurrentOrder[I] = I;
5100     }
5101   }
5102   if (I < E) {
5103     CurrentOrder.clear();
5104     return false;
5105   }
5106   if (ShouldKeepOrder)
5107     CurrentOrder.clear();
5108 
5109   return ShouldKeepOrder;
5110 }
5111 
5112 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5113                                     ArrayRef<Value *> VectorizedVals) const {
5114   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5115          all_of(I->users(), [this](User *U) {
5116            return ScalarToTreeEntry.count(U) > 0 ||
5117                   isVectorLikeInstWithConstOps(U) ||
5118                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5119          });
5120 }
5121 
5122 static std::pair<InstructionCost, InstructionCost>
5123 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5124                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5125   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5126 
5127   // Calculate the cost of the scalar and vector calls.
5128   SmallVector<Type *, 4> VecTys;
5129   for (Use &Arg : CI->args())
5130     VecTys.push_back(
5131         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5132   FastMathFlags FMF;
5133   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5134     FMF = FPCI->getFastMathFlags();
5135   SmallVector<const Value *> Arguments(CI->args());
5136   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5137                                     dyn_cast<IntrinsicInst>(CI));
5138   auto IntrinsicCost =
5139     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5140 
5141   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5142                                      VecTy->getNumElements())),
5143                             false /*HasGlobalPred*/);
5144   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5145   auto LibCost = IntrinsicCost;
5146   if (!CI->isNoBuiltin() && VecFunc) {
5147     // Calculate the cost of the vector library call.
5148     // If the corresponding vector call is cheaper, return its cost.
5149     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5150                                     TTI::TCK_RecipThroughput);
5151   }
5152   return {IntrinsicCost, LibCost};
5153 }
5154 
5155 /// Compute the cost of creating a vector of type \p VecTy containing the
5156 /// extracted values from \p VL.
5157 static InstructionCost
5158 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5159                    TargetTransformInfo::ShuffleKind ShuffleKind,
5160                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5161   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5162 
5163   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5164       VecTy->getNumElements() < NumOfParts)
5165     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5166 
5167   bool AllConsecutive = true;
5168   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5169   unsigned Idx = -1;
5170   InstructionCost Cost = 0;
5171 
5172   // Process extracts in blocks of EltsPerVector to check if the source vector
5173   // operand can be re-used directly. If not, add the cost of creating a shuffle
5174   // to extract the values into a vector register.
5175   SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
5176   for (auto *V : VL) {
5177     ++Idx;
5178 
5179     // Need to exclude undefs from analysis.
5180     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5181       continue;
5182 
5183     // Reached the start of a new vector registers.
5184     if (Idx % EltsPerVector == 0) {
5185       RegMask.assign(EltsPerVector, UndefMaskElem);
5186       AllConsecutive = true;
5187       continue;
5188     }
5189 
5190     // Check all extracts for a vector register on the target directly
5191     // extract values in order.
5192     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5193     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5194       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5195       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5196                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5197       RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
5198     }
5199 
5200     if (AllConsecutive)
5201       continue;
5202 
5203     // Skip all indices, except for the last index per vector block.
5204     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5205       continue;
5206 
5207     // If we have a series of extracts which are not consecutive and hence
5208     // cannot re-use the source vector register directly, compute the shuffle
5209     // cost to extract the vector with EltsPerVector elements.
5210     Cost += TTI.getShuffleCost(
5211         TargetTransformInfo::SK_PermuteSingleSrc,
5212         FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
5213   }
5214   return Cost;
5215 }
5216 
5217 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5218 /// operations operands.
5219 static void
5220 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5221                       ArrayRef<int> ReusesIndices,
5222                       const function_ref<bool(Instruction *)> IsAltOp,
5223                       SmallVectorImpl<int> &Mask,
5224                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5225                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5226   unsigned Sz = VL.size();
5227   Mask.assign(Sz, UndefMaskElem);
5228   SmallVector<int> OrderMask;
5229   if (!ReorderIndices.empty())
5230     inversePermutation(ReorderIndices, OrderMask);
5231   for (unsigned I = 0; I < Sz; ++I) {
5232     unsigned Idx = I;
5233     if (!ReorderIndices.empty())
5234       Idx = OrderMask[I];
5235     auto *OpInst = cast<Instruction>(VL[Idx]);
5236     if (IsAltOp(OpInst)) {
5237       Mask[I] = Sz + Idx;
5238       if (AltScalars)
5239         AltScalars->push_back(OpInst);
5240     } else {
5241       Mask[I] = Idx;
5242       if (OpScalars)
5243         OpScalars->push_back(OpInst);
5244     }
5245   }
5246   if (!ReusesIndices.empty()) {
5247     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5248     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5249       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5250     });
5251     Mask.swap(NewMask);
5252   }
5253 }
5254 
5255 /// Checks if the specified instruction \p I is an alternate operation for the
5256 /// given \p MainOp and \p AltOp instructions.
5257 static bool isAlternateInstruction(const Instruction *I,
5258                                    const Instruction *MainOp,
5259                                    const Instruction *AltOp) {
5260   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5261     auto *AltCI0 = cast<CmpInst>(AltOp);
5262     auto *CI = cast<CmpInst>(I);
5263     CmpInst::Predicate P0 = CI0->getPredicate();
5264     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5265     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5266     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5267     CmpInst::Predicate CurrentPred = CI->getPredicate();
5268     if (P0 == AltP0Swapped)
5269       return I == AltCI0 ||
5270              (I != MainOp &&
5271               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5272                                    CI->getOperand(0), CI->getOperand(1)));
5273     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5274   }
5275   return I->getOpcode() == AltOp->getOpcode();
5276 }
5277 
5278 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5279                                       ArrayRef<Value *> VectorizedVals) {
5280   ArrayRef<Value*> VL = E->Scalars;
5281 
5282   Type *ScalarTy = VL[0]->getType();
5283   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5284     ScalarTy = SI->getValueOperand()->getType();
5285   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5286     ScalarTy = CI->getOperand(0)->getType();
5287   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5288     ScalarTy = IE->getOperand(1)->getType();
5289   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5290   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5291 
5292   // If we have computed a smaller type for the expression, update VecTy so
5293   // that the costs will be accurate.
5294   if (MinBWs.count(VL[0]))
5295     VecTy = FixedVectorType::get(
5296         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5297   unsigned EntryVF = E->getVectorFactor();
5298   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5299 
5300   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5301   // FIXME: it tries to fix a problem with MSVC buildbots.
5302   TargetTransformInfo &TTIRef = *TTI;
5303   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5304                                VectorizedVals, E](InstructionCost &Cost) {
5305     DenseMap<Value *, int> ExtractVectorsTys;
5306     SmallPtrSet<Value *, 4> CheckedExtracts;
5307     for (auto *V : VL) {
5308       if (isa<UndefValue>(V))
5309         continue;
5310       // If all users of instruction are going to be vectorized and this
5311       // instruction itself is not going to be vectorized, consider this
5312       // instruction as dead and remove its cost from the final cost of the
5313       // vectorized tree.
5314       // Also, avoid adjusting the cost for extractelements with multiple uses
5315       // in different graph entries.
5316       const TreeEntry *VE = getTreeEntry(V);
5317       if (!CheckedExtracts.insert(V).second ||
5318           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5319           (VE && VE != E))
5320         continue;
5321       auto *EE = cast<ExtractElementInst>(V);
5322       Optional<unsigned> EEIdx = getExtractIndex(EE);
5323       if (!EEIdx)
5324         continue;
5325       unsigned Idx = *EEIdx;
5326       if (TTIRef.getNumberOfParts(VecTy) !=
5327           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5328         auto It =
5329             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5330         It->getSecond() = std::min<int>(It->second, Idx);
5331       }
5332       // Take credit for instruction that will become dead.
5333       if (EE->hasOneUse()) {
5334         Instruction *Ext = EE->user_back();
5335         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5336             all_of(Ext->users(),
5337                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5338           // Use getExtractWithExtendCost() to calculate the cost of
5339           // extractelement/ext pair.
5340           Cost -=
5341               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5342                                               EE->getVectorOperandType(), Idx);
5343           // Add back the cost of s|zext which is subtracted separately.
5344           Cost += TTIRef.getCastInstrCost(
5345               Ext->getOpcode(), Ext->getType(), EE->getType(),
5346               TTI::getCastContextHint(Ext), CostKind, Ext);
5347           continue;
5348         }
5349       }
5350       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5351                                         EE->getVectorOperandType(), Idx);
5352     }
5353     // Add a cost for subvector extracts/inserts if required.
5354     for (const auto &Data : ExtractVectorsTys) {
5355       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5356       unsigned NumElts = VecTy->getNumElements();
5357       if (Data.second % NumElts == 0)
5358         continue;
5359       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5360         unsigned Idx = (Data.second / NumElts) * NumElts;
5361         unsigned EENumElts = EEVTy->getNumElements();
5362         if (Idx + NumElts <= EENumElts) {
5363           Cost +=
5364               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5365                                     EEVTy, None, Idx, VecTy);
5366         } else {
5367           // Need to round up the subvector type vectorization factor to avoid a
5368           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5369           // <= EENumElts.
5370           auto *SubVT =
5371               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5372           Cost +=
5373               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5374                                     EEVTy, None, Idx, SubVT);
5375         }
5376       } else {
5377         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5378                                       VecTy, None, 0, EEVTy);
5379       }
5380     }
5381   };
5382   if (E->State == TreeEntry::NeedToGather) {
5383     if (allConstant(VL))
5384       return 0;
5385     if (isa<InsertElementInst>(VL[0]))
5386       return InstructionCost::getInvalid();
5387     SmallVector<int> Mask;
5388     SmallVector<const TreeEntry *> Entries;
5389     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5390         isGatherShuffledEntry(E, Mask, Entries);
5391     if (Shuffle.hasValue()) {
5392       InstructionCost GatherCost = 0;
5393       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5394         // Perfect match in the graph, will reuse the previously vectorized
5395         // node. Cost is 0.
5396         LLVM_DEBUG(
5397             dbgs()
5398             << "SLP: perfect diamond match for gather bundle that starts with "
5399             << *VL.front() << ".\n");
5400         if (NeedToShuffleReuses)
5401           GatherCost =
5402               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5403                                   FinalVecTy, E->ReuseShuffleIndices);
5404       } else {
5405         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5406                           << " entries for bundle that starts with "
5407                           << *VL.front() << ".\n");
5408         // Detected that instead of gather we can emit a shuffle of single/two
5409         // previously vectorized nodes. Add the cost of the permutation rather
5410         // than gather.
5411         ::addMask(Mask, E->ReuseShuffleIndices);
5412         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5413       }
5414       return GatherCost;
5415     }
5416     if ((E->getOpcode() == Instruction::ExtractElement ||
5417          all_of(E->Scalars,
5418                 [](Value *V) {
5419                   return isa<ExtractElementInst, UndefValue>(V);
5420                 })) &&
5421         allSameType(VL)) {
5422       // Check that gather of extractelements can be represented as just a
5423       // shuffle of a single/two vectors the scalars are extracted from.
5424       SmallVector<int> Mask;
5425       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5426           isFixedVectorShuffle(VL, Mask);
5427       if (ShuffleKind.hasValue()) {
5428         // Found the bunch of extractelement instructions that must be gathered
5429         // into a vector and can be represented as a permutation elements in a
5430         // single input vector or of 2 input vectors.
5431         InstructionCost Cost =
5432             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5433         AdjustExtractsCost(Cost);
5434         if (NeedToShuffleReuses)
5435           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5436                                       FinalVecTy, E->ReuseShuffleIndices);
5437         return Cost;
5438       }
5439     }
5440     if (isSplat(VL)) {
5441       // Found the broadcasting of the single scalar, calculate the cost as the
5442       // broadcast.
5443       assert(VecTy == FinalVecTy &&
5444              "No reused scalars expected for broadcast.");
5445       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5446                                  /*Mask=*/None, /*Index=*/0,
5447                                  /*SubTp=*/nullptr, /*Args=*/VL[0]);
5448     }
5449     InstructionCost ReuseShuffleCost = 0;
5450     if (NeedToShuffleReuses)
5451       ReuseShuffleCost = TTI->getShuffleCost(
5452           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5453     // Improve gather cost for gather of loads, if we can group some of the
5454     // loads into vector loads.
5455     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5456         !E->isAltShuffle()) {
5457       BoUpSLP::ValueSet VectorizedLoads;
5458       unsigned StartIdx = 0;
5459       unsigned VF = VL.size() / 2;
5460       unsigned VectorizedCnt = 0;
5461       unsigned ScatterVectorizeCnt = 0;
5462       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5463       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5464         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5465              Cnt += VF) {
5466           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5467           if (!VectorizedLoads.count(Slice.front()) &&
5468               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5469             SmallVector<Value *> PointerOps;
5470             OrdersType CurrentOrder;
5471             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5472                                               *SE, CurrentOrder, PointerOps);
5473             switch (LS) {
5474             case LoadsState::Vectorize:
5475             case LoadsState::ScatterVectorize:
5476               // Mark the vectorized loads so that we don't vectorize them
5477               // again.
5478               if (LS == LoadsState::Vectorize)
5479                 ++VectorizedCnt;
5480               else
5481                 ++ScatterVectorizeCnt;
5482               VectorizedLoads.insert(Slice.begin(), Slice.end());
5483               // If we vectorized initial block, no need to try to vectorize it
5484               // again.
5485               if (Cnt == StartIdx)
5486                 StartIdx += VF;
5487               break;
5488             case LoadsState::Gather:
5489               break;
5490             }
5491           }
5492         }
5493         // Check if the whole array was vectorized already - exit.
5494         if (StartIdx >= VL.size())
5495           break;
5496         // Found vectorizable parts - exit.
5497         if (!VectorizedLoads.empty())
5498           break;
5499       }
5500       if (!VectorizedLoads.empty()) {
5501         InstructionCost GatherCost = 0;
5502         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5503         bool NeedInsertSubvectorAnalysis =
5504             !NumParts || (VL.size() / VF) > NumParts;
5505         // Get the cost for gathered loads.
5506         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5507           if (VectorizedLoads.contains(VL[I]))
5508             continue;
5509           GatherCost += getGatherCost(VL.slice(I, VF));
5510         }
5511         // The cost for vectorized loads.
5512         InstructionCost ScalarsCost = 0;
5513         for (Value *V : VectorizedLoads) {
5514           auto *LI = cast<LoadInst>(V);
5515           ScalarsCost += TTI->getMemoryOpCost(
5516               Instruction::Load, LI->getType(), LI->getAlign(),
5517               LI->getPointerAddressSpace(), CostKind, LI);
5518         }
5519         auto *LI = cast<LoadInst>(E->getMainOp());
5520         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5521         Align Alignment = LI->getAlign();
5522         GatherCost +=
5523             VectorizedCnt *
5524             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5525                                  LI->getPointerAddressSpace(), CostKind, LI);
5526         GatherCost += ScatterVectorizeCnt *
5527                       TTI->getGatherScatterOpCost(
5528                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5529                           /*VariableMask=*/false, Alignment, CostKind, LI);
5530         if (NeedInsertSubvectorAnalysis) {
5531           // Add the cost for the subvectors insert.
5532           for (int I = VF, E = VL.size(); I < E; I += VF)
5533             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5534                                               None, I, LoadTy);
5535         }
5536         return ReuseShuffleCost + GatherCost - ScalarsCost;
5537       }
5538     }
5539     return ReuseShuffleCost + getGatherCost(VL);
5540   }
5541   InstructionCost CommonCost = 0;
5542   SmallVector<int> Mask;
5543   if (!E->ReorderIndices.empty()) {
5544     SmallVector<int> NewMask;
5545     if (E->getOpcode() == Instruction::Store) {
5546       // For stores the order is actually a mask.
5547       NewMask.resize(E->ReorderIndices.size());
5548       copy(E->ReorderIndices, NewMask.begin());
5549     } else {
5550       inversePermutation(E->ReorderIndices, NewMask);
5551     }
5552     ::addMask(Mask, NewMask);
5553   }
5554   if (NeedToShuffleReuses)
5555     ::addMask(Mask, E->ReuseShuffleIndices);
5556   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5557     CommonCost =
5558         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5559   assert((E->State == TreeEntry::Vectorize ||
5560           E->State == TreeEntry::ScatterVectorize) &&
5561          "Unhandled state");
5562   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5563   Instruction *VL0 = E->getMainOp();
5564   unsigned ShuffleOrOp =
5565       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5566   switch (ShuffleOrOp) {
5567     case Instruction::PHI:
5568       return 0;
5569 
5570     case Instruction::ExtractValue:
5571     case Instruction::ExtractElement: {
5572       // The common cost of removal ExtractElement/ExtractValue instructions +
5573       // the cost of shuffles, if required to resuffle the original vector.
5574       if (NeedToShuffleReuses) {
5575         unsigned Idx = 0;
5576         for (unsigned I : E->ReuseShuffleIndices) {
5577           if (ShuffleOrOp == Instruction::ExtractElement) {
5578             auto *EE = cast<ExtractElementInst>(VL[I]);
5579             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5580                                                   EE->getVectorOperandType(),
5581                                                   *getExtractIndex(EE));
5582           } else {
5583             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5584                                                   VecTy, Idx);
5585             ++Idx;
5586           }
5587         }
5588         Idx = EntryVF;
5589         for (Value *V : VL) {
5590           if (ShuffleOrOp == Instruction::ExtractElement) {
5591             auto *EE = cast<ExtractElementInst>(V);
5592             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5593                                                   EE->getVectorOperandType(),
5594                                                   *getExtractIndex(EE));
5595           } else {
5596             --Idx;
5597             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5598                                                   VecTy, Idx);
5599           }
5600         }
5601       }
5602       if (ShuffleOrOp == Instruction::ExtractValue) {
5603         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5604           auto *EI = cast<Instruction>(VL[I]);
5605           // Take credit for instruction that will become dead.
5606           if (EI->hasOneUse()) {
5607             Instruction *Ext = EI->user_back();
5608             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5609                 all_of(Ext->users(),
5610                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5611               // Use getExtractWithExtendCost() to calculate the cost of
5612               // extractelement/ext pair.
5613               CommonCost -= TTI->getExtractWithExtendCost(
5614                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5615               // Add back the cost of s|zext which is subtracted separately.
5616               CommonCost += TTI->getCastInstrCost(
5617                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5618                   TTI::getCastContextHint(Ext), CostKind, Ext);
5619               continue;
5620             }
5621           }
5622           CommonCost -=
5623               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5624         }
5625       } else {
5626         AdjustExtractsCost(CommonCost);
5627       }
5628       return CommonCost;
5629     }
5630     case Instruction::InsertElement: {
5631       assert(E->ReuseShuffleIndices.empty() &&
5632              "Unique insertelements only are expected.");
5633       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5634 
5635       unsigned const NumElts = SrcVecTy->getNumElements();
5636       unsigned const NumScalars = VL.size();
5637       APInt DemandedElts = APInt::getZero(NumElts);
5638       // TODO: Add support for Instruction::InsertValue.
5639       SmallVector<int> Mask;
5640       if (!E->ReorderIndices.empty()) {
5641         inversePermutation(E->ReorderIndices, Mask);
5642         Mask.append(NumElts - NumScalars, UndefMaskElem);
5643       } else {
5644         Mask.assign(NumElts, UndefMaskElem);
5645         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5646       }
5647       unsigned Offset = *getInsertIndex(VL0);
5648       bool IsIdentity = true;
5649       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5650       Mask.swap(PrevMask);
5651       for (unsigned I = 0; I < NumScalars; ++I) {
5652         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5653         DemandedElts.setBit(InsertIdx);
5654         IsIdentity &= InsertIdx - Offset == I;
5655         Mask[InsertIdx - Offset] = I;
5656       }
5657       assert(Offset < NumElts && "Failed to find vector index offset");
5658 
5659       InstructionCost Cost = 0;
5660       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5661                                             /*Insert*/ true, /*Extract*/ false);
5662 
5663       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5664         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5665         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5666         Cost += TTI->getShuffleCost(
5667             TargetTransformInfo::SK_PermuteSingleSrc,
5668             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5669       } else if (!IsIdentity) {
5670         auto *FirstInsert =
5671             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5672               return !is_contained(E->Scalars,
5673                                    cast<Instruction>(V)->getOperand(0));
5674             }));
5675         if (isUndefVector(FirstInsert->getOperand(0))) {
5676           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5677         } else {
5678           SmallVector<int> InsertMask(NumElts);
5679           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5680           for (unsigned I = 0; I < NumElts; I++) {
5681             if (Mask[I] != UndefMaskElem)
5682               InsertMask[Offset + I] = NumElts + I;
5683           }
5684           Cost +=
5685               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5686         }
5687       }
5688 
5689       return Cost;
5690     }
5691     case Instruction::ZExt:
5692     case Instruction::SExt:
5693     case Instruction::FPToUI:
5694     case Instruction::FPToSI:
5695     case Instruction::FPExt:
5696     case Instruction::PtrToInt:
5697     case Instruction::IntToPtr:
5698     case Instruction::SIToFP:
5699     case Instruction::UIToFP:
5700     case Instruction::Trunc:
5701     case Instruction::FPTrunc:
5702     case Instruction::BitCast: {
5703       Type *SrcTy = VL0->getOperand(0)->getType();
5704       InstructionCost ScalarEltCost =
5705           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5706                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5707       if (NeedToShuffleReuses) {
5708         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5709       }
5710 
5711       // Calculate the cost of this instruction.
5712       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5713 
5714       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5715       InstructionCost VecCost = 0;
5716       // Check if the values are candidates to demote.
5717       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5718         VecCost = CommonCost + TTI->getCastInstrCost(
5719                                    E->getOpcode(), VecTy, SrcVecTy,
5720                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5721       }
5722       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5723       return VecCost - ScalarCost;
5724     }
5725     case Instruction::FCmp:
5726     case Instruction::ICmp:
5727     case Instruction::Select: {
5728       // Calculate the cost of this instruction.
5729       InstructionCost ScalarEltCost =
5730           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5731                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5732       if (NeedToShuffleReuses) {
5733         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5734       }
5735       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5736       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5737 
5738       // Check if all entries in VL are either compares or selects with compares
5739       // as condition that have the same predicates.
5740       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5741       bool First = true;
5742       for (auto *V : VL) {
5743         CmpInst::Predicate CurrentPred;
5744         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5745         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5746              !match(V, MatchCmp)) ||
5747             (!First && VecPred != CurrentPred)) {
5748           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5749           break;
5750         }
5751         First = false;
5752         VecPred = CurrentPred;
5753       }
5754 
5755       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5756           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5757       // Check if it is possible and profitable to use min/max for selects in
5758       // VL.
5759       //
5760       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5761       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5762         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5763                                           {VecTy, VecTy});
5764         InstructionCost IntrinsicCost =
5765             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5766         // If the selects are the only uses of the compares, they will be dead
5767         // and we can adjust the cost by removing their cost.
5768         if (IntrinsicAndUse.second)
5769           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5770                                                    MaskTy, VecPred, CostKind);
5771         VecCost = std::min(VecCost, IntrinsicCost);
5772       }
5773       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5774       return CommonCost + VecCost - ScalarCost;
5775     }
5776     case Instruction::FNeg:
5777     case Instruction::Add:
5778     case Instruction::FAdd:
5779     case Instruction::Sub:
5780     case Instruction::FSub:
5781     case Instruction::Mul:
5782     case Instruction::FMul:
5783     case Instruction::UDiv:
5784     case Instruction::SDiv:
5785     case Instruction::FDiv:
5786     case Instruction::URem:
5787     case Instruction::SRem:
5788     case Instruction::FRem:
5789     case Instruction::Shl:
5790     case Instruction::LShr:
5791     case Instruction::AShr:
5792     case Instruction::And:
5793     case Instruction::Or:
5794     case Instruction::Xor: {
5795       // Certain instructions can be cheaper to vectorize if they have a
5796       // constant second vector operand.
5797       TargetTransformInfo::OperandValueKind Op1VK =
5798           TargetTransformInfo::OK_AnyValue;
5799       TargetTransformInfo::OperandValueKind Op2VK =
5800           TargetTransformInfo::OK_UniformConstantValue;
5801       TargetTransformInfo::OperandValueProperties Op1VP =
5802           TargetTransformInfo::OP_None;
5803       TargetTransformInfo::OperandValueProperties Op2VP =
5804           TargetTransformInfo::OP_PowerOf2;
5805 
5806       // If all operands are exactly the same ConstantInt then set the
5807       // operand kind to OK_UniformConstantValue.
5808       // If instead not all operands are constants, then set the operand kind
5809       // to OK_AnyValue. If all operands are constants but not the same,
5810       // then set the operand kind to OK_NonUniformConstantValue.
5811       ConstantInt *CInt0 = nullptr;
5812       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5813         const Instruction *I = cast<Instruction>(VL[i]);
5814         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5815         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5816         if (!CInt) {
5817           Op2VK = TargetTransformInfo::OK_AnyValue;
5818           Op2VP = TargetTransformInfo::OP_None;
5819           break;
5820         }
5821         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5822             !CInt->getValue().isPowerOf2())
5823           Op2VP = TargetTransformInfo::OP_None;
5824         if (i == 0) {
5825           CInt0 = CInt;
5826           continue;
5827         }
5828         if (CInt0 != CInt)
5829           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5830       }
5831 
5832       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5833       InstructionCost ScalarEltCost =
5834           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5835                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5836       if (NeedToShuffleReuses) {
5837         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5838       }
5839       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5840       InstructionCost VecCost =
5841           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5842                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5843       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5844       return CommonCost + VecCost - ScalarCost;
5845     }
5846     case Instruction::GetElementPtr: {
5847       TargetTransformInfo::OperandValueKind Op1VK =
5848           TargetTransformInfo::OK_AnyValue;
5849       TargetTransformInfo::OperandValueKind Op2VK =
5850           TargetTransformInfo::OK_UniformConstantValue;
5851 
5852       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5853           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5854       if (NeedToShuffleReuses) {
5855         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5856       }
5857       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5858       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5859           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5860       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5861       return CommonCost + VecCost - ScalarCost;
5862     }
5863     case Instruction::Load: {
5864       // Cost of wide load - cost of scalar loads.
5865       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5866       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5867           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5868       if (NeedToShuffleReuses) {
5869         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5870       }
5871       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5872       InstructionCost VecLdCost;
5873       if (E->State == TreeEntry::Vectorize) {
5874         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5875                                          CostKind, VL0);
5876       } else {
5877         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5878         Align CommonAlignment = Alignment;
5879         for (Value *V : VL)
5880           CommonAlignment =
5881               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5882         VecLdCost = TTI->getGatherScatterOpCost(
5883             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5884             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5885       }
5886       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5887       return CommonCost + VecLdCost - ScalarLdCost;
5888     }
5889     case Instruction::Store: {
5890       // We know that we can merge the stores. Calculate the cost.
5891       bool IsReorder = !E->ReorderIndices.empty();
5892       auto *SI =
5893           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5894       Align Alignment = SI->getAlign();
5895       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5896           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5897       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5898       InstructionCost VecStCost = TTI->getMemoryOpCost(
5899           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5900       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5901       return CommonCost + VecStCost - ScalarStCost;
5902     }
5903     case Instruction::Call: {
5904       CallInst *CI = cast<CallInst>(VL0);
5905       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5906 
5907       // Calculate the cost of the scalar and vector calls.
5908       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5909       InstructionCost ScalarEltCost =
5910           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5911       if (NeedToShuffleReuses) {
5912         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5913       }
5914       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5915 
5916       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5917       InstructionCost VecCallCost =
5918           std::min(VecCallCosts.first, VecCallCosts.second);
5919 
5920       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5921                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5922                         << " for " << *CI << "\n");
5923 
5924       return CommonCost + VecCallCost - ScalarCallCost;
5925     }
5926     case Instruction::ShuffleVector: {
5927       assert(E->isAltShuffle() &&
5928              ((Instruction::isBinaryOp(E->getOpcode()) &&
5929                Instruction::isBinaryOp(E->getAltOpcode())) ||
5930               (Instruction::isCast(E->getOpcode()) &&
5931                Instruction::isCast(E->getAltOpcode())) ||
5932               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5933              "Invalid Shuffle Vector Operand");
5934       InstructionCost ScalarCost = 0;
5935       if (NeedToShuffleReuses) {
5936         for (unsigned Idx : E->ReuseShuffleIndices) {
5937           Instruction *I = cast<Instruction>(VL[Idx]);
5938           CommonCost -= TTI->getInstructionCost(I, CostKind);
5939         }
5940         for (Value *V : VL) {
5941           Instruction *I = cast<Instruction>(V);
5942           CommonCost += TTI->getInstructionCost(I, CostKind);
5943         }
5944       }
5945       for (Value *V : VL) {
5946         Instruction *I = cast<Instruction>(V);
5947         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5948         ScalarCost += TTI->getInstructionCost(I, CostKind);
5949       }
5950       // VecCost is equal to sum of the cost of creating 2 vectors
5951       // and the cost of creating shuffle.
5952       InstructionCost VecCost = 0;
5953       // Try to find the previous shuffle node with the same operands and same
5954       // main/alternate ops.
5955       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5956         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5957           if (TE.get() == E)
5958             break;
5959           if (TE->isAltShuffle() &&
5960               ((TE->getOpcode() == E->getOpcode() &&
5961                 TE->getAltOpcode() == E->getAltOpcode()) ||
5962                (TE->getOpcode() == E->getAltOpcode() &&
5963                 TE->getAltOpcode() == E->getOpcode())) &&
5964               TE->hasEqualOperands(*E))
5965             return true;
5966         }
5967         return false;
5968       };
5969       if (TryFindNodeWithEqualOperands()) {
5970         LLVM_DEBUG({
5971           dbgs() << "SLP: diamond match for alternate node found.\n";
5972           E->dump();
5973         });
5974         // No need to add new vector costs here since we're going to reuse
5975         // same main/alternate vector ops, just do different shuffling.
5976       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5977         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5978         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5979                                                CostKind);
5980       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5981         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5982                                           Builder.getInt1Ty(),
5983                                           CI0->getPredicate(), CostKind, VL0);
5984         VecCost += TTI->getCmpSelInstrCost(
5985             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5986             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5987             E->getAltOp());
5988       } else {
5989         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5990         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5991         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5992         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5993         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5994                                         TTI::CastContextHint::None, CostKind);
5995         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5996                                          TTI::CastContextHint::None, CostKind);
5997       }
5998 
5999       if (E->ReuseShuffleIndices.empty()) {
6000         CommonCost =
6001             TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
6002       } else {
6003         SmallVector<int> Mask;
6004         buildShuffleEntryMask(
6005             E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6006             [E](Instruction *I) {
6007               assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6008               return I->getOpcode() == E->getAltOpcode();
6009             },
6010             Mask);
6011         CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
6012                                          FinalVecTy, Mask);
6013       }
6014       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
6015       return CommonCost + VecCost - ScalarCost;
6016     }
6017     default:
6018       llvm_unreachable("Unknown instruction");
6019   }
6020 }
6021 
6022 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
6023   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
6024                     << VectorizableTree.size() << " is fully vectorizable .\n");
6025 
6026   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
6027     SmallVector<int> Mask;
6028     return TE->State == TreeEntry::NeedToGather &&
6029            !any_of(TE->Scalars,
6030                    [this](Value *V) { return EphValues.contains(V); }) &&
6031            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
6032             TE->Scalars.size() < Limit ||
6033             ((TE->getOpcode() == Instruction::ExtractElement ||
6034               all_of(TE->Scalars,
6035                      [](Value *V) {
6036                        return isa<ExtractElementInst, UndefValue>(V);
6037                      })) &&
6038              isFixedVectorShuffle(TE->Scalars, Mask)) ||
6039             (TE->State == TreeEntry::NeedToGather &&
6040              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
6041   };
6042 
6043   // We only handle trees of heights 1 and 2.
6044   if (VectorizableTree.size() == 1 &&
6045       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
6046        (ForReduction &&
6047         AreVectorizableGathers(VectorizableTree[0].get(),
6048                                VectorizableTree[0]->Scalars.size()) &&
6049         VectorizableTree[0]->getVectorFactor() > 2)))
6050     return true;
6051 
6052   if (VectorizableTree.size() != 2)
6053     return false;
6054 
6055   // Handle splat and all-constants stores. Also try to vectorize tiny trees
6056   // with the second gather nodes if they have less scalar operands rather than
6057   // the initial tree element (may be profitable to shuffle the second gather)
6058   // or they are extractelements, which form shuffle.
6059   SmallVector<int> Mask;
6060   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
6061       AreVectorizableGathers(VectorizableTree[1].get(),
6062                              VectorizableTree[0]->Scalars.size()))
6063     return true;
6064 
6065   // Gathering cost would be too much for tiny trees.
6066   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
6067       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
6068        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
6069     return false;
6070 
6071   return true;
6072 }
6073 
6074 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
6075                                        TargetTransformInfo *TTI,
6076                                        bool MustMatchOrInst) {
6077   // Look past the root to find a source value. Arbitrarily follow the
6078   // path through operand 0 of any 'or'. Also, peek through optional
6079   // shift-left-by-multiple-of-8-bits.
6080   Value *ZextLoad = Root;
6081   const APInt *ShAmtC;
6082   bool FoundOr = false;
6083   while (!isa<ConstantExpr>(ZextLoad) &&
6084          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
6085           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
6086            ShAmtC->urem(8) == 0))) {
6087     auto *BinOp = cast<BinaryOperator>(ZextLoad);
6088     ZextLoad = BinOp->getOperand(0);
6089     if (BinOp->getOpcode() == Instruction::Or)
6090       FoundOr = true;
6091   }
6092   // Check if the input is an extended load of the required or/shift expression.
6093   Value *Load;
6094   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
6095       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
6096     return false;
6097 
6098   // Require that the total load bit width is a legal integer type.
6099   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6100   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6101   Type *SrcTy = Load->getType();
6102   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6103   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6104     return false;
6105 
6106   // Everything matched - assume that we can fold the whole sequence using
6107   // load combining.
6108   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6109              << *(cast<Instruction>(Root)) << "\n");
6110 
6111   return true;
6112 }
6113 
6114 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6115   if (RdxKind != RecurKind::Or)
6116     return false;
6117 
6118   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6119   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6120   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6121                                     /* MatchOr */ false);
6122 }
6123 
6124 bool BoUpSLP::isLoadCombineCandidate() const {
6125   // Peek through a final sequence of stores and check if all operations are
6126   // likely to be load-combined.
6127   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6128   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6129     Value *X;
6130     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6131         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6132       return false;
6133   }
6134   return true;
6135 }
6136 
6137 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6138   // No need to vectorize inserts of gathered values.
6139   if (VectorizableTree.size() == 2 &&
6140       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6141       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6142     return true;
6143 
6144   // We can vectorize the tree if its size is greater than or equal to the
6145   // minimum size specified by the MinTreeSize command line option.
6146   if (VectorizableTree.size() >= MinTreeSize)
6147     return false;
6148 
6149   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6150   // can vectorize it if we can prove it fully vectorizable.
6151   if (isFullyVectorizableTinyTree(ForReduction))
6152     return false;
6153 
6154   assert(VectorizableTree.empty()
6155              ? ExternalUses.empty()
6156              : true && "We shouldn't have any external users");
6157 
6158   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6159   // vectorizable.
6160   return true;
6161 }
6162 
6163 InstructionCost BoUpSLP::getSpillCost() const {
6164   // Walk from the bottom of the tree to the top, tracking which values are
6165   // live. When we see a call instruction that is not part of our tree,
6166   // query TTI to see if there is a cost to keeping values live over it
6167   // (for example, if spills and fills are required).
6168   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6169   InstructionCost Cost = 0;
6170 
6171   SmallPtrSet<Instruction*, 4> LiveValues;
6172   Instruction *PrevInst = nullptr;
6173 
6174   // The entries in VectorizableTree are not necessarily ordered by their
6175   // position in basic blocks. Collect them and order them by dominance so later
6176   // instructions are guaranteed to be visited first. For instructions in
6177   // different basic blocks, we only scan to the beginning of the block, so
6178   // their order does not matter, as long as all instructions in a basic block
6179   // are grouped together. Using dominance ensures a deterministic order.
6180   SmallVector<Instruction *, 16> OrderedScalars;
6181   for (const auto &TEPtr : VectorizableTree) {
6182     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6183     if (!Inst)
6184       continue;
6185     OrderedScalars.push_back(Inst);
6186   }
6187   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6188     auto *NodeA = DT->getNode(A->getParent());
6189     auto *NodeB = DT->getNode(B->getParent());
6190     assert(NodeA && "Should only process reachable instructions");
6191     assert(NodeB && "Should only process reachable instructions");
6192     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6193            "Different nodes should have different DFS numbers");
6194     if (NodeA != NodeB)
6195       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6196     return B->comesBefore(A);
6197   });
6198 
6199   for (Instruction *Inst : OrderedScalars) {
6200     if (!PrevInst) {
6201       PrevInst = Inst;
6202       continue;
6203     }
6204 
6205     // Update LiveValues.
6206     LiveValues.erase(PrevInst);
6207     for (auto &J : PrevInst->operands()) {
6208       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6209         LiveValues.insert(cast<Instruction>(&*J));
6210     }
6211 
6212     LLVM_DEBUG({
6213       dbgs() << "SLP: #LV: " << LiveValues.size();
6214       for (auto *X : LiveValues)
6215         dbgs() << " " << X->getName();
6216       dbgs() << ", Looking at ";
6217       Inst->dump();
6218     });
6219 
6220     // Now find the sequence of instructions between PrevInst and Inst.
6221     unsigned NumCalls = 0;
6222     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6223                                  PrevInstIt =
6224                                      PrevInst->getIterator().getReverse();
6225     while (InstIt != PrevInstIt) {
6226       if (PrevInstIt == PrevInst->getParent()->rend()) {
6227         PrevInstIt = Inst->getParent()->rbegin();
6228         continue;
6229       }
6230 
6231       // Debug information does not impact spill cost.
6232       if ((isa<CallInst>(&*PrevInstIt) &&
6233            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6234           &*PrevInstIt != PrevInst)
6235         NumCalls++;
6236 
6237       ++PrevInstIt;
6238     }
6239 
6240     if (NumCalls) {
6241       SmallVector<Type*, 4> V;
6242       for (auto *II : LiveValues) {
6243         auto *ScalarTy = II->getType();
6244         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6245           ScalarTy = VectorTy->getElementType();
6246         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6247       }
6248       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6249     }
6250 
6251     PrevInst = Inst;
6252   }
6253 
6254   return Cost;
6255 }
6256 
6257 /// Check if two insertelement instructions are from the same buildvector.
6258 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6259                                             InsertElementInst *V) {
6260   // Instructions must be from the same basic blocks.
6261   if (VU->getParent() != V->getParent())
6262     return false;
6263   // Checks if 2 insertelements are from the same buildvector.
6264   if (VU->getType() != V->getType())
6265     return false;
6266   // Multiple used inserts are separate nodes.
6267   if (!VU->hasOneUse() && !V->hasOneUse())
6268     return false;
6269   auto *IE1 = VU;
6270   auto *IE2 = V;
6271   // Go through the vector operand of insertelement instructions trying to find
6272   // either VU as the original vector for IE2 or V as the original vector for
6273   // IE1.
6274   do {
6275     if (IE2 == VU || IE1 == V)
6276       return true;
6277     if (IE1) {
6278       if (IE1 != VU && !IE1->hasOneUse())
6279         IE1 = nullptr;
6280       else
6281         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6282     }
6283     if (IE2) {
6284       if (IE2 != V && !IE2->hasOneUse())
6285         IE2 = nullptr;
6286       else
6287         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6288     }
6289   } while (IE1 || IE2);
6290   return false;
6291 }
6292 
6293 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
6294 /// buildvector sequence.
6295 static bool isFirstInsertElement(const InsertElementInst *IE1,
6296                                  const InsertElementInst *IE2) {
6297   const auto *I1 = IE1;
6298   const auto *I2 = IE2;
6299   do {
6300     if (I2 == IE1)
6301       return true;
6302     if (I1 == IE2)
6303       return false;
6304     if (I1)
6305       I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
6306     if (I2)
6307       I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
6308   } while (I1 || I2);
6309   llvm_unreachable("Two different buildvectors not expected.");
6310 }
6311 
6312 /// Does the analysis of the provided shuffle masks and performs the requested
6313 /// actions on the vectors with the given shuffle masks. It tries to do it in
6314 /// several steps.
6315 /// 1. If the Base vector is not undef vector, resizing the very first mask to
6316 /// have common VF and perform action for 2 input vectors (including non-undef
6317 /// Base). Other shuffle masks are combined with the resulting after the 1 stage
6318 /// and processed as a shuffle of 2 elements.
6319 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
6320 /// action only for 1 vector with the given mask, if it is not the identity
6321 /// mask.
6322 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
6323 /// vectors, combing the masks properly between the steps.
6324 template <typename T>
6325 static T *performExtractsShuffleAction(
6326     MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
6327     function_ref<unsigned(T *)> GetVF,
6328     function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction,
6329     function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
6330   assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
6331   SmallVector<int> Mask(ShuffleMask.begin()->second);
6332   auto VMIt = std::next(ShuffleMask.begin());
6333   T *Prev = nullptr;
6334   bool IsBaseNotUndef = !isUndefVector(Base);
6335   if (IsBaseNotUndef) {
6336     // Base is not undef, need to combine it with the next subvectors.
6337     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6338     for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
6339       if (Mask[Idx] == UndefMaskElem)
6340         Mask[Idx] = Idx;
6341       else
6342         Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
6343     }
6344     Prev = Action(Mask, {nullptr, Res.first});
6345   } else if (ShuffleMask.size() == 1) {
6346     // Base is undef and only 1 vector is shuffled - perform the action only for
6347     // single vector, if the mask is not the identity mask.
6348     std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask);
6349     if (Res.second)
6350       // Identity mask is found.
6351       Prev = Res.first;
6352     else
6353       Prev = Action(Mask, {ShuffleMask.begin()->first});
6354   } else {
6355     // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
6356     // shuffles step by step, combining shuffle between the steps.
6357     unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
6358     unsigned Vec2VF = GetVF(VMIt->first);
6359     if (Vec1VF == Vec2VF) {
6360       // No need to resize the input vectors since they are of the same size, we
6361       // can shuffle them directly.
6362       ArrayRef<int> SecMask = VMIt->second;
6363       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6364         if (SecMask[I] != UndefMaskElem) {
6365           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6366           Mask[I] = SecMask[I] + Vec1VF;
6367         }
6368       }
6369       Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
6370     } else {
6371       // Vectors of different sizes - resize and reshuffle.
6372       std::pair<T *, bool> Res1 =
6373           ResizeAction(ShuffleMask.begin()->first, Mask);
6374       std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second);
6375       ArrayRef<int> SecMask = VMIt->second;
6376       for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6377         if (Mask[I] != UndefMaskElem) {
6378           assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
6379           if (Res1.second)
6380             Mask[I] = I;
6381         } else if (SecMask[I] != UndefMaskElem) {
6382           assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
6383           Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
6384         }
6385       }
6386       Prev = Action(Mask, {Res1.first, Res2.first});
6387     }
6388     VMIt = std::next(VMIt);
6389   }
6390   // Perform requested actions for the remaining masks/vectors.
6391   for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
6392     // Shuffle other input vectors, if any.
6393     std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second);
6394     ArrayRef<int> SecMask = VMIt->second;
6395     for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
6396       if (SecMask[I] != UndefMaskElem) {
6397         assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
6398                "Multiple uses of scalars.");
6399         Mask[I] = (Res.second ? I : SecMask[I]) + VF;
6400       } else if (Mask[I] != UndefMaskElem) {
6401         Mask[I] = I;
6402       }
6403     }
6404     Prev = Action(Mask, {Prev, Res.first});
6405   }
6406   return Prev;
6407 }
6408 
6409 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6410   InstructionCost Cost = 0;
6411   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6412                     << VectorizableTree.size() << ".\n");
6413 
6414   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6415 
6416   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6417     TreeEntry &TE = *VectorizableTree[I];
6418 
6419     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6420     Cost += C;
6421     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6422                       << " for bundle that starts with " << *TE.Scalars[0]
6423                       << ".\n"
6424                       << "SLP: Current total cost = " << Cost << "\n");
6425   }
6426 
6427   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6428   InstructionCost ExtractCost = 0;
6429   SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
6430   SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
6431   SmallVector<APInt> DemandedElts;
6432   for (ExternalUser &EU : ExternalUses) {
6433     // We only add extract cost once for the same scalar.
6434     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6435         !ExtractCostCalculated.insert(EU.Scalar).second)
6436       continue;
6437 
6438     // Uses by ephemeral values are free (because the ephemeral value will be
6439     // removed prior to code generation, and so the extraction will be
6440     // removed as well).
6441     if (EphValues.count(EU.User))
6442       continue;
6443 
6444     // No extract cost for vector "scalar"
6445     if (isa<FixedVectorType>(EU.Scalar->getType()))
6446       continue;
6447 
6448     // Already counted the cost for external uses when tried to adjust the cost
6449     // for extractelements, no need to add it again.
6450     if (isa<ExtractElementInst>(EU.Scalar))
6451       continue;
6452 
6453     // If found user is an insertelement, do not calculate extract cost but try
6454     // to detect it as a final shuffled/identity match.
6455     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6456       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6457         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6458         if (InsertIdx) {
6459           const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
6460           auto *It =
6461               find_if(FirstUsers,
6462                       [VU](const std::pair<Value *, const TreeEntry *> &Pair) {
6463                         return areTwoInsertFromSameBuildVector(
6464                             VU, cast<InsertElementInst>(Pair.first));
6465                       });
6466           int VecId = -1;
6467           if (It == FirstUsers.end()) {
6468             (void)ShuffleMasks.emplace_back();
6469             // Find the insertvector, vectorized in tree, if any.
6470             Value *Base = VU;
6471             while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
6472               // Build the mask for the vectorized insertelement instructions.
6473               if (const TreeEntry *E = getTreeEntry(IEBase)) {
6474                 VU = IEBase;
6475                 do {
6476                   int Idx = E->findLaneForValue(Base);
6477                   SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
6478                   if (Mask.empty())
6479                     Mask.assign(FTy->getNumElements(), UndefMaskElem);
6480                   Mask[Idx] = Idx;
6481                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6482                 } while (E == getTreeEntry(Base));
6483                 break;
6484               }
6485               Base = cast<InsertElementInst>(Base)->getOperand(0);
6486             }
6487             FirstUsers.emplace_back(VU, ScalarTE);
6488             DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
6489             VecId = FirstUsers.size() - 1;
6490           } else {
6491             if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
6492               It->first = VU;
6493             VecId = std::distance(FirstUsers.begin(), It);
6494           }
6495           int InIdx = *InsertIdx;
6496           SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
6497           if (Mask.empty())
6498             Mask.assign(FTy->getNumElements(), UndefMaskElem);
6499           assert(Mask[InIdx] == UndefMaskElem &&
6500                  "InsertElementInstruction used already.");
6501           Mask[InIdx] = EU.Lane;
6502           DemandedElts[VecId].setBit(InIdx);
6503           continue;
6504         }
6505       }
6506     }
6507 
6508     // If we plan to rewrite the tree in a smaller type, we will need to sign
6509     // extend the extracted value back to the original type. Here, we account
6510     // for the extract and the added cost of the sign extend if needed.
6511     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6512     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6513     if (MinBWs.count(ScalarRoot)) {
6514       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6515       auto Extend =
6516           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6517       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6518       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6519                                                    VecTy, EU.Lane);
6520     } else {
6521       ExtractCost +=
6522           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6523     }
6524   }
6525 
6526   InstructionCost SpillCost = getSpillCost();
6527   Cost += SpillCost + ExtractCost;
6528   auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) {
6529     InstructionCost C = 0;
6530     unsigned VF = Mask.size();
6531     unsigned VecVF = TE->getVectorFactor();
6532     if (VF != VecVF &&
6533         (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
6534          (all_of(Mask,
6535                  [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
6536           !ShuffleVectorInst::isIdentityMask(Mask)))) {
6537       SmallVector<int> OrigMask(VecVF, UndefMaskElem);
6538       std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
6539                 OrigMask.begin());
6540       C = TTI->getShuffleCost(
6541           TTI::SK_PermuteSingleSrc,
6542           FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
6543       LLVM_DEBUG(
6544           dbgs() << "SLP: Adding cost " << C
6545                  << " for final shuffle of insertelement external users.\n";
6546           TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
6547       Cost += C;
6548       return std::make_pair(TE, true);
6549     }
6550     return std::make_pair(TE, false);
6551   };
6552   // Calculate the cost of the reshuffled vectors, if any.
6553   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
6554     Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
6555     unsigned VF = ShuffleMasks[I].begin()->second.size();
6556     auto *FTy = FixedVectorType::get(
6557         cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
6558     auto Vector = ShuffleMasks[I].takeVector();
6559     auto &&EstimateShufflesCost = [this, FTy,
6560                                    &Cost](ArrayRef<int> Mask,
6561                                           ArrayRef<const TreeEntry *> TEs) {
6562       assert((TEs.size() == 1 || TEs.size() == 2) &&
6563              "Expected exactly 1 or 2 tree entries.");
6564       if (TEs.size() == 1) {
6565         int Limit = 2 * Mask.size();
6566         if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
6567             !ShuffleVectorInst::isIdentityMask(Mask)) {
6568           InstructionCost C =
6569               TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
6570           LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6571                             << " for final shuffle of insertelement "
6572                                "external users.\n";
6573                      TEs.front()->dump();
6574                      dbgs() << "SLP: Current total cost = " << Cost << "\n");
6575           Cost += C;
6576         }
6577       } else {
6578         InstructionCost C =
6579             TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
6580         LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6581                           << " for final shuffle of vector node and external "
6582                              "insertelement users.\n";
6583                    if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
6584                    dbgs() << "SLP: Current total cost = " << Cost << "\n");
6585         Cost += C;
6586       }
6587       return TEs.back();
6588     };
6589     (void)performExtractsShuffleAction<const TreeEntry>(
6590         makeMutableArrayRef(Vector.data(), Vector.size()), Base,
6591         [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
6592         EstimateShufflesCost);
6593     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6594         cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
6595         /*Insert*/ true, /*Extract*/ false);
6596     Cost -= InsertCost;
6597   }
6598 
6599 #ifndef NDEBUG
6600   SmallString<256> Str;
6601   {
6602     raw_svector_ostream OS(Str);
6603     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6604        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6605        << "SLP: Total Cost = " << Cost << ".\n";
6606   }
6607   LLVM_DEBUG(dbgs() << Str);
6608   if (ViewSLPTree)
6609     ViewGraph(this, "SLP" + F->getName(), false, Str);
6610 #endif
6611 
6612   return Cost;
6613 }
6614 
6615 Optional<TargetTransformInfo::ShuffleKind>
6616 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6617                                SmallVectorImpl<const TreeEntry *> &Entries) {
6618   // TODO: currently checking only for Scalars in the tree entry, need to count
6619   // reused elements too for better cost estimation.
6620   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6621   Entries.clear();
6622   // Build a lists of values to tree entries.
6623   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6624   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6625     if (EntryPtr.get() == TE)
6626       break;
6627     if (EntryPtr->State != TreeEntry::NeedToGather)
6628       continue;
6629     for (Value *V : EntryPtr->Scalars)
6630       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6631   }
6632   // Find all tree entries used by the gathered values. If no common entries
6633   // found - not a shuffle.
6634   // Here we build a set of tree nodes for each gathered value and trying to
6635   // find the intersection between these sets. If we have at least one common
6636   // tree node for each gathered value - we have just a permutation of the
6637   // single vector. If we have 2 different sets, we're in situation where we
6638   // have a permutation of 2 input vectors.
6639   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6640   DenseMap<Value *, int> UsedValuesEntry;
6641   for (Value *V : TE->Scalars) {
6642     if (isa<UndefValue>(V))
6643       continue;
6644     // Build a list of tree entries where V is used.
6645     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6646     auto It = ValueToTEs.find(V);
6647     if (It != ValueToTEs.end())
6648       VToTEs = It->second;
6649     if (const TreeEntry *VTE = getTreeEntry(V))
6650       VToTEs.insert(VTE);
6651     if (VToTEs.empty())
6652       return None;
6653     if (UsedTEs.empty()) {
6654       // The first iteration, just insert the list of nodes to vector.
6655       UsedTEs.push_back(VToTEs);
6656     } else {
6657       // Need to check if there are any previously used tree nodes which use V.
6658       // If there are no such nodes, consider that we have another one input
6659       // vector.
6660       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6661       unsigned Idx = 0;
6662       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6663         // Do we have a non-empty intersection of previously listed tree entries
6664         // and tree entries using current V?
6665         set_intersect(VToTEs, Set);
6666         if (!VToTEs.empty()) {
6667           // Yes, write the new subset and continue analysis for the next
6668           // scalar.
6669           Set.swap(VToTEs);
6670           break;
6671         }
6672         VToTEs = SavedVToTEs;
6673         ++Idx;
6674       }
6675       // No non-empty intersection found - need to add a second set of possible
6676       // source vectors.
6677       if (Idx == UsedTEs.size()) {
6678         // If the number of input vectors is greater than 2 - not a permutation,
6679         // fallback to the regular gather.
6680         if (UsedTEs.size() == 2)
6681           return None;
6682         UsedTEs.push_back(SavedVToTEs);
6683         Idx = UsedTEs.size() - 1;
6684       }
6685       UsedValuesEntry.try_emplace(V, Idx);
6686     }
6687   }
6688 
6689   if (UsedTEs.empty()) {
6690     assert(all_of(TE->Scalars, UndefValue::classof) &&
6691            "Expected vector of undefs only.");
6692     return None;
6693   }
6694 
6695   unsigned VF = 0;
6696   if (UsedTEs.size() == 1) {
6697     // Try to find the perfect match in another gather node at first.
6698     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6699       return EntryPtr->isSame(TE->Scalars);
6700     });
6701     if (It != UsedTEs.front().end()) {
6702       Entries.push_back(*It);
6703       std::iota(Mask.begin(), Mask.end(), 0);
6704       return TargetTransformInfo::SK_PermuteSingleSrc;
6705     }
6706     // No perfect match, just shuffle, so choose the first tree node.
6707     Entries.push_back(*UsedTEs.front().begin());
6708   } else {
6709     // Try to find nodes with the same vector factor.
6710     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6711     DenseMap<int, const TreeEntry *> VFToTE;
6712     for (const TreeEntry *TE : UsedTEs.front())
6713       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6714     for (const TreeEntry *TE : UsedTEs.back()) {
6715       auto It = VFToTE.find(TE->getVectorFactor());
6716       if (It != VFToTE.end()) {
6717         VF = It->first;
6718         Entries.push_back(It->second);
6719         Entries.push_back(TE);
6720         break;
6721       }
6722     }
6723     // No 2 source vectors with the same vector factor - give up and do regular
6724     // gather.
6725     if (Entries.empty())
6726       return None;
6727   }
6728 
6729   // Build a shuffle mask for better cost estimation and vector emission.
6730   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6731     Value *V = TE->Scalars[I];
6732     if (isa<UndefValue>(V))
6733       continue;
6734     unsigned Idx = UsedValuesEntry.lookup(V);
6735     const TreeEntry *VTE = Entries[Idx];
6736     int FoundLane = VTE->findLaneForValue(V);
6737     Mask[I] = Idx * VF + FoundLane;
6738     // Extra check required by isSingleSourceMaskImpl function (called by
6739     // ShuffleVectorInst::isSingleSourceMask).
6740     if (Mask[I] >= 2 * E)
6741       return None;
6742   }
6743   switch (Entries.size()) {
6744   case 1:
6745     return TargetTransformInfo::SK_PermuteSingleSrc;
6746   case 2:
6747     return TargetTransformInfo::SK_PermuteTwoSrc;
6748   default:
6749     break;
6750   }
6751   return None;
6752 }
6753 
6754 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6755                                        const APInt &ShuffledIndices,
6756                                        bool NeedToShuffle) const {
6757   InstructionCost Cost =
6758       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6759                                     /*Extract*/ false);
6760   if (NeedToShuffle)
6761     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6762   return Cost;
6763 }
6764 
6765 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6766   // Find the type of the operands in VL.
6767   Type *ScalarTy = VL[0]->getType();
6768   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6769     ScalarTy = SI->getValueOperand()->getType();
6770   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6771   bool DuplicateNonConst = false;
6772   // Find the cost of inserting/extracting values from the vector.
6773   // Check if the same elements are inserted several times and count them as
6774   // shuffle candidates.
6775   APInt ShuffledElements = APInt::getZero(VL.size());
6776   DenseSet<Value *> UniqueElements;
6777   // Iterate in reverse order to consider insert elements with the high cost.
6778   for (unsigned I = VL.size(); I > 0; --I) {
6779     unsigned Idx = I - 1;
6780     // No need to shuffle duplicates for constants.
6781     if (isConstant(VL[Idx])) {
6782       ShuffledElements.setBit(Idx);
6783       continue;
6784     }
6785     if (!UniqueElements.insert(VL[Idx]).second) {
6786       DuplicateNonConst = true;
6787       ShuffledElements.setBit(Idx);
6788     }
6789   }
6790   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6791 }
6792 
6793 // Perform operand reordering on the instructions in VL and return the reordered
6794 // operands in Left and Right.
6795 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6796                                              SmallVectorImpl<Value *> &Left,
6797                                              SmallVectorImpl<Value *> &Right,
6798                                              const DataLayout &DL,
6799                                              ScalarEvolution &SE,
6800                                              const BoUpSLP &R) {
6801   if (VL.empty())
6802     return;
6803   VLOperands Ops(VL, DL, SE, R);
6804   // Reorder the operands in place.
6805   Ops.reorder();
6806   Left = Ops.getVL(0);
6807   Right = Ops.getVL(1);
6808 }
6809 
6810 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6811   // Get the basic block this bundle is in. All instructions in the bundle
6812   // should be in this block.
6813   auto *Front = E->getMainOp();
6814   auto *BB = Front->getParent();
6815   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6816     auto *I = cast<Instruction>(V);
6817     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6818   }));
6819 
6820   auto &&FindLastInst = [E, Front]() {
6821     Instruction *LastInst = Front;
6822     for (Value *V : E->Scalars) {
6823       auto *I = dyn_cast<Instruction>(V);
6824       if (!I)
6825         continue;
6826       if (LastInst->comesBefore(I))
6827         LastInst = I;
6828     }
6829     return LastInst;
6830   };
6831 
6832   auto &&FindFirstInst = [E, Front]() {
6833     Instruction *FirstInst = Front;
6834     for (Value *V : E->Scalars) {
6835       auto *I = dyn_cast<Instruction>(V);
6836       if (!I)
6837         continue;
6838       if (I->comesBefore(FirstInst))
6839         FirstInst = I;
6840     }
6841     return FirstInst;
6842   };
6843 
6844   // Set the insert point to the beginning of the basic block if the entry
6845   // should not be scheduled.
6846   if (E->State != TreeEntry::NeedToGather &&
6847       doesNotNeedToSchedule(E->Scalars)) {
6848     Instruction *InsertInst;
6849     if (all_of(E->Scalars, isUsedOutsideBlock))
6850       InsertInst = FindLastInst();
6851     else
6852       InsertInst = FindFirstInst();
6853     // If the instruction is PHI, set the insert point after all the PHIs.
6854     if (isa<PHINode>(InsertInst))
6855       InsertInst = BB->getFirstNonPHI();
6856     BasicBlock::iterator InsertPt = InsertInst->getIterator();
6857     Builder.SetInsertPoint(BB, InsertPt);
6858     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6859     return;
6860   }
6861 
6862   // The last instruction in the bundle in program order.
6863   Instruction *LastInst = nullptr;
6864 
6865   // Find the last instruction. The common case should be that BB has been
6866   // scheduled, and the last instruction is VL.back(). So we start with
6867   // VL.back() and iterate over schedule data until we reach the end of the
6868   // bundle. The end of the bundle is marked by null ScheduleData.
6869   if (BlocksSchedules.count(BB)) {
6870     Value *V = E->isOneOf(E->Scalars.back());
6871     if (doesNotNeedToBeScheduled(V))
6872       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6873     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6874     if (Bundle && Bundle->isPartOfBundle())
6875       for (; Bundle; Bundle = Bundle->NextInBundle)
6876         if (Bundle->OpValue == Bundle->Inst)
6877           LastInst = Bundle->Inst;
6878   }
6879 
6880   // LastInst can still be null at this point if there's either not an entry
6881   // for BB in BlocksSchedules or there's no ScheduleData available for
6882   // VL.back(). This can be the case if buildTree_rec aborts for various
6883   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6884   // size is reached, etc.). ScheduleData is initialized in the scheduling
6885   // "dry-run".
6886   //
6887   // If this happens, we can still find the last instruction by brute force. We
6888   // iterate forwards from Front (inclusive) until we either see all
6889   // instructions in the bundle or reach the end of the block. If Front is the
6890   // last instruction in program order, LastInst will be set to Front, and we
6891   // will visit all the remaining instructions in the block.
6892   //
6893   // One of the reasons we exit early from buildTree_rec is to place an upper
6894   // bound on compile-time. Thus, taking an additional compile-time hit here is
6895   // not ideal. However, this should be exceedingly rare since it requires that
6896   // we both exit early from buildTree_rec and that the bundle be out-of-order
6897   // (causing us to iterate all the way to the end of the block).
6898   if (!LastInst) {
6899     LastInst = FindLastInst();
6900     // If the instruction is PHI, set the insert point after all the PHIs.
6901     if (isa<PHINode>(LastInst))
6902       LastInst = BB->getFirstNonPHI()->getPrevNode();
6903   }
6904   assert(LastInst && "Failed to find last instruction in bundle");
6905 
6906   // Set the insertion point after the last instruction in the bundle. Set the
6907   // debug location to Front.
6908   Builder.SetInsertPoint(BB, std::next(LastInst->getIterator()));
6909   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6910 }
6911 
6912 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6913   // List of instructions/lanes from current block and/or the blocks which are
6914   // part of the current loop. These instructions will be inserted at the end to
6915   // make it possible to optimize loops and hoist invariant instructions out of
6916   // the loops body with better chances for success.
6917   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6918   SmallSet<int, 4> PostponedIndices;
6919   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6920   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6921     SmallPtrSet<BasicBlock *, 4> Visited;
6922     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6923       InsertBB = InsertBB->getSinglePredecessor();
6924     return InsertBB && InsertBB == InstBB;
6925   };
6926   for (int I = 0, E = VL.size(); I < E; ++I) {
6927     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6928       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6929            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6930           PostponedIndices.insert(I).second)
6931         PostponedInsts.emplace_back(Inst, I);
6932   }
6933 
6934   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6935     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6936     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6937     if (!InsElt)
6938       return Vec;
6939     GatherShuffleSeq.insert(InsElt);
6940     CSEBlocks.insert(InsElt->getParent());
6941     // Add to our 'need-to-extract' list.
6942     if (TreeEntry *Entry = getTreeEntry(V)) {
6943       // Find which lane we need to extract.
6944       unsigned FoundLane = Entry->findLaneForValue(V);
6945       ExternalUses.emplace_back(V, InsElt, FoundLane);
6946     }
6947     return Vec;
6948   };
6949   Value *Val0 =
6950       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6951   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6952   Value *Vec = PoisonValue::get(VecTy);
6953   SmallVector<int> NonConsts;
6954   // Insert constant values at first.
6955   for (int I = 0, E = VL.size(); I < E; ++I) {
6956     if (PostponedIndices.contains(I))
6957       continue;
6958     if (!isConstant(VL[I])) {
6959       NonConsts.push_back(I);
6960       continue;
6961     }
6962     Vec = CreateInsertElement(Vec, VL[I], I);
6963   }
6964   // Insert non-constant values.
6965   for (int I : NonConsts)
6966     Vec = CreateInsertElement(Vec, VL[I], I);
6967   // Append instructions, which are/may be part of the loop, in the end to make
6968   // it possible to hoist non-loop-based instructions.
6969   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6970     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6971 
6972   return Vec;
6973 }
6974 
6975 namespace {
6976 /// Merges shuffle masks and emits final shuffle instruction, if required.
6977 class ShuffleInstructionBuilder {
6978   IRBuilderBase &Builder;
6979   const unsigned VF = 0;
6980   bool IsFinalized = false;
6981   SmallVector<int, 4> Mask;
6982   /// Holds all of the instructions that we gathered.
6983   SetVector<Instruction *> &GatherShuffleSeq;
6984   /// A list of blocks that we are going to CSE.
6985   SetVector<BasicBlock *> &CSEBlocks;
6986 
6987 public:
6988   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6989                             SetVector<Instruction *> &GatherShuffleSeq,
6990                             SetVector<BasicBlock *> &CSEBlocks)
6991       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6992         CSEBlocks(CSEBlocks) {}
6993 
6994   /// Adds a mask, inverting it before applying.
6995   void addInversedMask(ArrayRef<unsigned> SubMask) {
6996     if (SubMask.empty())
6997       return;
6998     SmallVector<int, 4> NewMask;
6999     inversePermutation(SubMask, NewMask);
7000     addMask(NewMask);
7001   }
7002 
7003   /// Functions adds masks, merging them into  single one.
7004   void addMask(ArrayRef<unsigned> SubMask) {
7005     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
7006     addMask(NewMask);
7007   }
7008 
7009   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
7010 
7011   Value *finalize(Value *V) {
7012     IsFinalized = true;
7013     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
7014     if (VF == ValueVF && Mask.empty())
7015       return V;
7016     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
7017     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
7018     addMask(NormalizedMask);
7019 
7020     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
7021       return V;
7022     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
7023     if (auto *I = dyn_cast<Instruction>(Vec)) {
7024       GatherShuffleSeq.insert(I);
7025       CSEBlocks.insert(I->getParent());
7026     }
7027     return Vec;
7028   }
7029 
7030   ~ShuffleInstructionBuilder() {
7031     assert((IsFinalized || Mask.empty()) &&
7032            "Shuffle construction must be finalized.");
7033   }
7034 };
7035 } // namespace
7036 
7037 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
7038   const unsigned VF = VL.size();
7039   InstructionsState S = getSameOpcode(VL);
7040   if (S.getOpcode()) {
7041     if (TreeEntry *E = getTreeEntry(S.OpValue))
7042       if (E->isSame(VL)) {
7043         Value *V = vectorizeTree(E);
7044         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
7045           if (!E->ReuseShuffleIndices.empty()) {
7046             // Reshuffle to get only unique values.
7047             // If some of the scalars are duplicated in the vectorization tree
7048             // entry, we do not vectorize them but instead generate a mask for
7049             // the reuses. But if there are several users of the same entry,
7050             // they may have different vectorization factors. This is especially
7051             // important for PHI nodes. In this case, we need to adapt the
7052             // resulting instruction for the user vectorization factor and have
7053             // to reshuffle it again to take only unique elements of the vector.
7054             // Without this code the function incorrectly returns reduced vector
7055             // instruction with the same elements, not with the unique ones.
7056 
7057             // block:
7058             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
7059             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
7060             // ... (use %2)
7061             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
7062             // br %block
7063             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
7064             SmallSet<int, 4> UsedIdxs;
7065             int Pos = 0;
7066             int Sz = VL.size();
7067             for (int Idx : E->ReuseShuffleIndices) {
7068               if (Idx != Sz && Idx != UndefMaskElem &&
7069                   UsedIdxs.insert(Idx).second)
7070                 UniqueIdxs[Idx] = Pos;
7071               ++Pos;
7072             }
7073             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
7074                                             "less than original vector size.");
7075             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
7076             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
7077           } else {
7078             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
7079                    "Expected vectorization factor less "
7080                    "than original vector size.");
7081             SmallVector<int> UniformMask(VF, 0);
7082             std::iota(UniformMask.begin(), UniformMask.end(), 0);
7083             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
7084           }
7085           if (auto *I = dyn_cast<Instruction>(V)) {
7086             GatherShuffleSeq.insert(I);
7087             CSEBlocks.insert(I->getParent());
7088           }
7089         }
7090         return V;
7091       }
7092   }
7093 
7094   // Can't vectorize this, so simply build a new vector with each lane
7095   // corresponding to the requested value.
7096   return createBuildVector(VL);
7097 }
7098 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
7099   unsigned VF = VL.size();
7100   // Exploit possible reuse of values across lanes.
7101   SmallVector<int> ReuseShuffleIndicies;
7102   SmallVector<Value *> UniqueValues;
7103   if (VL.size() > 2) {
7104     DenseMap<Value *, unsigned> UniquePositions;
7105     unsigned NumValues =
7106         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
7107                                     return !isa<UndefValue>(V);
7108                                   }).base());
7109     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
7110     int UniqueVals = 0;
7111     for (Value *V : VL.drop_back(VL.size() - VF)) {
7112       if (isa<UndefValue>(V)) {
7113         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
7114         continue;
7115       }
7116       if (isConstant(V)) {
7117         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
7118         UniqueValues.emplace_back(V);
7119         continue;
7120       }
7121       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
7122       ReuseShuffleIndicies.emplace_back(Res.first->second);
7123       if (Res.second) {
7124         UniqueValues.emplace_back(V);
7125         ++UniqueVals;
7126       }
7127     }
7128     if (UniqueVals == 1 && UniqueValues.size() == 1) {
7129       // Emit pure splat vector.
7130       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
7131                                   UndefMaskElem);
7132     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
7133       ReuseShuffleIndicies.clear();
7134       UniqueValues.clear();
7135       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
7136     }
7137     UniqueValues.append(VF - UniqueValues.size(),
7138                         PoisonValue::get(VL[0]->getType()));
7139     VL = UniqueValues;
7140   }
7141 
7142   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7143                                            CSEBlocks);
7144   Value *Vec = gather(VL);
7145   if (!ReuseShuffleIndicies.empty()) {
7146     ShuffleBuilder.addMask(ReuseShuffleIndicies);
7147     Vec = ShuffleBuilder.finalize(Vec);
7148   }
7149   return Vec;
7150 }
7151 
7152 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
7153   IRBuilder<>::InsertPointGuard Guard(Builder);
7154 
7155   if (E->VectorizedValue) {
7156     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
7157     return E->VectorizedValue;
7158   }
7159 
7160   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
7161   unsigned VF = E->getVectorFactor();
7162   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
7163                                            CSEBlocks);
7164   if (E->State == TreeEntry::NeedToGather) {
7165     if (E->getMainOp())
7166       setInsertPointAfterBundle(E);
7167     Value *Vec;
7168     SmallVector<int> Mask;
7169     SmallVector<const TreeEntry *> Entries;
7170     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
7171         isGatherShuffledEntry(E, Mask, Entries);
7172     if (Shuffle.hasValue()) {
7173       assert((Entries.size() == 1 || Entries.size() == 2) &&
7174              "Expected shuffle of 1 or 2 entries.");
7175       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
7176                                         Entries.back()->VectorizedValue, Mask);
7177       if (auto *I = dyn_cast<Instruction>(Vec)) {
7178         GatherShuffleSeq.insert(I);
7179         CSEBlocks.insert(I->getParent());
7180       }
7181     } else {
7182       Vec = gather(E->Scalars);
7183     }
7184     if (NeedToShuffleReuses) {
7185       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7186       Vec = ShuffleBuilder.finalize(Vec);
7187     }
7188     E->VectorizedValue = Vec;
7189     return Vec;
7190   }
7191 
7192   assert((E->State == TreeEntry::Vectorize ||
7193           E->State == TreeEntry::ScatterVectorize) &&
7194          "Unhandled state");
7195   unsigned ShuffleOrOp =
7196       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
7197   Instruction *VL0 = E->getMainOp();
7198   Type *ScalarTy = VL0->getType();
7199   if (auto *Store = dyn_cast<StoreInst>(VL0))
7200     ScalarTy = Store->getValueOperand()->getType();
7201   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
7202     ScalarTy = IE->getOperand(1)->getType();
7203   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
7204   switch (ShuffleOrOp) {
7205     case Instruction::PHI: {
7206       assert(
7207           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
7208           "PHI reordering is free.");
7209       auto *PH = cast<PHINode>(VL0);
7210       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
7211       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7212       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
7213       Value *V = NewPhi;
7214 
7215       // Adjust insertion point once all PHI's have been generated.
7216       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
7217       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7218 
7219       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7220       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7221       V = ShuffleBuilder.finalize(V);
7222 
7223       E->VectorizedValue = V;
7224 
7225       // PHINodes may have multiple entries from the same block. We want to
7226       // visit every block once.
7227       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7228 
7229       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7230         ValueList Operands;
7231         BasicBlock *IBB = PH->getIncomingBlock(i);
7232 
7233         if (!VisitedBBs.insert(IBB).second) {
7234           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7235           continue;
7236         }
7237 
7238         Builder.SetInsertPoint(IBB->getTerminator());
7239         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7240         Value *Vec = vectorizeTree(E->getOperand(i));
7241         NewPhi->addIncoming(Vec, IBB);
7242       }
7243 
7244       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7245              "Invalid number of incoming values");
7246       return V;
7247     }
7248 
7249     case Instruction::ExtractElement: {
7250       Value *V = E->getSingleOperand(0);
7251       Builder.SetInsertPoint(VL0);
7252       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7253       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7254       V = ShuffleBuilder.finalize(V);
7255       E->VectorizedValue = V;
7256       return V;
7257     }
7258     case Instruction::ExtractValue: {
7259       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7260       Builder.SetInsertPoint(LI);
7261       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7262       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7263       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7264       Value *NewV = propagateMetadata(V, E->Scalars);
7265       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7266       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7267       NewV = ShuffleBuilder.finalize(NewV);
7268       E->VectorizedValue = NewV;
7269       return NewV;
7270     }
7271     case Instruction::InsertElement: {
7272       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7273       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7274       Value *V = vectorizeTree(E->getOperand(1));
7275 
7276       // Create InsertVector shuffle if necessary
7277       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7278         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7279       }));
7280       const unsigned NumElts =
7281           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7282       const unsigned NumScalars = E->Scalars.size();
7283 
7284       unsigned Offset = *getInsertIndex(VL0);
7285       assert(Offset < NumElts && "Failed to find vector index offset");
7286 
7287       // Create shuffle to resize vector
7288       SmallVector<int> Mask;
7289       if (!E->ReorderIndices.empty()) {
7290         inversePermutation(E->ReorderIndices, Mask);
7291         Mask.append(NumElts - NumScalars, UndefMaskElem);
7292       } else {
7293         Mask.assign(NumElts, UndefMaskElem);
7294         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7295       }
7296       // Create InsertVector shuffle if necessary
7297       bool IsIdentity = true;
7298       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7299       Mask.swap(PrevMask);
7300       for (unsigned I = 0; I < NumScalars; ++I) {
7301         Value *Scalar = E->Scalars[PrevMask[I]];
7302         unsigned InsertIdx = *getInsertIndex(Scalar);
7303         IsIdentity &= InsertIdx - Offset == I;
7304         Mask[InsertIdx - Offset] = I;
7305       }
7306       if (!IsIdentity || NumElts != NumScalars) {
7307         V = Builder.CreateShuffleVector(V, Mask);
7308         if (auto *I = dyn_cast<Instruction>(V)) {
7309           GatherShuffleSeq.insert(I);
7310           CSEBlocks.insert(I->getParent());
7311         }
7312       }
7313 
7314       if ((!IsIdentity || Offset != 0 ||
7315            !isUndefVector(FirstInsert->getOperand(0))) &&
7316           NumElts != NumScalars) {
7317         SmallVector<int> InsertMask(NumElts);
7318         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7319         for (unsigned I = 0; I < NumElts; I++) {
7320           if (Mask[I] != UndefMaskElem)
7321             InsertMask[Offset + I] = NumElts + I;
7322         }
7323 
7324         V = Builder.CreateShuffleVector(
7325             FirstInsert->getOperand(0), V, InsertMask,
7326             cast<Instruction>(E->Scalars.back())->getName());
7327         if (auto *I = dyn_cast<Instruction>(V)) {
7328           GatherShuffleSeq.insert(I);
7329           CSEBlocks.insert(I->getParent());
7330         }
7331       }
7332 
7333       ++NumVectorInstructions;
7334       E->VectorizedValue = V;
7335       return V;
7336     }
7337     case Instruction::ZExt:
7338     case Instruction::SExt:
7339     case Instruction::FPToUI:
7340     case Instruction::FPToSI:
7341     case Instruction::FPExt:
7342     case Instruction::PtrToInt:
7343     case Instruction::IntToPtr:
7344     case Instruction::SIToFP:
7345     case Instruction::UIToFP:
7346     case Instruction::Trunc:
7347     case Instruction::FPTrunc:
7348     case Instruction::BitCast: {
7349       setInsertPointAfterBundle(E);
7350 
7351       Value *InVec = vectorizeTree(E->getOperand(0));
7352 
7353       if (E->VectorizedValue) {
7354         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7355         return E->VectorizedValue;
7356       }
7357 
7358       auto *CI = cast<CastInst>(VL0);
7359       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7360       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7361       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7362       V = ShuffleBuilder.finalize(V);
7363 
7364       E->VectorizedValue = V;
7365       ++NumVectorInstructions;
7366       return V;
7367     }
7368     case Instruction::FCmp:
7369     case Instruction::ICmp: {
7370       setInsertPointAfterBundle(E);
7371 
7372       Value *L = vectorizeTree(E->getOperand(0));
7373       Value *R = vectorizeTree(E->getOperand(1));
7374 
7375       if (E->VectorizedValue) {
7376         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7377         return E->VectorizedValue;
7378       }
7379 
7380       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7381       Value *V = Builder.CreateCmp(P0, L, R);
7382       propagateIRFlags(V, E->Scalars, VL0);
7383       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7384       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7385       V = ShuffleBuilder.finalize(V);
7386 
7387       E->VectorizedValue = V;
7388       ++NumVectorInstructions;
7389       return V;
7390     }
7391     case Instruction::Select: {
7392       setInsertPointAfterBundle(E);
7393 
7394       Value *Cond = vectorizeTree(E->getOperand(0));
7395       Value *True = vectorizeTree(E->getOperand(1));
7396       Value *False = vectorizeTree(E->getOperand(2));
7397 
7398       if (E->VectorizedValue) {
7399         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7400         return E->VectorizedValue;
7401       }
7402 
7403       Value *V = Builder.CreateSelect(Cond, True, False);
7404       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7405       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7406       V = ShuffleBuilder.finalize(V);
7407 
7408       E->VectorizedValue = V;
7409       ++NumVectorInstructions;
7410       return V;
7411     }
7412     case Instruction::FNeg: {
7413       setInsertPointAfterBundle(E);
7414 
7415       Value *Op = vectorizeTree(E->getOperand(0));
7416 
7417       if (E->VectorizedValue) {
7418         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7419         return E->VectorizedValue;
7420       }
7421 
7422       Value *V = Builder.CreateUnOp(
7423           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7424       propagateIRFlags(V, E->Scalars, VL0);
7425       if (auto *I = dyn_cast<Instruction>(V))
7426         V = propagateMetadata(I, E->Scalars);
7427 
7428       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7429       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7430       V = ShuffleBuilder.finalize(V);
7431 
7432       E->VectorizedValue = V;
7433       ++NumVectorInstructions;
7434 
7435       return V;
7436     }
7437     case Instruction::Add:
7438     case Instruction::FAdd:
7439     case Instruction::Sub:
7440     case Instruction::FSub:
7441     case Instruction::Mul:
7442     case Instruction::FMul:
7443     case Instruction::UDiv:
7444     case Instruction::SDiv:
7445     case Instruction::FDiv:
7446     case Instruction::URem:
7447     case Instruction::SRem:
7448     case Instruction::FRem:
7449     case Instruction::Shl:
7450     case Instruction::LShr:
7451     case Instruction::AShr:
7452     case Instruction::And:
7453     case Instruction::Or:
7454     case Instruction::Xor: {
7455       setInsertPointAfterBundle(E);
7456 
7457       Value *LHS = vectorizeTree(E->getOperand(0));
7458       Value *RHS = vectorizeTree(E->getOperand(1));
7459 
7460       if (E->VectorizedValue) {
7461         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7462         return E->VectorizedValue;
7463       }
7464 
7465       Value *V = Builder.CreateBinOp(
7466           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7467           RHS);
7468       propagateIRFlags(V, E->Scalars, VL0);
7469       if (auto *I = dyn_cast<Instruction>(V))
7470         V = propagateMetadata(I, E->Scalars);
7471 
7472       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7473       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7474       V = ShuffleBuilder.finalize(V);
7475 
7476       E->VectorizedValue = V;
7477       ++NumVectorInstructions;
7478 
7479       return V;
7480     }
7481     case Instruction::Load: {
7482       // Loads are inserted at the head of the tree because we don't want to
7483       // sink them all the way down past store instructions.
7484       setInsertPointAfterBundle(E);
7485 
7486       LoadInst *LI = cast<LoadInst>(VL0);
7487       Instruction *NewLI;
7488       unsigned AS = LI->getPointerAddressSpace();
7489       Value *PO = LI->getPointerOperand();
7490       if (E->State == TreeEntry::Vectorize) {
7491         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7492         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7493 
7494         // The pointer operand uses an in-tree scalar so we add the new BitCast
7495         // or LoadInst to ExternalUses list to make sure that an extract will
7496         // be generated in the future.
7497         if (TreeEntry *Entry = getTreeEntry(PO)) {
7498           // Find which lane we need to extract.
7499           unsigned FoundLane = Entry->findLaneForValue(PO);
7500           ExternalUses.emplace_back(
7501               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7502         }
7503       } else {
7504         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7505         Value *VecPtr = vectorizeTree(E->getOperand(0));
7506         // Use the minimum alignment of the gathered loads.
7507         Align CommonAlignment = LI->getAlign();
7508         for (Value *V : E->Scalars)
7509           CommonAlignment =
7510               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7511         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7512       }
7513       Value *V = propagateMetadata(NewLI, E->Scalars);
7514 
7515       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7516       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7517       V = ShuffleBuilder.finalize(V);
7518       E->VectorizedValue = V;
7519       ++NumVectorInstructions;
7520       return V;
7521     }
7522     case Instruction::Store: {
7523       auto *SI = cast<StoreInst>(VL0);
7524       unsigned AS = SI->getPointerAddressSpace();
7525 
7526       setInsertPointAfterBundle(E);
7527 
7528       Value *VecValue = vectorizeTree(E->getOperand(0));
7529       ShuffleBuilder.addMask(E->ReorderIndices);
7530       VecValue = ShuffleBuilder.finalize(VecValue);
7531 
7532       Value *ScalarPtr = SI->getPointerOperand();
7533       Value *VecPtr = Builder.CreateBitCast(
7534           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7535       StoreInst *ST =
7536           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7537 
7538       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7539       // StoreInst to ExternalUses to make sure that an extract will be
7540       // generated in the future.
7541       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7542         // Find which lane we need to extract.
7543         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7544         ExternalUses.push_back(ExternalUser(
7545             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7546             FoundLane));
7547       }
7548 
7549       Value *V = propagateMetadata(ST, E->Scalars);
7550 
7551       E->VectorizedValue = V;
7552       ++NumVectorInstructions;
7553       return V;
7554     }
7555     case Instruction::GetElementPtr: {
7556       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7557       setInsertPointAfterBundle(E);
7558 
7559       Value *Op0 = vectorizeTree(E->getOperand(0));
7560 
7561       SmallVector<Value *> OpVecs;
7562       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7563         Value *OpVec = vectorizeTree(E->getOperand(J));
7564         OpVecs.push_back(OpVec);
7565       }
7566 
7567       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7568       if (Instruction *I = dyn_cast<Instruction>(V))
7569         V = propagateMetadata(I, E->Scalars);
7570 
7571       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7572       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7573       V = ShuffleBuilder.finalize(V);
7574 
7575       E->VectorizedValue = V;
7576       ++NumVectorInstructions;
7577 
7578       return V;
7579     }
7580     case Instruction::Call: {
7581       CallInst *CI = cast<CallInst>(VL0);
7582       setInsertPointAfterBundle(E);
7583 
7584       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7585       if (Function *FI = CI->getCalledFunction())
7586         IID = FI->getIntrinsicID();
7587 
7588       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7589 
7590       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7591       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7592                           VecCallCosts.first <= VecCallCosts.second;
7593 
7594       Value *ScalarArg = nullptr;
7595       std::vector<Value *> OpVecs;
7596       SmallVector<Type *, 2> TysForDecl =
7597           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7598       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7599         ValueList OpVL;
7600         // Some intrinsics have scalar arguments. This argument should not be
7601         // vectorized.
7602         if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
7603           CallInst *CEI = cast<CallInst>(VL0);
7604           ScalarArg = CEI->getArgOperand(j);
7605           OpVecs.push_back(CEI->getArgOperand(j));
7606           if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7607             TysForDecl.push_back(ScalarArg->getType());
7608           continue;
7609         }
7610 
7611         Value *OpVec = vectorizeTree(E->getOperand(j));
7612         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7613         OpVecs.push_back(OpVec);
7614         if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
7615           TysForDecl.push_back(OpVec->getType());
7616       }
7617 
7618       Function *CF;
7619       if (!UseIntrinsic) {
7620         VFShape Shape =
7621             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7622                                   VecTy->getNumElements())),
7623                          false /*HasGlobalPred*/);
7624         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7625       } else {
7626         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7627       }
7628 
7629       SmallVector<OperandBundleDef, 1> OpBundles;
7630       CI->getOperandBundlesAsDefs(OpBundles);
7631       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7632 
7633       // The scalar argument uses an in-tree scalar so we add the new vectorized
7634       // call to ExternalUses list to make sure that an extract will be
7635       // generated in the future.
7636       if (ScalarArg) {
7637         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7638           // Find which lane we need to extract.
7639           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7640           ExternalUses.push_back(
7641               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7642         }
7643       }
7644 
7645       propagateIRFlags(V, E->Scalars, VL0);
7646       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7647       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7648       V = ShuffleBuilder.finalize(V);
7649 
7650       E->VectorizedValue = V;
7651       ++NumVectorInstructions;
7652       return V;
7653     }
7654     case Instruction::ShuffleVector: {
7655       assert(E->isAltShuffle() &&
7656              ((Instruction::isBinaryOp(E->getOpcode()) &&
7657                Instruction::isBinaryOp(E->getAltOpcode())) ||
7658               (Instruction::isCast(E->getOpcode()) &&
7659                Instruction::isCast(E->getAltOpcode())) ||
7660               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7661              "Invalid Shuffle Vector Operand");
7662 
7663       Value *LHS = nullptr, *RHS = nullptr;
7664       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7665         setInsertPointAfterBundle(E);
7666         LHS = vectorizeTree(E->getOperand(0));
7667         RHS = vectorizeTree(E->getOperand(1));
7668       } else {
7669         setInsertPointAfterBundle(E);
7670         LHS = vectorizeTree(E->getOperand(0));
7671       }
7672 
7673       if (E->VectorizedValue) {
7674         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7675         return E->VectorizedValue;
7676       }
7677 
7678       Value *V0, *V1;
7679       if (Instruction::isBinaryOp(E->getOpcode())) {
7680         V0 = Builder.CreateBinOp(
7681             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7682         V1 = Builder.CreateBinOp(
7683             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7684       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7685         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7686         auto *AltCI = cast<CmpInst>(E->getAltOp());
7687         CmpInst::Predicate AltPred = AltCI->getPredicate();
7688         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7689       } else {
7690         V0 = Builder.CreateCast(
7691             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7692         V1 = Builder.CreateCast(
7693             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7694       }
7695       // Add V0 and V1 to later analysis to try to find and remove matching
7696       // instruction, if any.
7697       for (Value *V : {V0, V1}) {
7698         if (auto *I = dyn_cast<Instruction>(V)) {
7699           GatherShuffleSeq.insert(I);
7700           CSEBlocks.insert(I->getParent());
7701         }
7702       }
7703 
7704       // Create shuffle to take alternate operations from the vector.
7705       // Also, gather up main and alt scalar ops to propagate IR flags to
7706       // each vector operation.
7707       ValueList OpScalars, AltScalars;
7708       SmallVector<int> Mask;
7709       buildShuffleEntryMask(
7710           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7711           [E](Instruction *I) {
7712             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7713             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7714           },
7715           Mask, &OpScalars, &AltScalars);
7716 
7717       propagateIRFlags(V0, OpScalars);
7718       propagateIRFlags(V1, AltScalars);
7719 
7720       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7721       if (auto *I = dyn_cast<Instruction>(V)) {
7722         V = propagateMetadata(I, E->Scalars);
7723         GatherShuffleSeq.insert(I);
7724         CSEBlocks.insert(I->getParent());
7725       }
7726       V = ShuffleBuilder.finalize(V);
7727 
7728       E->VectorizedValue = V;
7729       ++NumVectorInstructions;
7730 
7731       return V;
7732     }
7733     default:
7734     llvm_unreachable("unknown inst");
7735   }
7736   return nullptr;
7737 }
7738 
7739 Value *BoUpSLP::vectorizeTree() {
7740   ExtraValueToDebugLocsMap ExternallyUsedValues;
7741   return vectorizeTree(ExternallyUsedValues);
7742 }
7743 
7744 Value *
7745 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7746   // All blocks must be scheduled before any instructions are inserted.
7747   for (auto &BSIter : BlocksSchedules) {
7748     scheduleBlock(BSIter.second.get());
7749   }
7750 
7751   Builder.SetInsertPoint(&F->getEntryBlock().front());
7752   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7753 
7754   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7755   // vectorized root. InstCombine will then rewrite the entire expression. We
7756   // sign extend the extracted values below.
7757   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7758   if (MinBWs.count(ScalarRoot)) {
7759     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7760       // If current instr is a phi and not the last phi, insert it after the
7761       // last phi node.
7762       if (isa<PHINode>(I))
7763         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7764       else
7765         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7766     }
7767     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7768     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7769     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7770     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7771     VectorizableTree[0]->VectorizedValue = Trunc;
7772   }
7773 
7774   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7775                     << " values .\n");
7776 
7777   // Extract all of the elements with the external uses.
7778   for (const auto &ExternalUse : ExternalUses) {
7779     Value *Scalar = ExternalUse.Scalar;
7780     llvm::User *User = ExternalUse.User;
7781 
7782     // Skip users that we already RAUW. This happens when one instruction
7783     // has multiple uses of the same value.
7784     if (User && !is_contained(Scalar->users(), User))
7785       continue;
7786     TreeEntry *E = getTreeEntry(Scalar);
7787     assert(E && "Invalid scalar");
7788     assert(E->State != TreeEntry::NeedToGather &&
7789            "Extracting from a gather list");
7790 
7791     Value *Vec = E->VectorizedValue;
7792     assert(Vec && "Can't find vectorizable value");
7793 
7794     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7795     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7796       if (Scalar->getType() != Vec->getType()) {
7797         Value *Ex;
7798         // "Reuse" the existing extract to improve final codegen.
7799         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7800           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7801                                             ES->getOperand(1));
7802         } else {
7803           Ex = Builder.CreateExtractElement(Vec, Lane);
7804         }
7805         // If necessary, sign-extend or zero-extend ScalarRoot
7806         // to the larger type.
7807         if (!MinBWs.count(ScalarRoot))
7808           return Ex;
7809         if (MinBWs[ScalarRoot].second)
7810           return Builder.CreateSExt(Ex, Scalar->getType());
7811         return Builder.CreateZExt(Ex, Scalar->getType());
7812       }
7813       assert(isa<FixedVectorType>(Scalar->getType()) &&
7814              isa<InsertElementInst>(Scalar) &&
7815              "In-tree scalar of vector type is not insertelement?");
7816       return Vec;
7817     };
7818     // If User == nullptr, the Scalar is used as extra arg. Generate
7819     // ExtractElement instruction and update the record for this scalar in
7820     // ExternallyUsedValues.
7821     if (!User) {
7822       assert(ExternallyUsedValues.count(Scalar) &&
7823              "Scalar with nullptr as an external user must be registered in "
7824              "ExternallyUsedValues map");
7825       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7826         Builder.SetInsertPoint(VecI->getParent(),
7827                                std::next(VecI->getIterator()));
7828       } else {
7829         Builder.SetInsertPoint(&F->getEntryBlock().front());
7830       }
7831       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7832       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7833       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7834       auto It = ExternallyUsedValues.find(Scalar);
7835       assert(It != ExternallyUsedValues.end() &&
7836              "Externally used scalar is not found in ExternallyUsedValues");
7837       NewInstLocs.append(It->second);
7838       ExternallyUsedValues.erase(Scalar);
7839       // Required to update internally referenced instructions.
7840       Scalar->replaceAllUsesWith(NewInst);
7841       continue;
7842     }
7843 
7844     // Generate extracts for out-of-tree users.
7845     // Find the insertion point for the extractelement lane.
7846     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7847       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7848         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7849           if (PH->getIncomingValue(i) == Scalar) {
7850             Instruction *IncomingTerminator =
7851                 PH->getIncomingBlock(i)->getTerminator();
7852             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7853               Builder.SetInsertPoint(VecI->getParent(),
7854                                      std::next(VecI->getIterator()));
7855             } else {
7856               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7857             }
7858             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7859             CSEBlocks.insert(PH->getIncomingBlock(i));
7860             PH->setOperand(i, NewInst);
7861           }
7862         }
7863       } else {
7864         Builder.SetInsertPoint(cast<Instruction>(User));
7865         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7866         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7867         User->replaceUsesOfWith(Scalar, NewInst);
7868       }
7869     } else {
7870       Builder.SetInsertPoint(&F->getEntryBlock().front());
7871       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7872       CSEBlocks.insert(&F->getEntryBlock());
7873       User->replaceUsesOfWith(Scalar, NewInst);
7874     }
7875 
7876     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7877   }
7878 
7879   // For each vectorized value:
7880   for (auto &TEPtr : VectorizableTree) {
7881     TreeEntry *Entry = TEPtr.get();
7882 
7883     // No need to handle users of gathered values.
7884     if (Entry->State == TreeEntry::NeedToGather)
7885       continue;
7886 
7887     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7888 
7889     // For each lane:
7890     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7891       Value *Scalar = Entry->Scalars[Lane];
7892 
7893 #ifndef NDEBUG
7894       Type *Ty = Scalar->getType();
7895       if (!Ty->isVoidTy()) {
7896         for (User *U : Scalar->users()) {
7897           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7898 
7899           // It is legal to delete users in the ignorelist.
7900           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7901                   (isa_and_nonnull<Instruction>(U) &&
7902                    isDeleted(cast<Instruction>(U)))) &&
7903                  "Deleting out-of-tree value");
7904         }
7905       }
7906 #endif
7907       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7908       eraseInstruction(cast<Instruction>(Scalar));
7909     }
7910   }
7911 
7912   Builder.ClearInsertionPoint();
7913   InstrElementSize.clear();
7914 
7915   return VectorizableTree[0]->VectorizedValue;
7916 }
7917 
7918 void BoUpSLP::optimizeGatherSequence() {
7919   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7920                     << " gather sequences instructions.\n");
7921   // LICM InsertElementInst sequences.
7922   for (Instruction *I : GatherShuffleSeq) {
7923     if (isDeleted(I))
7924       continue;
7925 
7926     // Check if this block is inside a loop.
7927     Loop *L = LI->getLoopFor(I->getParent());
7928     if (!L)
7929       continue;
7930 
7931     // Check if it has a preheader.
7932     BasicBlock *PreHeader = L->getLoopPreheader();
7933     if (!PreHeader)
7934       continue;
7935 
7936     // If the vector or the element that we insert into it are
7937     // instructions that are defined in this basic block then we can't
7938     // hoist this instruction.
7939     if (any_of(I->operands(), [L](Value *V) {
7940           auto *OpI = dyn_cast<Instruction>(V);
7941           return OpI && L->contains(OpI);
7942         }))
7943       continue;
7944 
7945     // We can hoist this instruction. Move it to the pre-header.
7946     I->moveBefore(PreHeader->getTerminator());
7947   }
7948 
7949   // Make a list of all reachable blocks in our CSE queue.
7950   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7951   CSEWorkList.reserve(CSEBlocks.size());
7952   for (BasicBlock *BB : CSEBlocks)
7953     if (DomTreeNode *N = DT->getNode(BB)) {
7954       assert(DT->isReachableFromEntry(N));
7955       CSEWorkList.push_back(N);
7956     }
7957 
7958   // Sort blocks by domination. This ensures we visit a block after all blocks
7959   // dominating it are visited.
7960   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7961     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7962            "Different nodes should have different DFS numbers");
7963     return A->getDFSNumIn() < B->getDFSNumIn();
7964   });
7965 
7966   // Less defined shuffles can be replaced by the more defined copies.
7967   // Between two shuffles one is less defined if it has the same vector operands
7968   // and its mask indeces are the same as in the first one or undefs. E.g.
7969   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7970   // poison, <0, 0, 0, 0>.
7971   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7972                                            SmallVectorImpl<int> &NewMask) {
7973     if (I1->getType() != I2->getType())
7974       return false;
7975     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7976     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7977     if (!SI1 || !SI2)
7978       return I1->isIdenticalTo(I2);
7979     if (SI1->isIdenticalTo(SI2))
7980       return true;
7981     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7982       if (SI1->getOperand(I) != SI2->getOperand(I))
7983         return false;
7984     // Check if the second instruction is more defined than the first one.
7985     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7986     ArrayRef<int> SM1 = SI1->getShuffleMask();
7987     // Count trailing undefs in the mask to check the final number of used
7988     // registers.
7989     unsigned LastUndefsCnt = 0;
7990     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7991       if (SM1[I] == UndefMaskElem)
7992         ++LastUndefsCnt;
7993       else
7994         LastUndefsCnt = 0;
7995       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7996           NewMask[I] != SM1[I])
7997         return false;
7998       if (NewMask[I] == UndefMaskElem)
7999         NewMask[I] = SM1[I];
8000     }
8001     // Check if the last undefs actually change the final number of used vector
8002     // registers.
8003     return SM1.size() - LastUndefsCnt > 1 &&
8004            TTI->getNumberOfParts(SI1->getType()) ==
8005                TTI->getNumberOfParts(
8006                    FixedVectorType::get(SI1->getType()->getElementType(),
8007                                         SM1.size() - LastUndefsCnt));
8008   };
8009   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
8010   // instructions. TODO: We can further optimize this scan if we split the
8011   // instructions into different buckets based on the insert lane.
8012   SmallVector<Instruction *, 16> Visited;
8013   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
8014     assert(*I &&
8015            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
8016            "Worklist not sorted properly!");
8017     BasicBlock *BB = (*I)->getBlock();
8018     // For all instructions in blocks containing gather sequences:
8019     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
8020       if (isDeleted(&In))
8021         continue;
8022       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
8023           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
8024         continue;
8025 
8026       // Check if we can replace this instruction with any of the
8027       // visited instructions.
8028       bool Replaced = false;
8029       for (Instruction *&V : Visited) {
8030         SmallVector<int> NewMask;
8031         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
8032             DT->dominates(V->getParent(), In.getParent())) {
8033           In.replaceAllUsesWith(V);
8034           eraseInstruction(&In);
8035           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
8036             if (!NewMask.empty())
8037               SI->setShuffleMask(NewMask);
8038           Replaced = true;
8039           break;
8040         }
8041         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
8042             GatherShuffleSeq.contains(V) &&
8043             IsIdenticalOrLessDefined(V, &In, NewMask) &&
8044             DT->dominates(In.getParent(), V->getParent())) {
8045           In.moveAfter(V);
8046           V->replaceAllUsesWith(&In);
8047           eraseInstruction(V);
8048           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
8049             if (!NewMask.empty())
8050               SI->setShuffleMask(NewMask);
8051           V = &In;
8052           Replaced = true;
8053           break;
8054         }
8055       }
8056       if (!Replaced) {
8057         assert(!is_contained(Visited, &In));
8058         Visited.push_back(&In);
8059       }
8060     }
8061   }
8062   CSEBlocks.clear();
8063   GatherShuffleSeq.clear();
8064 }
8065 
8066 BoUpSLP::ScheduleData *
8067 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
8068   ScheduleData *Bundle = nullptr;
8069   ScheduleData *PrevInBundle = nullptr;
8070   for (Value *V : VL) {
8071     if (doesNotNeedToBeScheduled(V))
8072       continue;
8073     ScheduleData *BundleMember = getScheduleData(V);
8074     assert(BundleMember &&
8075            "no ScheduleData for bundle member "
8076            "(maybe not in same basic block)");
8077     assert(BundleMember->isSchedulingEntity() &&
8078            "bundle member already part of other bundle");
8079     if (PrevInBundle) {
8080       PrevInBundle->NextInBundle = BundleMember;
8081     } else {
8082       Bundle = BundleMember;
8083     }
8084 
8085     // Group the instructions to a bundle.
8086     BundleMember->FirstInBundle = Bundle;
8087     PrevInBundle = BundleMember;
8088   }
8089   assert(Bundle && "Failed to find schedule bundle");
8090   return Bundle;
8091 }
8092 
8093 // Groups the instructions to a bundle (which is then a single scheduling entity)
8094 // and schedules instructions until the bundle gets ready.
8095 Optional<BoUpSLP::ScheduleData *>
8096 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
8097                                             const InstructionsState &S) {
8098   // No need to schedule PHIs, insertelement, extractelement and extractvalue
8099   // instructions.
8100   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
8101       doesNotNeedToSchedule(VL))
8102     return nullptr;
8103 
8104   // Initialize the instruction bundle.
8105   Instruction *OldScheduleEnd = ScheduleEnd;
8106   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
8107 
8108   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
8109                                                          ScheduleData *Bundle) {
8110     // The scheduling region got new instructions at the lower end (or it is a
8111     // new region for the first bundle). This makes it necessary to
8112     // recalculate all dependencies.
8113     // It is seldom that this needs to be done a second time after adding the
8114     // initial bundle to the region.
8115     if (ScheduleEnd != OldScheduleEnd) {
8116       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
8117         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
8118       ReSchedule = true;
8119     }
8120     if (Bundle) {
8121       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
8122                         << " in block " << BB->getName() << "\n");
8123       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
8124     }
8125 
8126     if (ReSchedule) {
8127       resetSchedule();
8128       initialFillReadyList(ReadyInsts);
8129     }
8130 
8131     // Now try to schedule the new bundle or (if no bundle) just calculate
8132     // dependencies. As soon as the bundle is "ready" it means that there are no
8133     // cyclic dependencies and we can schedule it. Note that's important that we
8134     // don't "schedule" the bundle yet (see cancelScheduling).
8135     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
8136            !ReadyInsts.empty()) {
8137       ScheduleData *Picked = ReadyInsts.pop_back_val();
8138       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
8139              "must be ready to schedule");
8140       schedule(Picked, ReadyInsts);
8141     }
8142   };
8143 
8144   // Make sure that the scheduling region contains all
8145   // instructions of the bundle.
8146   for (Value *V : VL) {
8147     if (doesNotNeedToBeScheduled(V))
8148       continue;
8149     if (!extendSchedulingRegion(V, S)) {
8150       // If the scheduling region got new instructions at the lower end (or it
8151       // is a new region for the first bundle). This makes it necessary to
8152       // recalculate all dependencies.
8153       // Otherwise the compiler may crash trying to incorrectly calculate
8154       // dependencies and emit instruction in the wrong order at the actual
8155       // scheduling.
8156       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
8157       return None;
8158     }
8159   }
8160 
8161   bool ReSchedule = false;
8162   for (Value *V : VL) {
8163     if (doesNotNeedToBeScheduled(V))
8164       continue;
8165     ScheduleData *BundleMember = getScheduleData(V);
8166     assert(BundleMember &&
8167            "no ScheduleData for bundle member (maybe not in same basic block)");
8168 
8169     // Make sure we don't leave the pieces of the bundle in the ready list when
8170     // whole bundle might not be ready.
8171     ReadyInsts.remove(BundleMember);
8172 
8173     if (!BundleMember->IsScheduled)
8174       continue;
8175     // A bundle member was scheduled as single instruction before and now
8176     // needs to be scheduled as part of the bundle. We just get rid of the
8177     // existing schedule.
8178     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
8179                       << " was already scheduled\n");
8180     ReSchedule = true;
8181   }
8182 
8183   auto *Bundle = buildBundle(VL);
8184   TryScheduleBundleImpl(ReSchedule, Bundle);
8185   if (!Bundle->isReady()) {
8186     cancelScheduling(VL, S.OpValue);
8187     return None;
8188   }
8189   return Bundle;
8190 }
8191 
8192 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
8193                                                 Value *OpValue) {
8194   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
8195       doesNotNeedToSchedule(VL))
8196     return;
8197 
8198   if (doesNotNeedToBeScheduled(OpValue))
8199     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
8200   ScheduleData *Bundle = getScheduleData(OpValue);
8201   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
8202   assert(!Bundle->IsScheduled &&
8203          "Can't cancel bundle which is already scheduled");
8204   assert(Bundle->isSchedulingEntity() &&
8205          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
8206          "tried to unbundle something which is not a bundle");
8207 
8208   // Remove the bundle from the ready list.
8209   if (Bundle->isReady())
8210     ReadyInsts.remove(Bundle);
8211 
8212   // Un-bundle: make single instructions out of the bundle.
8213   ScheduleData *BundleMember = Bundle;
8214   while (BundleMember) {
8215     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
8216     BundleMember->FirstInBundle = BundleMember;
8217     ScheduleData *Next = BundleMember->NextInBundle;
8218     BundleMember->NextInBundle = nullptr;
8219     BundleMember->TE = nullptr;
8220     if (BundleMember->unscheduledDepsInBundle() == 0) {
8221       ReadyInsts.insert(BundleMember);
8222     }
8223     BundleMember = Next;
8224   }
8225 }
8226 
8227 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8228   // Allocate a new ScheduleData for the instruction.
8229   if (ChunkPos >= ChunkSize) {
8230     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8231     ChunkPos = 0;
8232   }
8233   return &(ScheduleDataChunks.back()[ChunkPos++]);
8234 }
8235 
8236 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8237                                                       const InstructionsState &S) {
8238   if (getScheduleData(V, isOneOf(S, V)))
8239     return true;
8240   Instruction *I = dyn_cast<Instruction>(V);
8241   assert(I && "bundle member must be an instruction");
8242   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8243          !doesNotNeedToBeScheduled(I) &&
8244          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8245          "be scheduled");
8246   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8247     ScheduleData *ISD = getScheduleData(I);
8248     if (!ISD)
8249       return false;
8250     assert(isInSchedulingRegion(ISD) &&
8251            "ScheduleData not in scheduling region");
8252     ScheduleData *SD = allocateScheduleDataChunks();
8253     SD->Inst = I;
8254     SD->init(SchedulingRegionID, S.OpValue);
8255     ExtraScheduleDataMap[I][S.OpValue] = SD;
8256     return true;
8257   };
8258   if (CheckScheduleForI(I))
8259     return true;
8260   if (!ScheduleStart) {
8261     // It's the first instruction in the new region.
8262     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8263     ScheduleStart = I;
8264     ScheduleEnd = I->getNextNode();
8265     if (isOneOf(S, I) != I)
8266       CheckScheduleForI(I);
8267     assert(ScheduleEnd && "tried to vectorize a terminator?");
8268     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8269     return true;
8270   }
8271   // Search up and down at the same time, because we don't know if the new
8272   // instruction is above or below the existing scheduling region.
8273   BasicBlock::reverse_iterator UpIter =
8274       ++ScheduleStart->getIterator().getReverse();
8275   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8276   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8277   BasicBlock::iterator LowerEnd = BB->end();
8278   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8279          &*DownIter != I) {
8280     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8281       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8282       return false;
8283     }
8284 
8285     ++UpIter;
8286     ++DownIter;
8287   }
8288   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8289     assert(I->getParent() == ScheduleStart->getParent() &&
8290            "Instruction is in wrong basic block.");
8291     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8292     ScheduleStart = I;
8293     if (isOneOf(S, I) != I)
8294       CheckScheduleForI(I);
8295     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8296                       << "\n");
8297     return true;
8298   }
8299   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8300          "Expected to reach top of the basic block or instruction down the "
8301          "lower end.");
8302   assert(I->getParent() == ScheduleEnd->getParent() &&
8303          "Instruction is in wrong basic block.");
8304   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8305                    nullptr);
8306   ScheduleEnd = I->getNextNode();
8307   if (isOneOf(S, I) != I)
8308     CheckScheduleForI(I);
8309   assert(ScheduleEnd && "tried to vectorize a terminator?");
8310   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8311   return true;
8312 }
8313 
8314 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8315                                                 Instruction *ToI,
8316                                                 ScheduleData *PrevLoadStore,
8317                                                 ScheduleData *NextLoadStore) {
8318   ScheduleData *CurrentLoadStore = PrevLoadStore;
8319   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8320     // No need to allocate data for non-schedulable instructions.
8321     if (doesNotNeedToBeScheduled(I))
8322       continue;
8323     ScheduleData *SD = ScheduleDataMap.lookup(I);
8324     if (!SD) {
8325       SD = allocateScheduleDataChunks();
8326       ScheduleDataMap[I] = SD;
8327       SD->Inst = I;
8328     }
8329     assert(!isInSchedulingRegion(SD) &&
8330            "new ScheduleData already in scheduling region");
8331     SD->init(SchedulingRegionID, I);
8332 
8333     if (I->mayReadOrWriteMemory() &&
8334         (!isa<IntrinsicInst>(I) ||
8335          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8336           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8337               Intrinsic::pseudoprobe))) {
8338       // Update the linked list of memory accessing instructions.
8339       if (CurrentLoadStore) {
8340         CurrentLoadStore->NextLoadStore = SD;
8341       } else {
8342         FirstLoadStoreInRegion = SD;
8343       }
8344       CurrentLoadStore = SD;
8345     }
8346 
8347     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8348         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8349       RegionHasStackSave = true;
8350   }
8351   if (NextLoadStore) {
8352     if (CurrentLoadStore)
8353       CurrentLoadStore->NextLoadStore = NextLoadStore;
8354   } else {
8355     LastLoadStoreInRegion = CurrentLoadStore;
8356   }
8357 }
8358 
8359 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8360                                                      bool InsertInReadyList,
8361                                                      BoUpSLP *SLP) {
8362   assert(SD->isSchedulingEntity());
8363 
8364   SmallVector<ScheduleData *, 10> WorkList;
8365   WorkList.push_back(SD);
8366 
8367   while (!WorkList.empty()) {
8368     ScheduleData *SD = WorkList.pop_back_val();
8369     for (ScheduleData *BundleMember = SD; BundleMember;
8370          BundleMember = BundleMember->NextInBundle) {
8371       assert(isInSchedulingRegion(BundleMember));
8372       if (BundleMember->hasValidDependencies())
8373         continue;
8374 
8375       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8376                  << "\n");
8377       BundleMember->Dependencies = 0;
8378       BundleMember->resetUnscheduledDeps();
8379 
8380       // Handle def-use chain dependencies.
8381       if (BundleMember->OpValue != BundleMember->Inst) {
8382         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8383           BundleMember->Dependencies++;
8384           ScheduleData *DestBundle = UseSD->FirstInBundle;
8385           if (!DestBundle->IsScheduled)
8386             BundleMember->incrementUnscheduledDeps(1);
8387           if (!DestBundle->hasValidDependencies())
8388             WorkList.push_back(DestBundle);
8389         }
8390       } else {
8391         for (User *U : BundleMember->Inst->users()) {
8392           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8393             BundleMember->Dependencies++;
8394             ScheduleData *DestBundle = UseSD->FirstInBundle;
8395             if (!DestBundle->IsScheduled)
8396               BundleMember->incrementUnscheduledDeps(1);
8397             if (!DestBundle->hasValidDependencies())
8398               WorkList.push_back(DestBundle);
8399           }
8400         }
8401       }
8402 
8403       auto makeControlDependent = [&](Instruction *I) {
8404         auto *DepDest = getScheduleData(I);
8405         assert(DepDest && "must be in schedule window");
8406         DepDest->ControlDependencies.push_back(BundleMember);
8407         BundleMember->Dependencies++;
8408         ScheduleData *DestBundle = DepDest->FirstInBundle;
8409         if (!DestBundle->IsScheduled)
8410           BundleMember->incrementUnscheduledDeps(1);
8411         if (!DestBundle->hasValidDependencies())
8412           WorkList.push_back(DestBundle);
8413       };
8414 
8415       // Any instruction which isn't safe to speculate at the begining of the
8416       // block is control dependend on any early exit or non-willreturn call
8417       // which proceeds it.
8418       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8419         for (Instruction *I = BundleMember->Inst->getNextNode();
8420              I != ScheduleEnd; I = I->getNextNode()) {
8421           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8422             continue;
8423 
8424           // Add the dependency
8425           makeControlDependent(I);
8426 
8427           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8428             // Everything past here must be control dependent on I.
8429             break;
8430         }
8431       }
8432 
8433       if (RegionHasStackSave) {
8434         // If we have an inalloc alloca instruction, it needs to be scheduled
8435         // after any preceeding stacksave.  We also need to prevent any alloca
8436         // from reordering above a preceeding stackrestore.
8437         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8438             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8439           for (Instruction *I = BundleMember->Inst->getNextNode();
8440                I != ScheduleEnd; I = I->getNextNode()) {
8441             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8442                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8443               // Any allocas past here must be control dependent on I, and I
8444               // must be memory dependend on BundleMember->Inst.
8445               break;
8446 
8447             if (!isa<AllocaInst>(I))
8448               continue;
8449 
8450             // Add the dependency
8451             makeControlDependent(I);
8452           }
8453         }
8454 
8455         // In addition to the cases handle just above, we need to prevent
8456         // allocas from moving below a stacksave.  The stackrestore case
8457         // is currently thought to be conservatism.
8458         if (isa<AllocaInst>(BundleMember->Inst)) {
8459           for (Instruction *I = BundleMember->Inst->getNextNode();
8460                I != ScheduleEnd; I = I->getNextNode()) {
8461             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8462                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8463               continue;
8464 
8465             // Add the dependency
8466             makeControlDependent(I);
8467             break;
8468           }
8469         }
8470       }
8471 
8472       // Handle the memory dependencies (if any).
8473       ScheduleData *DepDest = BundleMember->NextLoadStore;
8474       if (!DepDest)
8475         continue;
8476       Instruction *SrcInst = BundleMember->Inst;
8477       assert(SrcInst->mayReadOrWriteMemory() &&
8478              "NextLoadStore list for non memory effecting bundle?");
8479       MemoryLocation SrcLoc = getLocation(SrcInst);
8480       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8481       unsigned numAliased = 0;
8482       unsigned DistToSrc = 1;
8483 
8484       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8485         assert(isInSchedulingRegion(DepDest));
8486 
8487         // We have two limits to reduce the complexity:
8488         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8489         //    SLP->isAliased (which is the expensive part in this loop).
8490         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8491         //    the whole loop (even if the loop is fast, it's quadratic).
8492         //    It's important for the loop break condition (see below) to
8493         //    check this limit even between two read-only instructions.
8494         if (DistToSrc >= MaxMemDepDistance ||
8495             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8496              (numAliased >= AliasedCheckLimit ||
8497               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8498 
8499           // We increment the counter only if the locations are aliased
8500           // (instead of counting all alias checks). This gives a better
8501           // balance between reduced runtime and accurate dependencies.
8502           numAliased++;
8503 
8504           DepDest->MemoryDependencies.push_back(BundleMember);
8505           BundleMember->Dependencies++;
8506           ScheduleData *DestBundle = DepDest->FirstInBundle;
8507           if (!DestBundle->IsScheduled) {
8508             BundleMember->incrementUnscheduledDeps(1);
8509           }
8510           if (!DestBundle->hasValidDependencies()) {
8511             WorkList.push_back(DestBundle);
8512           }
8513         }
8514 
8515         // Example, explaining the loop break condition: Let's assume our
8516         // starting instruction is i0 and MaxMemDepDistance = 3.
8517         //
8518         //                      +--------v--v--v
8519         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8520         //             +--------^--^--^
8521         //
8522         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8523         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8524         // Previously we already added dependencies from i3 to i6,i7,i8
8525         // (because of MaxMemDepDistance). As we added a dependency from
8526         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8527         // and we can abort this loop at i6.
8528         if (DistToSrc >= 2 * MaxMemDepDistance)
8529           break;
8530         DistToSrc++;
8531       }
8532     }
8533     if (InsertInReadyList && SD->isReady()) {
8534       ReadyInsts.insert(SD);
8535       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8536                         << "\n");
8537     }
8538   }
8539 }
8540 
8541 void BoUpSLP::BlockScheduling::resetSchedule() {
8542   assert(ScheduleStart &&
8543          "tried to reset schedule on block which has not been scheduled");
8544   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8545     doForAllOpcodes(I, [&](ScheduleData *SD) {
8546       assert(isInSchedulingRegion(SD) &&
8547              "ScheduleData not in scheduling region");
8548       SD->IsScheduled = false;
8549       SD->resetUnscheduledDeps();
8550     });
8551   }
8552   ReadyInsts.clear();
8553 }
8554 
8555 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8556   if (!BS->ScheduleStart)
8557     return;
8558 
8559   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8560 
8561   // A key point - if we got here, pre-scheduling was able to find a valid
8562   // scheduling of the sub-graph of the scheduling window which consists
8563   // of all vector bundles and their transitive users.  As such, we do not
8564   // need to reschedule anything *outside of* that subgraph.
8565 
8566   BS->resetSchedule();
8567 
8568   // For the real scheduling we use a more sophisticated ready-list: it is
8569   // sorted by the original instruction location. This lets the final schedule
8570   // be as  close as possible to the original instruction order.
8571   // WARNING: If changing this order causes a correctness issue, that means
8572   // there is some missing dependence edge in the schedule data graph.
8573   struct ScheduleDataCompare {
8574     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8575       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8576     }
8577   };
8578   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8579 
8580   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8581   // and fill the ready-list with initial instructions.
8582   int Idx = 0;
8583   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8584        I = I->getNextNode()) {
8585     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8586       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8587       (void)SDTE;
8588       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8589               SD->isPartOfBundle() ==
8590                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8591              "scheduler and vectorizer bundle mismatch");
8592       SD->FirstInBundle->SchedulingPriority = Idx++;
8593 
8594       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8595         BS->calculateDependencies(SD, false, this);
8596     });
8597   }
8598   BS->initialFillReadyList(ReadyInsts);
8599 
8600   Instruction *LastScheduledInst = BS->ScheduleEnd;
8601 
8602   // Do the "real" scheduling.
8603   while (!ReadyInsts.empty()) {
8604     ScheduleData *picked = *ReadyInsts.begin();
8605     ReadyInsts.erase(ReadyInsts.begin());
8606 
8607     // Move the scheduled instruction(s) to their dedicated places, if not
8608     // there yet.
8609     for (ScheduleData *BundleMember = picked; BundleMember;
8610          BundleMember = BundleMember->NextInBundle) {
8611       Instruction *pickedInst = BundleMember->Inst;
8612       if (pickedInst->getNextNode() != LastScheduledInst)
8613         pickedInst->moveBefore(LastScheduledInst);
8614       LastScheduledInst = pickedInst;
8615     }
8616 
8617     BS->schedule(picked, ReadyInsts);
8618   }
8619 
8620   // Check that we didn't break any of our invariants.
8621 #ifdef EXPENSIVE_CHECKS
8622   BS->verify();
8623 #endif
8624 
8625 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8626   // Check that all schedulable entities got scheduled
8627   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8628     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8629       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8630         assert(SD->IsScheduled && "must be scheduled at this point");
8631       }
8632     });
8633   }
8634 #endif
8635 
8636   // Avoid duplicate scheduling of the block.
8637   BS->ScheduleStart = nullptr;
8638 }
8639 
8640 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8641   // If V is a store, just return the width of the stored value (or value
8642   // truncated just before storing) without traversing the expression tree.
8643   // This is the common case.
8644   if (auto *Store = dyn_cast<StoreInst>(V)) {
8645     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8646       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8647     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8648   }
8649 
8650   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8651     return getVectorElementSize(IEI->getOperand(1));
8652 
8653   auto E = InstrElementSize.find(V);
8654   if (E != InstrElementSize.end())
8655     return E->second;
8656 
8657   // If V is not a store, we can traverse the expression tree to find loads
8658   // that feed it. The type of the loaded value may indicate a more suitable
8659   // width than V's type. We want to base the vector element size on the width
8660   // of memory operations where possible.
8661   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8662   SmallPtrSet<Instruction *, 16> Visited;
8663   if (auto *I = dyn_cast<Instruction>(V)) {
8664     Worklist.emplace_back(I, I->getParent());
8665     Visited.insert(I);
8666   }
8667 
8668   // Traverse the expression tree in bottom-up order looking for loads. If we
8669   // encounter an instruction we don't yet handle, we give up.
8670   auto Width = 0u;
8671   while (!Worklist.empty()) {
8672     Instruction *I;
8673     BasicBlock *Parent;
8674     std::tie(I, Parent) = Worklist.pop_back_val();
8675 
8676     // We should only be looking at scalar instructions here. If the current
8677     // instruction has a vector type, skip.
8678     auto *Ty = I->getType();
8679     if (isa<VectorType>(Ty))
8680       continue;
8681 
8682     // If the current instruction is a load, update MaxWidth to reflect the
8683     // width of the loaded value.
8684     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8685         isa<ExtractValueInst>(I))
8686       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8687 
8688     // Otherwise, we need to visit the operands of the instruction. We only
8689     // handle the interesting cases from buildTree here. If an operand is an
8690     // instruction we haven't yet visited and from the same basic block as the
8691     // user or the use is a PHI node, we add it to the worklist.
8692     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8693              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8694              isa<UnaryOperator>(I)) {
8695       for (Use &U : I->operands())
8696         if (auto *J = dyn_cast<Instruction>(U.get()))
8697           if (Visited.insert(J).second &&
8698               (isa<PHINode>(I) || J->getParent() == Parent))
8699             Worklist.emplace_back(J, J->getParent());
8700     } else {
8701       break;
8702     }
8703   }
8704 
8705   // If we didn't encounter a memory access in the expression tree, or if we
8706   // gave up for some reason, just return the width of V. Otherwise, return the
8707   // maximum width we found.
8708   if (!Width) {
8709     if (auto *CI = dyn_cast<CmpInst>(V))
8710       V = CI->getOperand(0);
8711     Width = DL->getTypeSizeInBits(V->getType());
8712   }
8713 
8714   for (Instruction *I : Visited)
8715     InstrElementSize[I] = Width;
8716 
8717   return Width;
8718 }
8719 
8720 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8721 // smaller type with a truncation. We collect the values that will be demoted
8722 // in ToDemote and additional roots that require investigating in Roots.
8723 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8724                                   SmallVectorImpl<Value *> &ToDemote,
8725                                   SmallVectorImpl<Value *> &Roots) {
8726   // We can always demote constants.
8727   if (isa<Constant>(V)) {
8728     ToDemote.push_back(V);
8729     return true;
8730   }
8731 
8732   // If the value is not an instruction in the expression with only one use, it
8733   // cannot be demoted.
8734   auto *I = dyn_cast<Instruction>(V);
8735   if (!I || !I->hasOneUse() || !Expr.count(I))
8736     return false;
8737 
8738   switch (I->getOpcode()) {
8739 
8740   // We can always demote truncations and extensions. Since truncations can
8741   // seed additional demotion, we save the truncated value.
8742   case Instruction::Trunc:
8743     Roots.push_back(I->getOperand(0));
8744     break;
8745   case Instruction::ZExt:
8746   case Instruction::SExt:
8747     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8748         isa<InsertElementInst>(I->getOperand(0)))
8749       return false;
8750     break;
8751 
8752   // We can demote certain binary operations if we can demote both of their
8753   // operands.
8754   case Instruction::Add:
8755   case Instruction::Sub:
8756   case Instruction::Mul:
8757   case Instruction::And:
8758   case Instruction::Or:
8759   case Instruction::Xor:
8760     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8761         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8762       return false;
8763     break;
8764 
8765   // We can demote selects if we can demote their true and false values.
8766   case Instruction::Select: {
8767     SelectInst *SI = cast<SelectInst>(I);
8768     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8769         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8770       return false;
8771     break;
8772   }
8773 
8774   // We can demote phis if we can demote all their incoming operands. Note that
8775   // we don't need to worry about cycles since we ensure single use above.
8776   case Instruction::PHI: {
8777     PHINode *PN = cast<PHINode>(I);
8778     for (Value *IncValue : PN->incoming_values())
8779       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8780         return false;
8781     break;
8782   }
8783 
8784   // Otherwise, conservatively give up.
8785   default:
8786     return false;
8787   }
8788 
8789   // Record the value that we can demote.
8790   ToDemote.push_back(V);
8791   return true;
8792 }
8793 
8794 void BoUpSLP::computeMinimumValueSizes() {
8795   // If there are no external uses, the expression tree must be rooted by a
8796   // store. We can't demote in-memory values, so there is nothing to do here.
8797   if (ExternalUses.empty())
8798     return;
8799 
8800   // We only attempt to truncate integer expressions.
8801   auto &TreeRoot = VectorizableTree[0]->Scalars;
8802   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8803   if (!TreeRootIT)
8804     return;
8805 
8806   // If the expression is not rooted by a store, these roots should have
8807   // external uses. We will rely on InstCombine to rewrite the expression in
8808   // the narrower type. However, InstCombine only rewrites single-use values.
8809   // This means that if a tree entry other than a root is used externally, it
8810   // must have multiple uses and InstCombine will not rewrite it. The code
8811   // below ensures that only the roots are used externally.
8812   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8813   for (auto &EU : ExternalUses)
8814     if (!Expr.erase(EU.Scalar))
8815       return;
8816   if (!Expr.empty())
8817     return;
8818 
8819   // Collect the scalar values of the vectorizable expression. We will use this
8820   // context to determine which values can be demoted. If we see a truncation,
8821   // we mark it as seeding another demotion.
8822   for (auto &EntryPtr : VectorizableTree)
8823     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8824 
8825   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8826   // have a single external user that is not in the vectorizable tree.
8827   for (auto *Root : TreeRoot)
8828     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8829       return;
8830 
8831   // Conservatively determine if we can actually truncate the roots of the
8832   // expression. Collect the values that can be demoted in ToDemote and
8833   // additional roots that require investigating in Roots.
8834   SmallVector<Value *, 32> ToDemote;
8835   SmallVector<Value *, 4> Roots;
8836   for (auto *Root : TreeRoot)
8837     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8838       return;
8839 
8840   // The maximum bit width required to represent all the values that can be
8841   // demoted without loss of precision. It would be safe to truncate the roots
8842   // of the expression to this width.
8843   auto MaxBitWidth = 8u;
8844 
8845   // We first check if all the bits of the roots are demanded. If they're not,
8846   // we can truncate the roots to this narrower type.
8847   for (auto *Root : TreeRoot) {
8848     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8849     MaxBitWidth = std::max<unsigned>(
8850         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8851   }
8852 
8853   // True if the roots can be zero-extended back to their original type, rather
8854   // than sign-extended. We know that if the leading bits are not demanded, we
8855   // can safely zero-extend. So we initialize IsKnownPositive to True.
8856   bool IsKnownPositive = true;
8857 
8858   // If all the bits of the roots are demanded, we can try a little harder to
8859   // compute a narrower type. This can happen, for example, if the roots are
8860   // getelementptr indices. InstCombine promotes these indices to the pointer
8861   // width. Thus, all their bits are technically demanded even though the
8862   // address computation might be vectorized in a smaller type.
8863   //
8864   // We start by looking at each entry that can be demoted. We compute the
8865   // maximum bit width required to store the scalar by using ValueTracking to
8866   // compute the number of high-order bits we can truncate.
8867   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8868       llvm::all_of(TreeRoot, [](Value *R) {
8869         assert(R->hasOneUse() && "Root should have only one use!");
8870         return isa<GetElementPtrInst>(R->user_back());
8871       })) {
8872     MaxBitWidth = 8u;
8873 
8874     // Determine if the sign bit of all the roots is known to be zero. If not,
8875     // IsKnownPositive is set to False.
8876     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8877       KnownBits Known = computeKnownBits(R, *DL);
8878       return Known.isNonNegative();
8879     });
8880 
8881     // Determine the maximum number of bits required to store the scalar
8882     // values.
8883     for (auto *Scalar : ToDemote) {
8884       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8885       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8886       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8887     }
8888 
8889     // If we can't prove that the sign bit is zero, we must add one to the
8890     // maximum bit width to account for the unknown sign bit. This preserves
8891     // the existing sign bit so we can safely sign-extend the root back to the
8892     // original type. Otherwise, if we know the sign bit is zero, we will
8893     // zero-extend the root instead.
8894     //
8895     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8896     //        one to the maximum bit width will yield a larger-than-necessary
8897     //        type. In general, we need to add an extra bit only if we can't
8898     //        prove that the upper bit of the original type is equal to the
8899     //        upper bit of the proposed smaller type. If these two bits are the
8900     //        same (either zero or one) we know that sign-extending from the
8901     //        smaller type will result in the same value. Here, since we can't
8902     //        yet prove this, we are just making the proposed smaller type
8903     //        larger to ensure correctness.
8904     if (!IsKnownPositive)
8905       ++MaxBitWidth;
8906   }
8907 
8908   // Round MaxBitWidth up to the next power-of-two.
8909   if (!isPowerOf2_64(MaxBitWidth))
8910     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8911 
8912   // If the maximum bit width we compute is less than the with of the roots'
8913   // type, we can proceed with the narrowing. Otherwise, do nothing.
8914   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8915     return;
8916 
8917   // If we can truncate the root, we must collect additional values that might
8918   // be demoted as a result. That is, those seeded by truncations we will
8919   // modify.
8920   while (!Roots.empty())
8921     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8922 
8923   // Finally, map the values we can demote to the maximum bit with we computed.
8924   for (auto *Scalar : ToDemote)
8925     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8926 }
8927 
8928 namespace {
8929 
8930 /// The SLPVectorizer Pass.
8931 struct SLPVectorizer : public FunctionPass {
8932   SLPVectorizerPass Impl;
8933 
8934   /// Pass identification, replacement for typeid
8935   static char ID;
8936 
8937   explicit SLPVectorizer() : FunctionPass(ID) {
8938     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8939   }
8940 
8941   bool doInitialization(Module &M) override { return false; }
8942 
8943   bool runOnFunction(Function &F) override {
8944     if (skipFunction(F))
8945       return false;
8946 
8947     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8948     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8949     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8950     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8951     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8952     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8953     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8954     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8955     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8956     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8957 
8958     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8959   }
8960 
8961   void getAnalysisUsage(AnalysisUsage &AU) const override {
8962     FunctionPass::getAnalysisUsage(AU);
8963     AU.addRequired<AssumptionCacheTracker>();
8964     AU.addRequired<ScalarEvolutionWrapperPass>();
8965     AU.addRequired<AAResultsWrapperPass>();
8966     AU.addRequired<TargetTransformInfoWrapperPass>();
8967     AU.addRequired<LoopInfoWrapperPass>();
8968     AU.addRequired<DominatorTreeWrapperPass>();
8969     AU.addRequired<DemandedBitsWrapperPass>();
8970     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8971     AU.addRequired<InjectTLIMappingsLegacy>();
8972     AU.addPreserved<LoopInfoWrapperPass>();
8973     AU.addPreserved<DominatorTreeWrapperPass>();
8974     AU.addPreserved<AAResultsWrapperPass>();
8975     AU.addPreserved<GlobalsAAWrapperPass>();
8976     AU.setPreservesCFG();
8977   }
8978 };
8979 
8980 } // end anonymous namespace
8981 
8982 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8983   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8984   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8985   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8986   auto *AA = &AM.getResult<AAManager>(F);
8987   auto *LI = &AM.getResult<LoopAnalysis>(F);
8988   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8989   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8990   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8991   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8992 
8993   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8994   if (!Changed)
8995     return PreservedAnalyses::all();
8996 
8997   PreservedAnalyses PA;
8998   PA.preserveSet<CFGAnalyses>();
8999   return PA;
9000 }
9001 
9002 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
9003                                 TargetTransformInfo *TTI_,
9004                                 TargetLibraryInfo *TLI_, AAResults *AA_,
9005                                 LoopInfo *LI_, DominatorTree *DT_,
9006                                 AssumptionCache *AC_, DemandedBits *DB_,
9007                                 OptimizationRemarkEmitter *ORE_) {
9008   if (!RunSLPVectorization)
9009     return false;
9010   SE = SE_;
9011   TTI = TTI_;
9012   TLI = TLI_;
9013   AA = AA_;
9014   LI = LI_;
9015   DT = DT_;
9016   AC = AC_;
9017   DB = DB_;
9018   DL = &F.getParent()->getDataLayout();
9019 
9020   Stores.clear();
9021   GEPs.clear();
9022   bool Changed = false;
9023 
9024   // If the target claims to have no vector registers don't attempt
9025   // vectorization.
9026   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
9027     LLVM_DEBUG(
9028         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
9029     return false;
9030   }
9031 
9032   // Don't vectorize when the attribute NoImplicitFloat is used.
9033   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
9034     return false;
9035 
9036   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
9037 
9038   // Use the bottom up slp vectorizer to construct chains that start with
9039   // store instructions.
9040   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
9041 
9042   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
9043   // delete instructions.
9044 
9045   // Update DFS numbers now so that we can use them for ordering.
9046   DT->updateDFSNumbers();
9047 
9048   // Scan the blocks in the function in post order.
9049   for (auto BB : post_order(&F.getEntryBlock())) {
9050     // Start new block - clear the list of reduction roots.
9051     R.clearReductionData();
9052     collectSeedInstructions(BB);
9053 
9054     // Vectorize trees that end at stores.
9055     if (!Stores.empty()) {
9056       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
9057                         << " underlying objects.\n");
9058       Changed |= vectorizeStoreChains(R);
9059     }
9060 
9061     // Vectorize trees that end at reductions.
9062     Changed |= vectorizeChainsInBlock(BB, R);
9063 
9064     // Vectorize the index computations of getelementptr instructions. This
9065     // is primarily intended to catch gather-like idioms ending at
9066     // non-consecutive loads.
9067     if (!GEPs.empty()) {
9068       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
9069                         << " underlying objects.\n");
9070       Changed |= vectorizeGEPIndices(BB, R);
9071     }
9072   }
9073 
9074   if (Changed) {
9075     R.optimizeGatherSequence();
9076     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
9077   }
9078   return Changed;
9079 }
9080 
9081 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
9082                                             unsigned Idx) {
9083   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
9084                     << "\n");
9085   const unsigned Sz = R.getVectorElementSize(Chain[0]);
9086   const unsigned MinVF = R.getMinVecRegSize() / Sz;
9087   unsigned VF = Chain.size();
9088 
9089   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
9090     return false;
9091 
9092   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
9093                     << "\n");
9094 
9095   R.buildTree(Chain);
9096   if (R.isTreeTinyAndNotFullyVectorizable())
9097     return false;
9098   if (R.isLoadCombineCandidate())
9099     return false;
9100   R.reorderTopToBottom();
9101   R.reorderBottomToTop();
9102   R.buildExternalUses();
9103 
9104   R.computeMinimumValueSizes();
9105 
9106   InstructionCost Cost = R.getTreeCost();
9107 
9108   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
9109   if (Cost < -SLPCostThreshold) {
9110     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
9111 
9112     using namespace ore;
9113 
9114     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
9115                                         cast<StoreInst>(Chain[0]))
9116                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
9117                      << " and with tree size "
9118                      << NV("TreeSize", R.getTreeSize()));
9119 
9120     R.vectorizeTree();
9121     return true;
9122   }
9123 
9124   return false;
9125 }
9126 
9127 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
9128                                         BoUpSLP &R) {
9129   // We may run into multiple chains that merge into a single chain. We mark the
9130   // stores that we vectorized so that we don't visit the same store twice.
9131   BoUpSLP::ValueSet VectorizedStores;
9132   bool Changed = false;
9133 
9134   int E = Stores.size();
9135   SmallBitVector Tails(E, false);
9136   int MaxIter = MaxStoreLookup.getValue();
9137   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
9138       E, std::make_pair(E, INT_MAX));
9139   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
9140   int IterCnt;
9141   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
9142                                   &CheckedPairs,
9143                                   &ConsecutiveChain](int K, int Idx) {
9144     if (IterCnt >= MaxIter)
9145       return true;
9146     if (CheckedPairs[Idx].test(K))
9147       return ConsecutiveChain[K].second == 1 &&
9148              ConsecutiveChain[K].first == Idx;
9149     ++IterCnt;
9150     CheckedPairs[Idx].set(K);
9151     CheckedPairs[K].set(Idx);
9152     Optional<int> Diff = getPointersDiff(
9153         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
9154         Stores[Idx]->getValueOperand()->getType(),
9155         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
9156     if (!Diff || *Diff == 0)
9157       return false;
9158     int Val = *Diff;
9159     if (Val < 0) {
9160       if (ConsecutiveChain[Idx].second > -Val) {
9161         Tails.set(K);
9162         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
9163       }
9164       return false;
9165     }
9166     if (ConsecutiveChain[K].second <= Val)
9167       return false;
9168 
9169     Tails.set(Idx);
9170     ConsecutiveChain[K] = std::make_pair(Idx, Val);
9171     return Val == 1;
9172   };
9173   // Do a quadratic search on all of the given stores in reverse order and find
9174   // all of the pairs of stores that follow each other.
9175   for (int Idx = E - 1; Idx >= 0; --Idx) {
9176     // If a store has multiple consecutive store candidates, search according
9177     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
9178     // This is because usually pairing with immediate succeeding or preceding
9179     // candidate create the best chance to find slp vectorization opportunity.
9180     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
9181     IterCnt = 0;
9182     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
9183       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
9184           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
9185         break;
9186   }
9187 
9188   // Tracks if we tried to vectorize stores starting from the given tail
9189   // already.
9190   SmallBitVector TriedTails(E, false);
9191   // For stores that start but don't end a link in the chain:
9192   for (int Cnt = E; Cnt > 0; --Cnt) {
9193     int I = Cnt - 1;
9194     if (ConsecutiveChain[I].first == E || Tails.test(I))
9195       continue;
9196     // We found a store instr that starts a chain. Now follow the chain and try
9197     // to vectorize it.
9198     BoUpSLP::ValueList Operands;
9199     // Collect the chain into a list.
9200     while (I != E && !VectorizedStores.count(Stores[I])) {
9201       Operands.push_back(Stores[I]);
9202       Tails.set(I);
9203       if (ConsecutiveChain[I].second != 1) {
9204         // Mark the new end in the chain and go back, if required. It might be
9205         // required if the original stores come in reversed order, for example.
9206         if (ConsecutiveChain[I].first != E &&
9207             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
9208             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
9209           TriedTails.set(I);
9210           Tails.reset(ConsecutiveChain[I].first);
9211           if (Cnt < ConsecutiveChain[I].first + 2)
9212             Cnt = ConsecutiveChain[I].first + 2;
9213         }
9214         break;
9215       }
9216       // Move to the next value in the chain.
9217       I = ConsecutiveChain[I].first;
9218     }
9219     assert(!Operands.empty() && "Expected non-empty list of stores.");
9220 
9221     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9222     unsigned EltSize = R.getVectorElementSize(Operands[0]);
9223     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
9224 
9225     unsigned MinVF = R.getMinVF(EltSize);
9226     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9227                               MaxElts);
9228 
9229     // FIXME: Is division-by-2 the correct step? Should we assert that the
9230     // register size is a power-of-2?
9231     unsigned StartIdx = 0;
9232     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9233       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9234         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9235         if (!VectorizedStores.count(Slice.front()) &&
9236             !VectorizedStores.count(Slice.back()) &&
9237             vectorizeStoreChain(Slice, R, Cnt)) {
9238           // Mark the vectorized stores so that we don't vectorize them again.
9239           VectorizedStores.insert(Slice.begin(), Slice.end());
9240           Changed = true;
9241           // If we vectorized initial block, no need to try to vectorize it
9242           // again.
9243           if (Cnt == StartIdx)
9244             StartIdx += Size;
9245           Cnt += Size;
9246           continue;
9247         }
9248         ++Cnt;
9249       }
9250       // Check if the whole array was vectorized already - exit.
9251       if (StartIdx >= Operands.size())
9252         break;
9253     }
9254   }
9255 
9256   return Changed;
9257 }
9258 
9259 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9260   // Initialize the collections. We will make a single pass over the block.
9261   Stores.clear();
9262   GEPs.clear();
9263 
9264   // Visit the store and getelementptr instructions in BB and organize them in
9265   // Stores and GEPs according to the underlying objects of their pointer
9266   // operands.
9267   for (Instruction &I : *BB) {
9268     // Ignore store instructions that are volatile or have a pointer operand
9269     // that doesn't point to a scalar type.
9270     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9271       if (!SI->isSimple())
9272         continue;
9273       if (!isValidElementType(SI->getValueOperand()->getType()))
9274         continue;
9275       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9276     }
9277 
9278     // Ignore getelementptr instructions that have more than one index, a
9279     // constant index, or a pointer operand that doesn't point to a scalar
9280     // type.
9281     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9282       auto Idx = GEP->idx_begin()->get();
9283       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9284         continue;
9285       if (!isValidElementType(Idx->getType()))
9286         continue;
9287       if (GEP->getType()->isVectorTy())
9288         continue;
9289       GEPs[GEP->getPointerOperand()].push_back(GEP);
9290     }
9291   }
9292 }
9293 
9294 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9295   if (!A || !B)
9296     return false;
9297   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9298     return false;
9299   Value *VL[] = {A, B};
9300   return tryToVectorizeList(VL, R);
9301 }
9302 
9303 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9304                                            bool LimitForRegisterSize) {
9305   if (VL.size() < 2)
9306     return false;
9307 
9308   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9309                     << VL.size() << ".\n");
9310 
9311   // Check that all of the parts are instructions of the same type,
9312   // we permit an alternate opcode via InstructionsState.
9313   InstructionsState S = getSameOpcode(VL);
9314   if (!S.getOpcode())
9315     return false;
9316 
9317   Instruction *I0 = cast<Instruction>(S.OpValue);
9318   // Make sure invalid types (including vector type) are rejected before
9319   // determining vectorization factor for scalar instructions.
9320   for (Value *V : VL) {
9321     Type *Ty = V->getType();
9322     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9323       // NOTE: the following will give user internal llvm type name, which may
9324       // not be useful.
9325       R.getORE()->emit([&]() {
9326         std::string type_str;
9327         llvm::raw_string_ostream rso(type_str);
9328         Ty->print(rso);
9329         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9330                << "Cannot SLP vectorize list: type "
9331                << rso.str() + " is unsupported by vectorizer";
9332       });
9333       return false;
9334     }
9335   }
9336 
9337   unsigned Sz = R.getVectorElementSize(I0);
9338   unsigned MinVF = R.getMinVF(Sz);
9339   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9340   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9341   if (MaxVF < 2) {
9342     R.getORE()->emit([&]() {
9343       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9344              << "Cannot SLP vectorize list: vectorization factor "
9345              << "less than 2 is not supported";
9346     });
9347     return false;
9348   }
9349 
9350   bool Changed = false;
9351   bool CandidateFound = false;
9352   InstructionCost MinCost = SLPCostThreshold.getValue();
9353   Type *ScalarTy = VL[0]->getType();
9354   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9355     ScalarTy = IE->getOperand(1)->getType();
9356 
9357   unsigned NextInst = 0, MaxInst = VL.size();
9358   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9359     // No actual vectorization should happen, if number of parts is the same as
9360     // provided vectorization factor (i.e. the scalar type is used for vector
9361     // code during codegen).
9362     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9363     if (TTI->getNumberOfParts(VecTy) == VF)
9364       continue;
9365     for (unsigned I = NextInst; I < MaxInst; ++I) {
9366       unsigned OpsWidth = 0;
9367 
9368       if (I + VF > MaxInst)
9369         OpsWidth = MaxInst - I;
9370       else
9371         OpsWidth = VF;
9372 
9373       if (!isPowerOf2_32(OpsWidth))
9374         continue;
9375 
9376       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9377           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9378         break;
9379 
9380       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9381       // Check that a previous iteration of this loop did not delete the Value.
9382       if (llvm::any_of(Ops, [&R](Value *V) {
9383             auto *I = dyn_cast<Instruction>(V);
9384             return I && R.isDeleted(I);
9385           }))
9386         continue;
9387 
9388       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9389                         << "\n");
9390 
9391       R.buildTree(Ops);
9392       if (R.isTreeTinyAndNotFullyVectorizable())
9393         continue;
9394       R.reorderTopToBottom();
9395       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9396       R.buildExternalUses();
9397 
9398       R.computeMinimumValueSizes();
9399       InstructionCost Cost = R.getTreeCost();
9400       CandidateFound = true;
9401       MinCost = std::min(MinCost, Cost);
9402 
9403       if (Cost < -SLPCostThreshold) {
9404         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9405         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9406                                                     cast<Instruction>(Ops[0]))
9407                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9408                                  << " and with tree size "
9409                                  << ore::NV("TreeSize", R.getTreeSize()));
9410 
9411         R.vectorizeTree();
9412         // Move to the next bundle.
9413         I += VF - 1;
9414         NextInst = I + 1;
9415         Changed = true;
9416       }
9417     }
9418   }
9419 
9420   if (!Changed && CandidateFound) {
9421     R.getORE()->emit([&]() {
9422       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9423              << "List vectorization was possible but not beneficial with cost "
9424              << ore::NV("Cost", MinCost) << " >= "
9425              << ore::NV("Treshold", -SLPCostThreshold);
9426     });
9427   } else if (!Changed) {
9428     R.getORE()->emit([&]() {
9429       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9430              << "Cannot SLP vectorize list: vectorization was impossible"
9431              << " with available vectorization factors";
9432     });
9433   }
9434   return Changed;
9435 }
9436 
9437 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9438   if (!I)
9439     return false;
9440 
9441   if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) ||
9442       isa<VectorType>(I->getType()))
9443     return false;
9444 
9445   Value *P = I->getParent();
9446 
9447   // Vectorize in current basic block only.
9448   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9449   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9450   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9451     return false;
9452 
9453   // First collect all possible candidates
9454   SmallVector<std::pair<Value *, Value *>, 4> Candidates;
9455   Candidates.emplace_back(Op0, Op1);
9456 
9457   auto *A = dyn_cast<BinaryOperator>(Op0);
9458   auto *B = dyn_cast<BinaryOperator>(Op1);
9459   // Try to skip B.
9460   if (A && B && B->hasOneUse()) {
9461     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9462     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9463     if (B0 && B0->getParent() == P)
9464       Candidates.emplace_back(A, B0);
9465     if (B1 && B1->getParent() == P)
9466       Candidates.emplace_back(A, B1);
9467   }
9468   // Try to skip A.
9469   if (B && A && A->hasOneUse()) {
9470     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9471     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9472     if (A0 && A0->getParent() == P)
9473       Candidates.emplace_back(A0, B);
9474     if (A1 && A1->getParent() == P)
9475       Candidates.emplace_back(A1, B);
9476   }
9477 
9478   if (Candidates.size() == 1)
9479     return tryToVectorizePair(Op0, Op1, R);
9480 
9481   // We have multiple options. Try to pick the single best.
9482   Optional<int> BestCandidate = R.findBestRootPair(Candidates);
9483   if (!BestCandidate)
9484     return false;
9485   return tryToVectorizePair(Candidates[*BestCandidate].first,
9486                             Candidates[*BestCandidate].second, R);
9487 }
9488 
9489 namespace {
9490 
9491 /// Model horizontal reductions.
9492 ///
9493 /// A horizontal reduction is a tree of reduction instructions that has values
9494 /// that can be put into a vector as its leaves. For example:
9495 ///
9496 /// mul mul mul mul
9497 ///  \  /    \  /
9498 ///   +       +
9499 ///    \     /
9500 ///       +
9501 /// This tree has "mul" as its leaf values and "+" as its reduction
9502 /// instructions. A reduction can feed into a store or a binary operation
9503 /// feeding a phi.
9504 ///    ...
9505 ///    \  /
9506 ///     +
9507 ///     |
9508 ///  phi +=
9509 ///
9510 ///  Or:
9511 ///    ...
9512 ///    \  /
9513 ///     +
9514 ///     |
9515 ///   *p =
9516 ///
9517 class HorizontalReduction {
9518   using ReductionOpsType = SmallVector<Value *, 16>;
9519   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9520   ReductionOpsListType ReductionOps;
9521   /// List of possibly reduced values.
9522   SmallVector<SmallVector<Value *>> ReducedVals;
9523   /// Maps reduced value to the corresponding reduction operation.
9524   DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
9525   // Use map vector to make stable output.
9526   MapVector<Instruction *, Value *> ExtraArgs;
9527   WeakTrackingVH ReductionRoot;
9528   /// The type of reduction operation.
9529   RecurKind RdxKind;
9530 
9531   static bool isCmpSelMinMax(Instruction *I) {
9532     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9533            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9534   }
9535 
9536   // And/or are potentially poison-safe logical patterns like:
9537   // select x, y, false
9538   // select x, true, y
9539   static bool isBoolLogicOp(Instruction *I) {
9540     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9541            match(I, m_LogicalOr(m_Value(), m_Value()));
9542   }
9543 
9544   /// Checks if instruction is associative and can be vectorized.
9545   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9546     if (Kind == RecurKind::None)
9547       return false;
9548 
9549     // Integer ops that map to select instructions or intrinsics are fine.
9550     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9551         isBoolLogicOp(I))
9552       return true;
9553 
9554     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9555       // FP min/max are associative except for NaN and -0.0. We do not
9556       // have to rule out -0.0 here because the intrinsic semantics do not
9557       // specify a fixed result for it.
9558       return I->getFastMathFlags().noNaNs();
9559     }
9560 
9561     return I->isAssociative();
9562   }
9563 
9564   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9565     // Poison-safe 'or' takes the form: select X, true, Y
9566     // To make that work with the normal operand processing, we skip the
9567     // true value operand.
9568     // TODO: Change the code and data structures to handle this without a hack.
9569     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9570       return I->getOperand(2);
9571     return I->getOperand(Index);
9572   }
9573 
9574   /// Creates reduction operation with the current opcode.
9575   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9576                          Value *RHS, const Twine &Name, bool UseSelect) {
9577     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9578     switch (Kind) {
9579     case RecurKind::Or:
9580       if (UseSelect &&
9581           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9582         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9583       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9584                                  Name);
9585     case RecurKind::And:
9586       if (UseSelect &&
9587           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9588         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9589       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9590                                  Name);
9591     case RecurKind::Add:
9592     case RecurKind::Mul:
9593     case RecurKind::Xor:
9594     case RecurKind::FAdd:
9595     case RecurKind::FMul:
9596       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9597                                  Name);
9598     case RecurKind::FMax:
9599       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9600     case RecurKind::FMin:
9601       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9602     case RecurKind::SMax:
9603       if (UseSelect) {
9604         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9605         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9606       }
9607       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9608     case RecurKind::SMin:
9609       if (UseSelect) {
9610         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9611         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9612       }
9613       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9614     case RecurKind::UMax:
9615       if (UseSelect) {
9616         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9617         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9618       }
9619       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9620     case RecurKind::UMin:
9621       if (UseSelect) {
9622         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9623         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9624       }
9625       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9626     default:
9627       llvm_unreachable("Unknown reduction operation.");
9628     }
9629   }
9630 
9631   /// Creates reduction operation with the current opcode with the IR flags
9632   /// from \p ReductionOps.
9633   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9634                          Value *RHS, const Twine &Name,
9635                          const ReductionOpsListType &ReductionOps) {
9636     bool UseSelect = ReductionOps.size() == 2 ||
9637                      // Logical or/and.
9638                      (ReductionOps.size() == 1 &&
9639                       isa<SelectInst>(ReductionOps.front().front()));
9640     assert((!UseSelect || ReductionOps.size() != 2 ||
9641             isa<SelectInst>(ReductionOps[1][0])) &&
9642            "Expected cmp + select pairs for reduction");
9643     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9644     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9645       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9646         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9647         propagateIRFlags(Op, ReductionOps[1]);
9648         return Op;
9649       }
9650     }
9651     propagateIRFlags(Op, ReductionOps[0]);
9652     return Op;
9653   }
9654 
9655   /// Creates reduction operation with the current opcode with the IR flags
9656   /// from \p I.
9657   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9658                          Value *RHS, const Twine &Name, Value *I) {
9659     auto *SelI = dyn_cast<SelectInst>(I);
9660     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9661     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9662       if (auto *Sel = dyn_cast<SelectInst>(Op))
9663         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9664     }
9665     propagateIRFlags(Op, I);
9666     return Op;
9667   }
9668 
9669   static RecurKind getRdxKind(Value *V) {
9670     auto *I = dyn_cast<Instruction>(V);
9671     if (!I)
9672       return RecurKind::None;
9673     if (match(I, m_Add(m_Value(), m_Value())))
9674       return RecurKind::Add;
9675     if (match(I, m_Mul(m_Value(), m_Value())))
9676       return RecurKind::Mul;
9677     if (match(I, m_And(m_Value(), m_Value())) ||
9678         match(I, m_LogicalAnd(m_Value(), m_Value())))
9679       return RecurKind::And;
9680     if (match(I, m_Or(m_Value(), m_Value())) ||
9681         match(I, m_LogicalOr(m_Value(), m_Value())))
9682       return RecurKind::Or;
9683     if (match(I, m_Xor(m_Value(), m_Value())))
9684       return RecurKind::Xor;
9685     if (match(I, m_FAdd(m_Value(), m_Value())))
9686       return RecurKind::FAdd;
9687     if (match(I, m_FMul(m_Value(), m_Value())))
9688       return RecurKind::FMul;
9689 
9690     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9691       return RecurKind::FMax;
9692     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9693       return RecurKind::FMin;
9694 
9695     // This matches either cmp+select or intrinsics. SLP is expected to handle
9696     // either form.
9697     // TODO: If we are canonicalizing to intrinsics, we can remove several
9698     //       special-case paths that deal with selects.
9699     if (match(I, m_SMax(m_Value(), m_Value())))
9700       return RecurKind::SMax;
9701     if (match(I, m_SMin(m_Value(), m_Value())))
9702       return RecurKind::SMin;
9703     if (match(I, m_UMax(m_Value(), m_Value())))
9704       return RecurKind::UMax;
9705     if (match(I, m_UMin(m_Value(), m_Value())))
9706       return RecurKind::UMin;
9707 
9708     if (auto *Select = dyn_cast<SelectInst>(I)) {
9709       // Try harder: look for min/max pattern based on instructions producing
9710       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9711       // During the intermediate stages of SLP, it's very common to have
9712       // pattern like this (since optimizeGatherSequence is run only once
9713       // at the end):
9714       // %1 = extractelement <2 x i32> %a, i32 0
9715       // %2 = extractelement <2 x i32> %a, i32 1
9716       // %cond = icmp sgt i32 %1, %2
9717       // %3 = extractelement <2 x i32> %a, i32 0
9718       // %4 = extractelement <2 x i32> %a, i32 1
9719       // %select = select i1 %cond, i32 %3, i32 %4
9720       CmpInst::Predicate Pred;
9721       Instruction *L1;
9722       Instruction *L2;
9723 
9724       Value *LHS = Select->getTrueValue();
9725       Value *RHS = Select->getFalseValue();
9726       Value *Cond = Select->getCondition();
9727 
9728       // TODO: Support inverse predicates.
9729       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9730         if (!isa<ExtractElementInst>(RHS) ||
9731             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9732           return RecurKind::None;
9733       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9734         if (!isa<ExtractElementInst>(LHS) ||
9735             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9736           return RecurKind::None;
9737       } else {
9738         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9739           return RecurKind::None;
9740         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9741             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9742             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9743           return RecurKind::None;
9744       }
9745 
9746       switch (Pred) {
9747       default:
9748         return RecurKind::None;
9749       case CmpInst::ICMP_SGT:
9750       case CmpInst::ICMP_SGE:
9751         return RecurKind::SMax;
9752       case CmpInst::ICMP_SLT:
9753       case CmpInst::ICMP_SLE:
9754         return RecurKind::SMin;
9755       case CmpInst::ICMP_UGT:
9756       case CmpInst::ICMP_UGE:
9757         return RecurKind::UMax;
9758       case CmpInst::ICMP_ULT:
9759       case CmpInst::ICMP_ULE:
9760         return RecurKind::UMin;
9761       }
9762     }
9763     return RecurKind::None;
9764   }
9765 
9766   /// Get the index of the first operand.
9767   static unsigned getFirstOperandIndex(Instruction *I) {
9768     return isCmpSelMinMax(I) ? 1 : 0;
9769   }
9770 
9771   /// Total number of operands in the reduction operation.
9772   static unsigned getNumberOfOperands(Instruction *I) {
9773     return isCmpSelMinMax(I) ? 3 : 2;
9774   }
9775 
9776   /// Checks if the instruction is in basic block \p BB.
9777   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9778   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9779     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9780       auto *Sel = cast<SelectInst>(I);
9781       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9782       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9783     }
9784     return I->getParent() == BB;
9785   }
9786 
9787   /// Expected number of uses for reduction operations/reduced values.
9788   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9789     if (IsCmpSelMinMax) {
9790       // SelectInst must be used twice while the condition op must have single
9791       // use only.
9792       if (auto *Sel = dyn_cast<SelectInst>(I))
9793         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9794       return I->hasNUses(2);
9795     }
9796 
9797     // Arithmetic reduction operation must be used once only.
9798     return I->hasOneUse();
9799   }
9800 
9801   /// Initializes the list of reduction operations.
9802   void initReductionOps(Instruction *I) {
9803     if (isCmpSelMinMax(I))
9804       ReductionOps.assign(2, ReductionOpsType());
9805     else
9806       ReductionOps.assign(1, ReductionOpsType());
9807   }
9808 
9809   /// Add all reduction operations for the reduction instruction \p I.
9810   void addReductionOps(Instruction *I) {
9811     if (isCmpSelMinMax(I)) {
9812       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9813       ReductionOps[1].emplace_back(I);
9814     } else {
9815       ReductionOps[0].emplace_back(I);
9816     }
9817   }
9818 
9819   static Value *getLHS(RecurKind Kind, Instruction *I) {
9820     if (Kind == RecurKind::None)
9821       return nullptr;
9822     return I->getOperand(getFirstOperandIndex(I));
9823   }
9824   static Value *getRHS(RecurKind Kind, Instruction *I) {
9825     if (Kind == RecurKind::None)
9826       return nullptr;
9827     return I->getOperand(getFirstOperandIndex(I) + 1);
9828   }
9829 
9830 public:
9831   HorizontalReduction() = default;
9832 
9833   /// Try to find a reduction tree.
9834   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9835                                  ScalarEvolution &SE, const DataLayout &DL,
9836                                  const TargetLibraryInfo &TLI) {
9837     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9838            "Phi needs to use the binary operator");
9839     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9840             isa<IntrinsicInst>(Inst)) &&
9841            "Expected binop, select, or intrinsic for reduction matching");
9842     RdxKind = getRdxKind(Inst);
9843 
9844     // We could have a initial reductions that is not an add.
9845     //  r *= v1 + v2 + v3 + v4
9846     // In such a case start looking for a tree rooted in the first '+'.
9847     if (Phi) {
9848       if (getLHS(RdxKind, Inst) == Phi) {
9849         Phi = nullptr;
9850         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9851         if (!Inst)
9852           return false;
9853         RdxKind = getRdxKind(Inst);
9854       } else if (getRHS(RdxKind, Inst) == Phi) {
9855         Phi = nullptr;
9856         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9857         if (!Inst)
9858           return false;
9859         RdxKind = getRdxKind(Inst);
9860       }
9861     }
9862 
9863     if (!isVectorizable(RdxKind, Inst))
9864       return false;
9865 
9866     // Analyze "regular" integer/FP types for reductions - no target-specific
9867     // types or pointers.
9868     Type *Ty = Inst->getType();
9869     if (!isValidElementType(Ty) || Ty->isPointerTy())
9870       return false;
9871 
9872     // Though the ultimate reduction may have multiple uses, its condition must
9873     // have only single use.
9874     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9875       if (!Sel->getCondition()->hasOneUse())
9876         return false;
9877 
9878     ReductionRoot = Inst;
9879 
9880     // Iterate through all the operands of the possible reduction tree and
9881     // gather all the reduced values, sorting them by their value id.
9882     BasicBlock *BB = Inst->getParent();
9883     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9884     SmallVector<Instruction *> Worklist(1, Inst);
9885     // Checks if the operands of the \p TreeN instruction are also reduction
9886     // operations or should be treated as reduced values or an extra argument,
9887     // which is not part of the reduction.
9888     auto &&CheckOperands = [this, IsCmpSelMinMax,
9889                             BB](Instruction *TreeN,
9890                                 SmallVectorImpl<Value *> &ExtraArgs,
9891                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9892                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9893       for (int I = getFirstOperandIndex(TreeN),
9894                End = getNumberOfOperands(TreeN);
9895            I < End; ++I) {
9896         Value *EdgeVal = getRdxOperand(TreeN, I);
9897         ReducedValsToOps[EdgeVal].push_back(TreeN);
9898         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9899         // Edge has wrong parent - mark as an extra argument.
9900         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9901             !hasSameParent(EdgeInst, BB)) {
9902           ExtraArgs.push_back(EdgeVal);
9903           continue;
9904         }
9905         // If the edge is not an instruction, or it is different from the main
9906         // reduction opcode or has too many uses - possible reduced value.
9907         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9908             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9909             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9910           PossibleReducedVals.push_back(EdgeVal);
9911           continue;
9912         }
9913         ReductionOps.push_back(EdgeInst);
9914       }
9915     };
9916     // Try to regroup reduced values so that it gets more profitable to try to
9917     // reduce them. Values are grouped by their value ids, instructions - by
9918     // instruction op id and/or alternate op id, plus do extra analysis for
9919     // loads (grouping them by the distabce between pointers) and cmp
9920     // instructions (grouping them by the predicate).
9921     MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
9922         PossibleReducedVals;
9923     initReductionOps(Inst);
9924     while (!Worklist.empty()) {
9925       Instruction *TreeN = Worklist.pop_back_val();
9926       SmallVector<Value *> Args;
9927       SmallVector<Value *> PossibleRedVals;
9928       SmallVector<Instruction *> PossibleReductionOps;
9929       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9930       // If too many extra args - mark the instruction itself as a reduction
9931       // value, not a reduction operation.
9932       if (Args.size() < 2) {
9933         addReductionOps(TreeN);
9934         // Add extra args.
9935         if (!Args.empty()) {
9936           assert(Args.size() == 1 && "Expected only single argument.");
9937           ExtraArgs[TreeN] = Args.front();
9938         }
9939         // Add reduction values. The values are sorted for better vectorization
9940         // results.
9941         for (Value *V : PossibleRedVals) {
9942           size_t Key, Idx;
9943           std::tie(Key, Idx) = generateKeySubkey(
9944               V, &TLI,
9945               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9946                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9947                   auto *RLI = cast<LoadInst>(LoadData.second.front().first);
9948                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9949                                       LI->getType(), LI->getPointerOperand(),
9950                                       DL, SE, /*StrictCheck=*/true))
9951                     return hash_value(RLI->getPointerOperand());
9952                 }
9953                 return hash_value(LI->getPointerOperand());
9954               },
9955               /*AllowAlternate=*/false);
9956           ++PossibleReducedVals[Key][Idx]
9957                 .insert(std::make_pair(V, 0))
9958                 .first->second;
9959         }
9960         Worklist.append(PossibleReductionOps.rbegin(),
9961                         PossibleReductionOps.rend());
9962       } else {
9963         size_t Key, Idx;
9964         std::tie(Key, Idx) = generateKeySubkey(
9965             TreeN, &TLI,
9966             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9967               for (const auto &LoadData : PossibleReducedVals[Key]) {
9968                 auto *RLI = cast<LoadInst>(LoadData.second.front().first);
9969                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9970                                     LI->getType(), LI->getPointerOperand(), DL,
9971                                     SE, /*StrictCheck=*/true))
9972                   return hash_value(RLI->getPointerOperand());
9973               }
9974               return hash_value(LI->getPointerOperand());
9975             },
9976             /*AllowAlternate=*/false);
9977         ++PossibleReducedVals[Key][Idx]
9978               .insert(std::make_pair(TreeN, 0))
9979               .first->second;
9980       }
9981     }
9982     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9983     // Sort values by the total number of values kinds to start the reduction
9984     // from the longest possible reduced values sequences.
9985     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9986       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9987       SmallVector<SmallVector<Value *>> PossibleRedValsVect;
9988       for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
9989            It != E; ++It) {
9990         PossibleRedValsVect.emplace_back();
9991         auto RedValsVect = It->second.takeVector();
9992         stable_sort(RedValsVect, [](const auto &P1, const auto &P2) {
9993           return P1.second < P2.second;
9994         });
9995         for (const std::pair<Value *, unsigned> &Data : RedValsVect)
9996           PossibleRedValsVect.back().append(Data.second, Data.first);
9997       }
9998       stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
9999         return P1.size() > P2.size();
10000       });
10001       ReducedVals.emplace_back();
10002       for (ArrayRef<Value *> Data : PossibleRedValsVect)
10003         ReducedVals.back().append(Data.rbegin(), Data.rend());
10004     }
10005     // Sort the reduced values by number of same/alternate opcode and/or pointer
10006     // operand.
10007     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
10008       return P1.size() > P2.size();
10009     });
10010     return true;
10011   }
10012 
10013   /// Attempt to vectorize the tree found by matchAssociativeReduction.
10014   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
10015     constexpr int ReductionLimit = 4;
10016     // If there are a sufficient number of reduction values, reduce
10017     // to a nearby power-of-2. We can safely generate oversized
10018     // vectors and rely on the backend to split them to legal sizes.
10019     unsigned NumReducedVals = std::accumulate(
10020         ReducedVals.begin(), ReducedVals.end(), 0,
10021         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
10022     if (NumReducedVals < ReductionLimit)
10023       return nullptr;
10024 
10025     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
10026 
10027     // Track the reduced values in case if they are replaced by extractelement
10028     // because of the vectorization.
10029     DenseMap<Value *, WeakTrackingVH> TrackedVals;
10030     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
10031     // The same extra argument may be used several times, so log each attempt
10032     // to use it.
10033     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
10034       assert(Pair.first && "DebugLoc must be set.");
10035       ExternallyUsedValues[Pair.second].push_back(Pair.first);
10036       TrackedVals.try_emplace(Pair.second, Pair.second);
10037     }
10038 
10039     // The compare instruction of a min/max is the insertion point for new
10040     // instructions and may be replaced with a new compare instruction.
10041     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
10042       assert(isa<SelectInst>(RdxRootInst) &&
10043              "Expected min/max reduction to have select root instruction");
10044       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
10045       assert(isa<Instruction>(ScalarCond) &&
10046              "Expected min/max reduction to have compare condition");
10047       return cast<Instruction>(ScalarCond);
10048     };
10049 
10050     // The reduction root is used as the insertion point for new instructions,
10051     // so set it as externally used to prevent it from being deleted.
10052     ExternallyUsedValues[ReductionRoot];
10053     SmallVector<Value *> IgnoreList;
10054     for (ReductionOpsType &RdxOps : ReductionOps)
10055       for (Value *RdxOp : RdxOps) {
10056         if (!RdxOp)
10057           continue;
10058         IgnoreList.push_back(RdxOp);
10059       }
10060     bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
10061 
10062     // Need to track reduced vals, they may be changed during vectorization of
10063     // subvectors.
10064     for (ArrayRef<Value *> Candidates : ReducedVals)
10065       for (Value *V : Candidates)
10066         TrackedVals.try_emplace(V, V);
10067 
10068     DenseMap<Value *, unsigned> VectorizedVals;
10069     Value *VectorizedTree = nullptr;
10070     bool CheckForReusedReductionOps = false;
10071     // Try to vectorize elements based on their type.
10072     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10073       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
10074       InstructionsState S = getSameOpcode(OrigReducedVals);
10075       SmallVector<Value *> Candidates;
10076       DenseMap<Value *, Value *> TrackedToOrig;
10077       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
10078         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
10079         // Check if the reduction value was not overriden by the extractelement
10080         // instruction because of the vectorization and exclude it, if it is not
10081         // compatible with other values.
10082         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10083           if (isVectorLikeInstWithConstOps(Inst) &&
10084               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
10085             continue;
10086         Candidates.push_back(RdxVal);
10087         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
10088       }
10089       bool ShuffledExtracts = false;
10090       // Try to handle shuffled extractelements.
10091       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
10092           I + 1 < E) {
10093         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
10094         if (NextS.getOpcode() == Instruction::ExtractElement &&
10095             !NextS.isAltShuffle()) {
10096           SmallVector<Value *> CommonCandidates(Candidates);
10097           for (Value *RV : ReducedVals[I + 1]) {
10098             Value *RdxVal = TrackedVals.find(RV)->second;
10099             // Check if the reduction value was not overriden by the
10100             // extractelement instruction because of the vectorization and
10101             // exclude it, if it is not compatible with other values.
10102             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
10103               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
10104                 continue;
10105             CommonCandidates.push_back(RdxVal);
10106             TrackedToOrig.try_emplace(RdxVal, RV);
10107           }
10108           SmallVector<int> Mask;
10109           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
10110             ++I;
10111             Candidates.swap(CommonCandidates);
10112             ShuffledExtracts = true;
10113           }
10114         }
10115       }
10116       unsigned NumReducedVals = Candidates.size();
10117       if (NumReducedVals < ReductionLimit)
10118         continue;
10119 
10120       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
10121       unsigned Start = 0;
10122       unsigned Pos = Start;
10123       // Restarts vectorization attempt with lower vector factor.
10124       unsigned PrevReduxWidth = ReduxWidth;
10125       bool CheckForReusedReductionOpsLocal = false;
10126       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
10127                                   &CheckForReusedReductionOpsLocal,
10128                                   &PrevReduxWidth, &V,
10129                                   &IgnoreList](bool IgnoreVL = false) {
10130         bool IsAnyRedOpGathered =
10131             !IgnoreVL && any_of(IgnoreList, [&V](Value *RedOp) {
10132               return V.isGathered(RedOp);
10133             });
10134         if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
10135           // Check if any of the reduction ops are gathered. If so, worth
10136           // trying again with less number of reduction ops.
10137           CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
10138         }
10139         ++Pos;
10140         if (Pos < NumReducedVals - ReduxWidth + 1)
10141           return IsAnyRedOpGathered;
10142         Pos = Start;
10143         ReduxWidth /= 2;
10144         return IsAnyRedOpGathered;
10145       };
10146       while (Pos < NumReducedVals - ReduxWidth + 1 &&
10147              ReduxWidth >= ReductionLimit) {
10148         // Dependency in tree of the reduction ops - drop this attempt, try
10149         // later.
10150         if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
10151             Start == 0) {
10152           CheckForReusedReductionOps = true;
10153           break;
10154         }
10155         PrevReduxWidth = ReduxWidth;
10156         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
10157         // Beeing analyzed already - skip.
10158         if (V.areAnalyzedReductionVals(VL)) {
10159           (void)AdjustReducedVals(/*IgnoreVL=*/true);
10160           continue;
10161         }
10162         // Early exit if any of the reduction values were deleted during
10163         // previous vectorization attempts.
10164         if (any_of(VL, [&V](Value *RedVal) {
10165               auto *RedValI = dyn_cast<Instruction>(RedVal);
10166               if (!RedValI)
10167                 return false;
10168               return V.isDeleted(RedValI);
10169             }))
10170           break;
10171         V.buildTree(VL, IgnoreList);
10172         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
10173           if (!AdjustReducedVals())
10174             V.analyzedReductionVals(VL);
10175           continue;
10176         }
10177         if (V.isLoadCombineReductionCandidate(RdxKind)) {
10178           if (!AdjustReducedVals())
10179             V.analyzedReductionVals(VL);
10180           continue;
10181         }
10182         V.reorderTopToBottom();
10183         // No need to reorder the root node at all.
10184         V.reorderBottomToTop(/*IgnoreReorder=*/true);
10185         // Keep extracted other reduction values, if they are used in the
10186         // vectorization trees.
10187         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
10188             ExternallyUsedValues);
10189         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
10190           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
10191             continue;
10192           for_each(ReducedVals[Cnt],
10193                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
10194                      if (isa<Instruction>(V))
10195                        LocalExternallyUsedValues[TrackedVals[V]];
10196                    });
10197         }
10198         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
10199           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
10200             continue;
10201           if (VectorizedVals.count(Candidates[Cnt]))
10202             continue;
10203           LocalExternallyUsedValues[Candidates[Cnt]];
10204         }
10205         V.buildExternalUses(LocalExternallyUsedValues);
10206 
10207         V.computeMinimumValueSizes();
10208 
10209         // Intersect the fast-math-flags from all reduction operations.
10210         FastMathFlags RdxFMF;
10211         RdxFMF.set();
10212         for (Value *U : IgnoreList)
10213           if (auto *FPMO = dyn_cast<FPMathOperator>(U))
10214             RdxFMF &= FPMO->getFastMathFlags();
10215         // Estimate cost.
10216         InstructionCost TreeCost = V.getTreeCost(VL);
10217         InstructionCost ReductionCost =
10218             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
10219         InstructionCost Cost = TreeCost + ReductionCost;
10220         if (!Cost.isValid()) {
10221           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
10222           return nullptr;
10223         }
10224         if (Cost >= -SLPCostThreshold) {
10225           V.getORE()->emit([&]() {
10226             return OptimizationRemarkMissed(
10227                        SV_NAME, "HorSLPNotBeneficial",
10228                        ReducedValsToOps.find(VL[0])->second.front())
10229                    << "Vectorizing horizontal reduction is possible"
10230                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
10231                    << " and threshold "
10232                    << ore::NV("Threshold", -SLPCostThreshold);
10233           });
10234           if (!AdjustReducedVals())
10235             V.analyzedReductionVals(VL);
10236           continue;
10237         }
10238 
10239         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
10240                           << Cost << ". (HorRdx)\n");
10241         V.getORE()->emit([&]() {
10242           return OptimizationRemark(
10243                      SV_NAME, "VectorizedHorizontalReduction",
10244                      ReducedValsToOps.find(VL[0])->second.front())
10245                  << "Vectorized horizontal reduction with cost "
10246                  << ore::NV("Cost", Cost) << " and with tree size "
10247                  << ore::NV("TreeSize", V.getTreeSize());
10248         });
10249 
10250         Builder.setFastMathFlags(RdxFMF);
10251 
10252         // Vectorize a tree.
10253         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
10254 
10255         // Emit a reduction. If the root is a select (min/max idiom), the insert
10256         // point is the compare condition of that select.
10257         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
10258         if (IsCmpSelMinMax)
10259           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
10260         else
10261           Builder.SetInsertPoint(RdxRootInst);
10262 
10263         // To prevent poison from leaking across what used to be sequential,
10264         // safe, scalar boolean logic operations, the reduction operand must be
10265         // frozen.
10266         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
10267           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
10268 
10269         Value *ReducedSubTree =
10270             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
10271 
10272         if (!VectorizedTree) {
10273           // Initialize the final value in the reduction.
10274           VectorizedTree = ReducedSubTree;
10275         } else {
10276           // Update the final value in the reduction.
10277           Builder.SetCurrentDebugLocation(
10278               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
10279           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10280                                     ReducedSubTree, "op.rdx", ReductionOps);
10281         }
10282         // Count vectorized reduced values to exclude them from final reduction.
10283         for (Value *V : VL)
10284           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
10285                 .first->getSecond();
10286         Pos += ReduxWidth;
10287         Start = Pos;
10288         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
10289       }
10290     }
10291     if (VectorizedTree) {
10292       // Finish the reduction.
10293       // Need to add extra arguments and not vectorized possible reduction
10294       // values.
10295       SmallPtrSet<Value *, 8> Visited;
10296       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10297         ArrayRef<Value *> Candidates = ReducedVals[I];
10298         for (Value *RdxVal : Candidates) {
10299           if (!Visited.insert(RdxVal).second)
10300             continue;
10301           Value *StableRdxVal = RdxVal;
10302           auto TVIt = TrackedVals.find(RdxVal);
10303           if (TVIt != TrackedVals.end())
10304             StableRdxVal = TVIt->second;
10305           unsigned NumOps = 0;
10306           auto It = VectorizedVals.find(RdxVal);
10307           if (It != VectorizedVals.end())
10308             NumOps = It->second;
10309           for (Instruction *RedOp :
10310                makeArrayRef(ReducedValsToOps.find(RdxVal)->second)
10311                    .drop_back(NumOps)) {
10312             Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10313             ReductionOpsListType Ops;
10314             if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10315               Ops.emplace_back().push_back(Sel->getCondition());
10316             Ops.emplace_back().push_back(RedOp);
10317             VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10318                                       StableRdxVal, "op.rdx", Ops);
10319           }
10320         }
10321       }
10322       for (auto &Pair : ExternallyUsedValues) {
10323         // Add each externally used value to the final reduction.
10324         for (auto *I : Pair.second) {
10325           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10326           ReductionOpsListType Ops;
10327           if (auto *Sel = dyn_cast<SelectInst>(I))
10328             Ops.emplace_back().push_back(Sel->getCondition());
10329           Ops.emplace_back().push_back(I);
10330           Value *StableRdxVal = Pair.first;
10331           auto TVIt = TrackedVals.find(Pair.first);
10332           if (TVIt != TrackedVals.end())
10333             StableRdxVal = TVIt->second;
10334           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10335                                     StableRdxVal, "op.rdx", Ops);
10336         }
10337       }
10338 
10339       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10340 
10341       // The original scalar reduction is expected to have no remaining
10342       // uses outside the reduction tree itself.  Assert that we got this
10343       // correct, replace internal uses with undef, and mark for eventual
10344       // deletion.
10345 #ifndef NDEBUG
10346       SmallSet<Value *, 4> IgnoreSet;
10347       for (ArrayRef<Value *> RdxOps : ReductionOps)
10348         IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
10349 #endif
10350       for (ArrayRef<Value *> RdxOps : ReductionOps) {
10351         for (Value *Ignore : RdxOps) {
10352           if (!Ignore)
10353             continue;
10354 #ifndef NDEBUG
10355           for (auto *U : Ignore->users()) {
10356             assert(IgnoreSet.count(U) &&
10357                    "All users must be either in the reduction ops list.");
10358           }
10359 #endif
10360           if (!Ignore->use_empty()) {
10361             Value *Undef = UndefValue::get(Ignore->getType());
10362             Ignore->replaceAllUsesWith(Undef);
10363           }
10364           V.eraseInstruction(cast<Instruction>(Ignore));
10365         }
10366       }
10367     } else if (!CheckForReusedReductionOps) {
10368       for (ReductionOpsType &RdxOps : ReductionOps)
10369         for (Value *RdxOp : RdxOps)
10370           V.analyzedReductionRoot(cast<Instruction>(RdxOp));
10371     }
10372     return VectorizedTree;
10373   }
10374 
10375   unsigned numReductionValues() const { return ReducedVals.size(); }
10376 
10377 private:
10378   /// Calculate the cost of a reduction.
10379   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10380                                    Value *FirstReducedVal, unsigned ReduxWidth,
10381                                    FastMathFlags FMF) {
10382     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10383     Type *ScalarTy = FirstReducedVal->getType();
10384     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10385     InstructionCost VectorCost, ScalarCost;
10386     switch (RdxKind) {
10387     case RecurKind::Add:
10388     case RecurKind::Mul:
10389     case RecurKind::Or:
10390     case RecurKind::And:
10391     case RecurKind::Xor:
10392     case RecurKind::FAdd:
10393     case RecurKind::FMul: {
10394       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10395       VectorCost =
10396           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10397       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10398       break;
10399     }
10400     case RecurKind::FMax:
10401     case RecurKind::FMin: {
10402       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10403       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10404       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10405                                                /*IsUnsigned=*/false, CostKind);
10406       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10407       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10408                                            SclCondTy, RdxPred, CostKind) +
10409                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10410                                            SclCondTy, RdxPred, CostKind);
10411       break;
10412     }
10413     case RecurKind::SMax:
10414     case RecurKind::SMin:
10415     case RecurKind::UMax:
10416     case RecurKind::UMin: {
10417       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10418       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10419       bool IsUnsigned =
10420           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10421       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10422                                                CostKind);
10423       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10424       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10425                                            SclCondTy, RdxPred, CostKind) +
10426                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10427                                            SclCondTy, RdxPred, CostKind);
10428       break;
10429     }
10430     default:
10431       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10432     }
10433 
10434     // Scalar cost is repeated for N-1 elements.
10435     ScalarCost *= (ReduxWidth - 1);
10436     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10437                       << " for reduction that starts with " << *FirstReducedVal
10438                       << " (It is a splitting reduction)\n");
10439     return VectorCost - ScalarCost;
10440   }
10441 
10442   /// Emit a horizontal reduction of the vectorized value.
10443   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10444                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10445     assert(VectorizedValue && "Need to have a vectorized tree node");
10446     assert(isPowerOf2_32(ReduxWidth) &&
10447            "We only handle power-of-two reductions for now");
10448     assert(RdxKind != RecurKind::FMulAdd &&
10449            "A call to the llvm.fmuladd intrinsic is not handled yet");
10450 
10451     ++NumVectorInstructions;
10452     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10453   }
10454 };
10455 
10456 } // end anonymous namespace
10457 
10458 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10459   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10460     return cast<FixedVectorType>(IE->getType())->getNumElements();
10461 
10462   unsigned AggregateSize = 1;
10463   auto *IV = cast<InsertValueInst>(InsertInst);
10464   Type *CurrentType = IV->getType();
10465   do {
10466     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10467       for (auto *Elt : ST->elements())
10468         if (Elt != ST->getElementType(0)) // check homogeneity
10469           return None;
10470       AggregateSize *= ST->getNumElements();
10471       CurrentType = ST->getElementType(0);
10472     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10473       AggregateSize *= AT->getNumElements();
10474       CurrentType = AT->getElementType();
10475     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10476       AggregateSize *= VT->getNumElements();
10477       return AggregateSize;
10478     } else if (CurrentType->isSingleValueType()) {
10479       return AggregateSize;
10480     } else {
10481       return None;
10482     }
10483   } while (true);
10484 }
10485 
10486 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10487                                    TargetTransformInfo *TTI,
10488                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10489                                    SmallVectorImpl<Value *> &InsertElts,
10490                                    unsigned OperandOffset) {
10491   do {
10492     Value *InsertedOperand = LastInsertInst->getOperand(1);
10493     Optional<unsigned> OperandIndex =
10494         getInsertIndex(LastInsertInst, OperandOffset);
10495     if (!OperandIndex)
10496       return;
10497     if (isa<InsertElementInst>(InsertedOperand) ||
10498         isa<InsertValueInst>(InsertedOperand)) {
10499       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10500                              BuildVectorOpds, InsertElts, *OperandIndex);
10501 
10502     } else {
10503       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10504       InsertElts[*OperandIndex] = LastInsertInst;
10505     }
10506     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10507   } while (LastInsertInst != nullptr &&
10508            (isa<InsertValueInst>(LastInsertInst) ||
10509             isa<InsertElementInst>(LastInsertInst)) &&
10510            LastInsertInst->hasOneUse());
10511 }
10512 
10513 /// Recognize construction of vectors like
10514 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10515 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10516 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10517 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10518 ///  starting from the last insertelement or insertvalue instruction.
10519 ///
10520 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10521 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10522 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10523 ///
10524 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10525 ///
10526 /// \return true if it matches.
10527 static bool findBuildAggregate(Instruction *LastInsertInst,
10528                                TargetTransformInfo *TTI,
10529                                SmallVectorImpl<Value *> &BuildVectorOpds,
10530                                SmallVectorImpl<Value *> &InsertElts) {
10531 
10532   assert((isa<InsertElementInst>(LastInsertInst) ||
10533           isa<InsertValueInst>(LastInsertInst)) &&
10534          "Expected insertelement or insertvalue instruction!");
10535 
10536   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10537          "Expected empty result vectors!");
10538 
10539   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10540   if (!AggregateSize)
10541     return false;
10542   BuildVectorOpds.resize(*AggregateSize);
10543   InsertElts.resize(*AggregateSize);
10544 
10545   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10546   llvm::erase_value(BuildVectorOpds, nullptr);
10547   llvm::erase_value(InsertElts, nullptr);
10548   if (BuildVectorOpds.size() >= 2)
10549     return true;
10550 
10551   return false;
10552 }
10553 
10554 /// Try and get a reduction value from a phi node.
10555 ///
10556 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10557 /// if they come from either \p ParentBB or a containing loop latch.
10558 ///
10559 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10560 /// if not possible.
10561 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10562                                 BasicBlock *ParentBB, LoopInfo *LI) {
10563   // There are situations where the reduction value is not dominated by the
10564   // reduction phi. Vectorizing such cases has been reported to cause
10565   // miscompiles. See PR25787.
10566   auto DominatedReduxValue = [&](Value *R) {
10567     return isa<Instruction>(R) &&
10568            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10569   };
10570 
10571   Value *Rdx = nullptr;
10572 
10573   // Return the incoming value if it comes from the same BB as the phi node.
10574   if (P->getIncomingBlock(0) == ParentBB) {
10575     Rdx = P->getIncomingValue(0);
10576   } else if (P->getIncomingBlock(1) == ParentBB) {
10577     Rdx = P->getIncomingValue(1);
10578   }
10579 
10580   if (Rdx && DominatedReduxValue(Rdx))
10581     return Rdx;
10582 
10583   // Otherwise, check whether we have a loop latch to look at.
10584   Loop *BBL = LI->getLoopFor(ParentBB);
10585   if (!BBL)
10586     return nullptr;
10587   BasicBlock *BBLatch = BBL->getLoopLatch();
10588   if (!BBLatch)
10589     return nullptr;
10590 
10591   // There is a loop latch, return the incoming value if it comes from
10592   // that. This reduction pattern occasionally turns up.
10593   if (P->getIncomingBlock(0) == BBLatch) {
10594     Rdx = P->getIncomingValue(0);
10595   } else if (P->getIncomingBlock(1) == BBLatch) {
10596     Rdx = P->getIncomingValue(1);
10597   }
10598 
10599   if (Rdx && DominatedReduxValue(Rdx))
10600     return Rdx;
10601 
10602   return nullptr;
10603 }
10604 
10605 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10606   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10607     return true;
10608   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10609     return true;
10610   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10611     return true;
10612   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10613     return true;
10614   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10615     return true;
10616   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10617     return true;
10618   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10619     return true;
10620   return false;
10621 }
10622 
10623 /// Attempt to reduce a horizontal reduction.
10624 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10625 /// with reduction operators \a Root (or one of its operands) in a basic block
10626 /// \a BB, then check if it can be done. If horizontal reduction is not found
10627 /// and root instruction is a binary operation, vectorization of the operands is
10628 /// attempted.
10629 /// \returns true if a horizontal reduction was matched and reduced or operands
10630 /// of one of the binary instruction were vectorized.
10631 /// \returns false if a horizontal reduction was not matched (or not possible)
10632 /// or no vectorization of any binary operation feeding \a Root instruction was
10633 /// performed.
10634 static bool tryToVectorizeHorReductionOrInstOperands(
10635     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10636     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10637     const TargetLibraryInfo &TLI,
10638     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10639   if (!ShouldVectorizeHor)
10640     return false;
10641 
10642   if (!Root)
10643     return false;
10644 
10645   if (Root->getParent() != BB || isa<PHINode>(Root))
10646     return false;
10647   // Start analysis starting from Root instruction. If horizontal reduction is
10648   // found, try to vectorize it. If it is not a horizontal reduction or
10649   // vectorization is not possible or not effective, and currently analyzed
10650   // instruction is a binary operation, try to vectorize the operands, using
10651   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10652   // the same procedure considering each operand as a possible root of the
10653   // horizontal reduction.
10654   // Interrupt the process if the Root instruction itself was vectorized or all
10655   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10656   // Skip the analysis of CmpInsts. Compiler implements postanalysis of the
10657   // CmpInsts so we can skip extra attempts in
10658   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10659   std::queue<std::pair<Instruction *, unsigned>> Stack;
10660   Stack.emplace(Root, 0);
10661   SmallPtrSet<Value *, 8> VisitedInstrs;
10662   SmallVector<WeakTrackingVH> PostponedInsts;
10663   bool Res = false;
10664   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10665                                                      Value *&B0,
10666                                                      Value *&B1) -> Value * {
10667     if (R.isAnalizedReductionRoot(Inst))
10668       return nullptr;
10669     bool IsBinop = matchRdxBop(Inst, B0, B1);
10670     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10671     if (IsBinop || IsSelect) {
10672       HorizontalReduction HorRdx;
10673       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10674         return HorRdx.tryToReduce(R, TTI);
10675     }
10676     return nullptr;
10677   };
10678   while (!Stack.empty()) {
10679     Instruction *Inst;
10680     unsigned Level;
10681     std::tie(Inst, Level) = Stack.front();
10682     Stack.pop();
10683     // Do not try to analyze instruction that has already been vectorized.
10684     // This may happen when we vectorize instruction operands on a previous
10685     // iteration while stack was populated before that happened.
10686     if (R.isDeleted(Inst))
10687       continue;
10688     Value *B0 = nullptr, *B1 = nullptr;
10689     if (Value *V = TryToReduce(Inst, B0, B1)) {
10690       Res = true;
10691       // Set P to nullptr to avoid re-analysis of phi node in
10692       // matchAssociativeReduction function unless this is the root node.
10693       P = nullptr;
10694       if (auto *I = dyn_cast<Instruction>(V)) {
10695         // Try to find another reduction.
10696         Stack.emplace(I, Level);
10697         continue;
10698       }
10699     } else {
10700       bool IsBinop = B0 && B1;
10701       if (P && IsBinop) {
10702         Inst = dyn_cast<Instruction>(B0);
10703         if (Inst == P)
10704           Inst = dyn_cast<Instruction>(B1);
10705         if (!Inst) {
10706           // Set P to nullptr to avoid re-analysis of phi node in
10707           // matchAssociativeReduction function unless this is the root node.
10708           P = nullptr;
10709           continue;
10710         }
10711       }
10712       // Set P to nullptr to avoid re-analysis of phi node in
10713       // matchAssociativeReduction function unless this is the root node.
10714       P = nullptr;
10715       // Do not try to vectorize CmpInst operands, this is done separately.
10716       // Final attempt for binop args vectorization should happen after the loop
10717       // to try to find reductions.
10718       if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
10719         PostponedInsts.push_back(Inst);
10720     }
10721 
10722     // Try to vectorize operands.
10723     // Continue analysis for the instruction from the same basic block only to
10724     // save compile time.
10725     if (++Level < RecursionMaxDepth)
10726       for (auto *Op : Inst->operand_values())
10727         if (VisitedInstrs.insert(Op).second)
10728           if (auto *I = dyn_cast<Instruction>(Op))
10729             // Do not try to vectorize CmpInst operands,  this is done
10730             // separately.
10731             if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
10732                 !R.isDeleted(I) && I->getParent() == BB)
10733               Stack.emplace(I, Level);
10734   }
10735   // Try to vectorized binops where reductions were not found.
10736   for (Value *V : PostponedInsts)
10737     if (auto *Inst = dyn_cast<Instruction>(V))
10738       if (!R.isDeleted(Inst))
10739         Res |= Vectorize(Inst, R);
10740   return Res;
10741 }
10742 
10743 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10744                                                  BasicBlock *BB, BoUpSLP &R,
10745                                                  TargetTransformInfo *TTI) {
10746   auto *I = dyn_cast_or_null<Instruction>(V);
10747   if (!I)
10748     return false;
10749 
10750   if (!isa<BinaryOperator>(I))
10751     P = nullptr;
10752   // Try to match and vectorize a horizontal reduction.
10753   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10754     return tryToVectorize(I, R);
10755   };
10756   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10757                                                   *TLI, ExtraVectorization);
10758 }
10759 
10760 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10761                                                  BasicBlock *BB, BoUpSLP &R) {
10762   const DataLayout &DL = BB->getModule()->getDataLayout();
10763   if (!R.canMapToVector(IVI->getType(), DL))
10764     return false;
10765 
10766   SmallVector<Value *, 16> BuildVectorOpds;
10767   SmallVector<Value *, 16> BuildVectorInsts;
10768   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10769     return false;
10770 
10771   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10772   // Aggregate value is unlikely to be processed in vector register.
10773   return tryToVectorizeList(BuildVectorOpds, R);
10774 }
10775 
10776 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10777                                                    BasicBlock *BB, BoUpSLP &R) {
10778   SmallVector<Value *, 16> BuildVectorInsts;
10779   SmallVector<Value *, 16> BuildVectorOpds;
10780   SmallVector<int> Mask;
10781   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10782       (llvm::all_of(
10783            BuildVectorOpds,
10784            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10785        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10786     return false;
10787 
10788   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10789   return tryToVectorizeList(BuildVectorInsts, R);
10790 }
10791 
10792 template <typename T>
10793 static bool
10794 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10795                        function_ref<unsigned(T *)> Limit,
10796                        function_ref<bool(T *, T *)> Comparator,
10797                        function_ref<bool(T *, T *)> AreCompatible,
10798                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10799                        bool LimitForRegisterSize) {
10800   bool Changed = false;
10801   // Sort by type, parent, operands.
10802   stable_sort(Incoming, Comparator);
10803 
10804   // Try to vectorize elements base on their type.
10805   SmallVector<T *> Candidates;
10806   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10807     // Look for the next elements with the same type, parent and operand
10808     // kinds.
10809     auto *SameTypeIt = IncIt;
10810     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10811       ++SameTypeIt;
10812 
10813     // Try to vectorize them.
10814     unsigned NumElts = (SameTypeIt - IncIt);
10815     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10816                       << NumElts << ")\n");
10817     // The vectorization is a 3-state attempt:
10818     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10819     // size of maximal register at first.
10820     // 2. Try to vectorize remaining instructions with the same type, if
10821     // possible. This may result in the better vectorization results rather than
10822     // if we try just to vectorize instructions with the same/alternate opcodes.
10823     // 3. Final attempt to try to vectorize all instructions with the
10824     // same/alternate ops only, this may result in some extra final
10825     // vectorization.
10826     if (NumElts > 1 &&
10827         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10828       // Success start over because instructions might have been changed.
10829       Changed = true;
10830     } else if (NumElts < Limit(*IncIt) &&
10831                (Candidates.empty() ||
10832                 Candidates.front()->getType() == (*IncIt)->getType())) {
10833       Candidates.append(IncIt, std::next(IncIt, NumElts));
10834     }
10835     // Final attempt to vectorize instructions with the same types.
10836     if (Candidates.size() > 1 &&
10837         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10838       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10839         // Success start over because instructions might have been changed.
10840         Changed = true;
10841       } else if (LimitForRegisterSize) {
10842         // Try to vectorize using small vectors.
10843         for (auto *It = Candidates.begin(), *End = Candidates.end();
10844              It != End;) {
10845           auto *SameTypeIt = It;
10846           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10847             ++SameTypeIt;
10848           unsigned NumElts = (SameTypeIt - It);
10849           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10850                                             /*LimitForRegisterSize=*/false))
10851             Changed = true;
10852           It = SameTypeIt;
10853         }
10854       }
10855       Candidates.clear();
10856     }
10857 
10858     // Start over at the next instruction of a different type (or the end).
10859     IncIt = SameTypeIt;
10860   }
10861   return Changed;
10862 }
10863 
10864 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10865 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10866 /// operands. If IsCompatibility is false, function implements strict weak
10867 /// ordering relation between two cmp instructions, returning true if the first
10868 /// instruction is "less" than the second, i.e. its predicate is less than the
10869 /// predicate of the second or the operands IDs are less than the operands IDs
10870 /// of the second cmp instruction.
10871 template <bool IsCompatibility>
10872 static bool compareCmp(Value *V, Value *V2,
10873                        function_ref<bool(Instruction *)> IsDeleted) {
10874   auto *CI1 = cast<CmpInst>(V);
10875   auto *CI2 = cast<CmpInst>(V2);
10876   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10877     return false;
10878   if (CI1->getOperand(0)->getType()->getTypeID() <
10879       CI2->getOperand(0)->getType()->getTypeID())
10880     return !IsCompatibility;
10881   if (CI1->getOperand(0)->getType()->getTypeID() >
10882       CI2->getOperand(0)->getType()->getTypeID())
10883     return false;
10884   CmpInst::Predicate Pred1 = CI1->getPredicate();
10885   CmpInst::Predicate Pred2 = CI2->getPredicate();
10886   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10887   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10888   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10889   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10890   if (BasePred1 < BasePred2)
10891     return !IsCompatibility;
10892   if (BasePred1 > BasePred2)
10893     return false;
10894   // Compare operands.
10895   bool LEPreds = Pred1 <= Pred2;
10896   bool GEPreds = Pred1 >= Pred2;
10897   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10898     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10899     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10900     if (Op1->getValueID() < Op2->getValueID())
10901       return !IsCompatibility;
10902     if (Op1->getValueID() > Op2->getValueID())
10903       return false;
10904     if (auto *I1 = dyn_cast<Instruction>(Op1))
10905       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10906         if (I1->getParent() != I2->getParent())
10907           return false;
10908         InstructionsState S = getSameOpcode({I1, I2});
10909         if (S.getOpcode())
10910           continue;
10911         return false;
10912       }
10913   }
10914   return IsCompatibility;
10915 }
10916 
10917 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10918     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10919     bool AtTerminator) {
10920   bool OpsChanged = false;
10921   SmallVector<Instruction *, 4> PostponedCmps;
10922   for (auto *I : reverse(Instructions)) {
10923     if (R.isDeleted(I))
10924       continue;
10925     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
10926       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10927     } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
10928       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10929     } else if (isa<CmpInst>(I)) {
10930       PostponedCmps.push_back(I);
10931       continue;
10932     }
10933     // Try to find reductions in buildvector sequnces.
10934     OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI);
10935   }
10936   if (AtTerminator) {
10937     // Try to find reductions first.
10938     for (Instruction *I : PostponedCmps) {
10939       if (R.isDeleted(I))
10940         continue;
10941       for (Value *Op : I->operands())
10942         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10943     }
10944     // Try to vectorize operands as vector bundles.
10945     for (Instruction *I : PostponedCmps) {
10946       if (R.isDeleted(I))
10947         continue;
10948       OpsChanged |= tryToVectorize(I, R);
10949     }
10950     // Try to vectorize list of compares.
10951     // Sort by type, compare predicate, etc.
10952     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10953       return compareCmp<false>(V, V2,
10954                                [&R](Instruction *I) { return R.isDeleted(I); });
10955     };
10956 
10957     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10958       if (V1 == V2)
10959         return true;
10960       return compareCmp<true>(V1, V2,
10961                               [&R](Instruction *I) { return R.isDeleted(I); });
10962     };
10963     auto Limit = [&R](Value *V) {
10964       unsigned EltSize = R.getVectorElementSize(V);
10965       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10966     };
10967 
10968     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10969     OpsChanged |= tryToVectorizeSequence<Value>(
10970         Vals, Limit, CompareSorter, AreCompatibleCompares,
10971         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10972           // Exclude possible reductions from other blocks.
10973           bool ArePossiblyReducedInOtherBlock =
10974               any_of(Candidates, [](Value *V) {
10975                 return any_of(V->users(), [V](User *U) {
10976                   return isa<SelectInst>(U) &&
10977                          cast<SelectInst>(U)->getParent() !=
10978                              cast<Instruction>(V)->getParent();
10979                 });
10980               });
10981           if (ArePossiblyReducedInOtherBlock)
10982             return false;
10983           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10984         },
10985         /*LimitForRegisterSize=*/true);
10986     Instructions.clear();
10987   } else {
10988     // Insert in reverse order since the PostponedCmps vector was filled in
10989     // reverse order.
10990     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10991   }
10992   return OpsChanged;
10993 }
10994 
10995 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10996   bool Changed = false;
10997   SmallVector<Value *, 4> Incoming;
10998   SmallPtrSet<Value *, 16> VisitedInstrs;
10999   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
11000   // node. Allows better to identify the chains that can be vectorized in the
11001   // better way.
11002   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
11003   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
11004     assert(isValidElementType(V1->getType()) &&
11005            isValidElementType(V2->getType()) &&
11006            "Expected vectorizable types only.");
11007     // It is fine to compare type IDs here, since we expect only vectorizable
11008     // types, like ints, floats and pointers, we don't care about other type.
11009     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
11010       return true;
11011     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
11012       return false;
11013     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11014     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11015     if (Opcodes1.size() < Opcodes2.size())
11016       return true;
11017     if (Opcodes1.size() > Opcodes2.size())
11018       return false;
11019     Optional<bool> ConstOrder;
11020     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11021       // Undefs are compatible with any other value.
11022       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
11023         if (!ConstOrder)
11024           ConstOrder =
11025               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
11026         continue;
11027       }
11028       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11029         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11030           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
11031           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
11032           if (!NodeI1)
11033             return NodeI2 != nullptr;
11034           if (!NodeI2)
11035             return false;
11036           assert((NodeI1 == NodeI2) ==
11037                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11038                  "Different nodes should have different DFS numbers");
11039           if (NodeI1 != NodeI2)
11040             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11041           InstructionsState S = getSameOpcode({I1, I2});
11042           if (S.getOpcode())
11043             continue;
11044           return I1->getOpcode() < I2->getOpcode();
11045         }
11046       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
11047         if (!ConstOrder)
11048           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
11049         continue;
11050       }
11051       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
11052         return true;
11053       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
11054         return false;
11055     }
11056     return ConstOrder && *ConstOrder;
11057   };
11058   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
11059     if (V1 == V2)
11060       return true;
11061     if (V1->getType() != V2->getType())
11062       return false;
11063     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
11064     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
11065     if (Opcodes1.size() != Opcodes2.size())
11066       return false;
11067     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
11068       // Undefs are compatible with any other value.
11069       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
11070         continue;
11071       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
11072         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
11073           if (I1->getParent() != I2->getParent())
11074             return false;
11075           InstructionsState S = getSameOpcode({I1, I2});
11076           if (S.getOpcode())
11077             continue;
11078           return false;
11079         }
11080       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
11081         continue;
11082       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
11083         return false;
11084     }
11085     return true;
11086   };
11087   auto Limit = [&R](Value *V) {
11088     unsigned EltSize = R.getVectorElementSize(V);
11089     return std::max(2U, R.getMaxVecRegSize() / EltSize);
11090   };
11091 
11092   bool HaveVectorizedPhiNodes = false;
11093   do {
11094     // Collect the incoming values from the PHIs.
11095     Incoming.clear();
11096     for (Instruction &I : *BB) {
11097       PHINode *P = dyn_cast<PHINode>(&I);
11098       if (!P)
11099         break;
11100 
11101       // No need to analyze deleted, vectorized and non-vectorizable
11102       // instructions.
11103       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
11104           isValidElementType(P->getType()))
11105         Incoming.push_back(P);
11106     }
11107 
11108     // Find the corresponding non-phi nodes for better matching when trying to
11109     // build the tree.
11110     for (Value *V : Incoming) {
11111       SmallVectorImpl<Value *> &Opcodes =
11112           PHIToOpcodes.try_emplace(V).first->getSecond();
11113       if (!Opcodes.empty())
11114         continue;
11115       SmallVector<Value *, 4> Nodes(1, V);
11116       SmallPtrSet<Value *, 4> Visited;
11117       while (!Nodes.empty()) {
11118         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
11119         if (!Visited.insert(PHI).second)
11120           continue;
11121         for (Value *V : PHI->incoming_values()) {
11122           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
11123             Nodes.push_back(PHI1);
11124             continue;
11125           }
11126           Opcodes.emplace_back(V);
11127         }
11128       }
11129     }
11130 
11131     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
11132         Incoming, Limit, PHICompare, AreCompatiblePHIs,
11133         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
11134           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
11135         },
11136         /*LimitForRegisterSize=*/true);
11137     Changed |= HaveVectorizedPhiNodes;
11138     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
11139   } while (HaveVectorizedPhiNodes);
11140 
11141   VisitedInstrs.clear();
11142 
11143   SmallVector<Instruction *, 8> PostProcessInstructions;
11144   SmallDenseSet<Instruction *, 4> KeyNodes;
11145   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
11146     // Skip instructions with scalable type. The num of elements is unknown at
11147     // compile-time for scalable type.
11148     if (isa<ScalableVectorType>(it->getType()))
11149       continue;
11150 
11151     // Skip instructions marked for the deletion.
11152     if (R.isDeleted(&*it))
11153       continue;
11154     // We may go through BB multiple times so skip the one we have checked.
11155     if (!VisitedInstrs.insert(&*it).second) {
11156       if (it->use_empty() && KeyNodes.contains(&*it) &&
11157           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11158                                       it->isTerminator())) {
11159         // We would like to start over since some instructions are deleted
11160         // and the iterator may become invalid value.
11161         Changed = true;
11162         it = BB->begin();
11163         e = BB->end();
11164       }
11165       continue;
11166     }
11167 
11168     if (isa<DbgInfoIntrinsic>(it))
11169       continue;
11170 
11171     // Try to vectorize reductions that use PHINodes.
11172     if (PHINode *P = dyn_cast<PHINode>(it)) {
11173       // Check that the PHI is a reduction PHI.
11174       if (P->getNumIncomingValues() == 2) {
11175         // Try to match and vectorize a horizontal reduction.
11176         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
11177                                      TTI)) {
11178           Changed = true;
11179           it = BB->begin();
11180           e = BB->end();
11181           continue;
11182         }
11183       }
11184       // Try to vectorize the incoming values of the PHI, to catch reductions
11185       // that feed into PHIs.
11186       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
11187         // Skip if the incoming block is the current BB for now. Also, bypass
11188         // unreachable IR for efficiency and to avoid crashing.
11189         // TODO: Collect the skipped incoming values and try to vectorize them
11190         // after processing BB.
11191         if (BB == P->getIncomingBlock(I) ||
11192             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
11193           continue;
11194 
11195         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
11196                                             P->getIncomingBlock(I), R, TTI);
11197       }
11198       continue;
11199     }
11200 
11201     // Ran into an instruction without users, like terminator, or function call
11202     // with ignored return value, store. Ignore unused instructions (basing on
11203     // instruction type, except for CallInst and InvokeInst).
11204     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
11205                             isa<InvokeInst>(it))) {
11206       KeyNodes.insert(&*it);
11207       bool OpsChanged = false;
11208       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
11209         for (auto *V : it->operand_values()) {
11210           // Try to match and vectorize a horizontal reduction.
11211           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
11212         }
11213       }
11214       // Start vectorization of post-process list of instructions from the
11215       // top-tree instructions to try to vectorize as many instructions as
11216       // possible.
11217       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
11218                                                 it->isTerminator());
11219       if (OpsChanged) {
11220         // We would like to start over since some instructions are deleted
11221         // and the iterator may become invalid value.
11222         Changed = true;
11223         it = BB->begin();
11224         e = BB->end();
11225         continue;
11226       }
11227     }
11228 
11229     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
11230         isa<InsertValueInst>(it))
11231       PostProcessInstructions.push_back(&*it);
11232   }
11233 
11234   return Changed;
11235 }
11236 
11237 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
11238   auto Changed = false;
11239   for (auto &Entry : GEPs) {
11240     // If the getelementptr list has fewer than two elements, there's nothing
11241     // to do.
11242     if (Entry.second.size() < 2)
11243       continue;
11244 
11245     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
11246                       << Entry.second.size() << ".\n");
11247 
11248     // Process the GEP list in chunks suitable for the target's supported
11249     // vector size. If a vector register can't hold 1 element, we are done. We
11250     // are trying to vectorize the index computations, so the maximum number of
11251     // elements is based on the size of the index expression, rather than the
11252     // size of the GEP itself (the target's pointer size).
11253     unsigned MaxVecRegSize = R.getMaxVecRegSize();
11254     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
11255     if (MaxVecRegSize < EltSize)
11256       continue;
11257 
11258     unsigned MaxElts = MaxVecRegSize / EltSize;
11259     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
11260       auto Len = std::min<unsigned>(BE - BI, MaxElts);
11261       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
11262 
11263       // Initialize a set a candidate getelementptrs. Note that we use a
11264       // SetVector here to preserve program order. If the index computations
11265       // are vectorizable and begin with loads, we want to minimize the chance
11266       // of having to reorder them later.
11267       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
11268 
11269       // Some of the candidates may have already been vectorized after we
11270       // initially collected them. If so, they are marked as deleted, so remove
11271       // them from the set of candidates.
11272       Candidates.remove_if(
11273           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
11274 
11275       // Remove from the set of candidates all pairs of getelementptrs with
11276       // constant differences. Such getelementptrs are likely not good
11277       // candidates for vectorization in a bottom-up phase since one can be
11278       // computed from the other. We also ensure all candidate getelementptr
11279       // indices are unique.
11280       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
11281         auto *GEPI = GEPList[I];
11282         if (!Candidates.count(GEPI))
11283           continue;
11284         auto *SCEVI = SE->getSCEV(GEPList[I]);
11285         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
11286           auto *GEPJ = GEPList[J];
11287           auto *SCEVJ = SE->getSCEV(GEPList[J]);
11288           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
11289             Candidates.remove(GEPI);
11290             Candidates.remove(GEPJ);
11291           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
11292             Candidates.remove(GEPJ);
11293           }
11294         }
11295       }
11296 
11297       // We break out of the above computation as soon as we know there are
11298       // fewer than two candidates remaining.
11299       if (Candidates.size() < 2)
11300         continue;
11301 
11302       // Add the single, non-constant index of each candidate to the bundle. We
11303       // ensured the indices met these constraints when we originally collected
11304       // the getelementptrs.
11305       SmallVector<Value *, 16> Bundle(Candidates.size());
11306       auto BundleIndex = 0u;
11307       for (auto *V : Candidates) {
11308         auto *GEP = cast<GetElementPtrInst>(V);
11309         auto *GEPIdx = GEP->idx_begin()->get();
11310         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11311         Bundle[BundleIndex++] = GEPIdx;
11312       }
11313 
11314       // Try and vectorize the indices. We are currently only interested in
11315       // gather-like cases of the form:
11316       //
11317       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11318       //
11319       // where the loads of "a", the loads of "b", and the subtractions can be
11320       // performed in parallel. It's likely that detecting this pattern in a
11321       // bottom-up phase will be simpler and less costly than building a
11322       // full-blown top-down phase beginning at the consecutive loads.
11323       Changed |= tryToVectorizeList(Bundle, R);
11324     }
11325   }
11326   return Changed;
11327 }
11328 
11329 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11330   bool Changed = false;
11331   // Sort by type, base pointers and values operand. Value operands must be
11332   // compatible (have the same opcode, same parent), otherwise it is
11333   // definitely not profitable to try to vectorize them.
11334   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11335     if (V->getPointerOperandType()->getTypeID() <
11336         V2->getPointerOperandType()->getTypeID())
11337       return true;
11338     if (V->getPointerOperandType()->getTypeID() >
11339         V2->getPointerOperandType()->getTypeID())
11340       return false;
11341     // UndefValues are compatible with all other values.
11342     if (isa<UndefValue>(V->getValueOperand()) ||
11343         isa<UndefValue>(V2->getValueOperand()))
11344       return false;
11345     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11346       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11347         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11348             DT->getNode(I1->getParent());
11349         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11350             DT->getNode(I2->getParent());
11351         assert(NodeI1 && "Should only process reachable instructions");
11352         assert(NodeI2 && "Should only process reachable instructions");
11353         assert((NodeI1 == NodeI2) ==
11354                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11355                "Different nodes should have different DFS numbers");
11356         if (NodeI1 != NodeI2)
11357           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11358         InstructionsState S = getSameOpcode({I1, I2});
11359         if (S.getOpcode())
11360           return false;
11361         return I1->getOpcode() < I2->getOpcode();
11362       }
11363     if (isa<Constant>(V->getValueOperand()) &&
11364         isa<Constant>(V2->getValueOperand()))
11365       return false;
11366     return V->getValueOperand()->getValueID() <
11367            V2->getValueOperand()->getValueID();
11368   };
11369 
11370   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11371     if (V1 == V2)
11372       return true;
11373     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11374       return false;
11375     // Undefs are compatible with any other value.
11376     if (isa<UndefValue>(V1->getValueOperand()) ||
11377         isa<UndefValue>(V2->getValueOperand()))
11378       return true;
11379     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11380       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11381         if (I1->getParent() != I2->getParent())
11382           return false;
11383         InstructionsState S = getSameOpcode({I1, I2});
11384         return S.getOpcode() > 0;
11385       }
11386     if (isa<Constant>(V1->getValueOperand()) &&
11387         isa<Constant>(V2->getValueOperand()))
11388       return true;
11389     return V1->getValueOperand()->getValueID() ==
11390            V2->getValueOperand()->getValueID();
11391   };
11392   auto Limit = [&R, this](StoreInst *SI) {
11393     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11394     return R.getMinVF(EltSize);
11395   };
11396 
11397   // Attempt to sort and vectorize each of the store-groups.
11398   for (auto &Pair : Stores) {
11399     if (Pair.second.size() < 2)
11400       continue;
11401 
11402     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11403                       << Pair.second.size() << ".\n");
11404 
11405     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11406       continue;
11407 
11408     Changed |= tryToVectorizeSequence<StoreInst>(
11409         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11410         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11411           return vectorizeStores(Candidates, R);
11412         },
11413         /*LimitForRegisterSize=*/false);
11414   }
11415   return Changed;
11416 }
11417 
11418 char SLPVectorizer::ID = 0;
11419 
11420 static const char lv_name[] = "SLP Vectorizer";
11421 
11422 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11423 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11424 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11425 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11426 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11427 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11428 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11429 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11430 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11431 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11432 
11433 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11434