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/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/Operator.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #include "llvm/IR/Verifier.h"
75 #include "llvm/Pass.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/DOTGraphTraits.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/GraphWriter.h"
83 #include "llvm/Support/InstructionCost.h"
84 #include "llvm/Support/KnownBits.h"
85 #include "llvm/Support/MathExtras.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
88 #include "llvm/Transforms/Utils/LoopUtils.h"
89 #include "llvm/Transforms/Vectorize.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <memory>
95 #include <set>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 using namespace llvm::PatternMatch;
103 using namespace slpvectorizer;
104 
105 #define SV_NAME "slp-vectorizer"
106 #define DEBUG_TYPE "SLP"
107 
108 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
109 
110 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
111                                   cl::desc("Run the SLP vectorization passes"));
112 
113 static cl::opt<int>
114     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
115                      cl::desc("Only vectorize if you gain more than this "
116                               "number "));
117 
118 static cl::opt<bool>
119 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
120                    cl::desc("Attempt to vectorize horizontal reductions"));
121 
122 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
123     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
124     cl::desc(
125         "Attempt to vectorize horizontal reductions feeding into a store"));
126 
127 static cl::opt<int>
128 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
129     cl::desc("Attempt to vectorize for this register size in bits"));
130 
131 static cl::opt<unsigned>
132 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
133     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
134 
135 static cl::opt<int>
136 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
137     cl::desc("Maximum depth of the lookup for consecutive stores."));
138 
139 /// Limits the size of scheduling regions in a block.
140 /// It avoid long compile times for _very_ large blocks where vector
141 /// instructions are spread over a wide range.
142 /// This limit is way higher than needed by real-world functions.
143 static cl::opt<int>
144 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
145     cl::desc("Limit the size of the SLP scheduling region per block"));
146 
147 static cl::opt<int> MinVectorRegSizeOption(
148     "slp-min-reg-size", cl::init(128), cl::Hidden,
149     cl::desc("Attempt to vectorize for this register size in bits"));
150 
151 static cl::opt<unsigned> RecursionMaxDepth(
152     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
153     cl::desc("Limit the recursion depth when building a vectorizable tree"));
154 
155 static cl::opt<unsigned> MinTreeSize(
156     "slp-min-tree-size", cl::init(3), cl::Hidden,
157     cl::desc("Only vectorize small trees if they are fully vectorizable"));
158 
159 // The maximum depth that the look-ahead score heuristic will explore.
160 // The higher this value, the higher the compilation time overhead.
161 static cl::opt<int> LookAheadMaxDepth(
162     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
163     cl::desc("The maximum look-ahead depth for operand reordering scores"));
164 
165 static cl::opt<bool>
166     ViewSLPTree("view-slp-tree", cl::Hidden,
167                 cl::desc("Display the SLP trees with Graphviz"));
168 
169 // Limit the number of alias checks. The limit is chosen so that
170 // it has no negative effect on the llvm benchmarks.
171 static const unsigned AliasedCheckLimit = 10;
172 
173 // Another limit for the alias checks: The maximum distance between load/store
174 // instructions where alias checks are done.
175 // This limit is useful for very large basic blocks.
176 static const unsigned MaxMemDepDistance = 160;
177 
178 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
179 /// regions to be handled.
180 static const int MinScheduleRegionSize = 16;
181 
182 /// Predicate for the element types that the SLP vectorizer supports.
183 ///
184 /// The most important thing to filter here are types which are invalid in LLVM
185 /// vectors. We also filter target specific types which have absolutely no
186 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
187 /// avoids spending time checking the cost model and realizing that they will
188 /// be inevitably scalarized.
189 static bool isValidElementType(Type *Ty) {
190   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
191          !Ty->isPPC_FP128Ty();
192 }
193 
194 /// \returns True if the value is a constant (but not globals/constant
195 /// expressions).
196 static bool isConstant(Value *V) {
197   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
198 }
199 
200 /// Checks if \p V is one of vector-like instructions, i.e. undef,
201 /// insertelement/extractelement with constant indices for fixed vector type or
202 /// extractvalue instruction.
203 static bool isVectorLikeInstWithConstOps(Value *V) {
204   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
205       !isa<ExtractValueInst, UndefValue>(V))
206     return false;
207   auto *I = dyn_cast<Instruction>(V);
208   if (!I || isa<ExtractValueInst>(I))
209     return true;
210   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
211     return false;
212   if (isa<ExtractElementInst>(I))
213     return isConstant(I->getOperand(1));
214   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
215   return isConstant(I->getOperand(2));
216 }
217 
218 /// \returns true if all of the instructions in \p VL are in the same block or
219 /// false otherwise.
220 static bool allSameBlock(ArrayRef<Value *> VL) {
221   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
222   if (!I0)
223     return false;
224   if (all_of(VL, isVectorLikeInstWithConstOps))
225     return true;
226 
227   BasicBlock *BB = I0->getParent();
228   for (int I = 1, E = VL.size(); I < E; I++) {
229     auto *II = dyn_cast<Instruction>(VL[I]);
230     if (!II)
231       return false;
232 
233     if (BB != II->getParent())
234       return false;
235   }
236   return true;
237 }
238 
239 /// \returns True if all of the values in \p VL are constants (but not
240 /// globals/constant expressions).
241 static bool allConstant(ArrayRef<Value *> VL) {
242   // Constant expressions and globals can't be vectorized like normal integer/FP
243   // constants.
244   return all_of(VL, isConstant);
245 }
246 
247 /// \returns True if all of the values in \p VL are identical or some of them
248 /// are UndefValue.
249 static bool isSplat(ArrayRef<Value *> VL) {
250   Value *FirstNonUndef = nullptr;
251   for (Value *V : VL) {
252     if (isa<UndefValue>(V))
253       continue;
254     if (!FirstNonUndef) {
255       FirstNonUndef = V;
256       continue;
257     }
258     if (V != FirstNonUndef)
259       return false;
260   }
261   return FirstNonUndef != nullptr;
262 }
263 
264 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
265 static bool isCommutative(Instruction *I) {
266   if (auto *Cmp = dyn_cast<CmpInst>(I))
267     return Cmp->isCommutative();
268   if (auto *BO = dyn_cast<BinaryOperator>(I))
269     return BO->isCommutative();
270   // TODO: This should check for generic Instruction::isCommutative(), but
271   //       we need to confirm that the caller code correctly handles Intrinsics
272   //       for example (does not have 2 operands).
273   return false;
274 }
275 
276 /// Checks if the given value is actually an undefined constant vector.
277 static bool isUndefVector(const Value *V) {
278   if (isa<UndefValue>(V))
279     return true;
280   auto *C = dyn_cast<Constant>(V);
281   if (!C)
282     return false;
283   if (!C->containsUndefOrPoisonElement())
284     return false;
285   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
286   if (!VecTy)
287     return false;
288   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
289     if (Constant *Elem = C->getAggregateElement(I))
290       if (!isa<UndefValue>(Elem))
291         return false;
292   }
293   return true;
294 }
295 
296 /// Checks if the vector of instructions can be represented as a shuffle, like:
297 /// %x0 = extractelement <4 x i8> %x, i32 0
298 /// %x3 = extractelement <4 x i8> %x, i32 3
299 /// %y1 = extractelement <4 x i8> %y, i32 1
300 /// %y2 = extractelement <4 x i8> %y, i32 2
301 /// %x0x0 = mul i8 %x0, %x0
302 /// %x3x3 = mul i8 %x3, %x3
303 /// %y1y1 = mul i8 %y1, %y1
304 /// %y2y2 = mul i8 %y2, %y2
305 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
306 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
307 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
308 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
309 /// ret <4 x i8> %ins4
310 /// can be transformed into:
311 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
312 ///                                                         i32 6>
313 /// %2 = mul <4 x i8> %1, %1
314 /// ret <4 x i8> %2
315 /// We convert this initially to something like:
316 /// %x0 = extractelement <4 x i8> %x, i32 0
317 /// %x3 = extractelement <4 x i8> %x, i32 3
318 /// %y1 = extractelement <4 x i8> %y, i32 1
319 /// %y2 = extractelement <4 x i8> %y, i32 2
320 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
321 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
322 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
323 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
324 /// %5 = mul <4 x i8> %4, %4
325 /// %6 = extractelement <4 x i8> %5, i32 0
326 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
327 /// %7 = extractelement <4 x i8> %5, i32 1
328 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
329 /// %8 = extractelement <4 x i8> %5, i32 2
330 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
331 /// %9 = extractelement <4 x i8> %5, i32 3
332 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
333 /// ret <4 x i8> %ins4
334 /// InstCombiner transforms this into a shuffle and vector mul
335 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
336 /// TODO: Can we split off and reuse the shuffle mask detection from
337 /// TargetTransformInfo::getInstructionThroughput?
338 static Optional<TargetTransformInfo::ShuffleKind>
339 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
340   const auto *It =
341       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
342   if (It == VL.end())
343     return None;
344   auto *EI0 = cast<ExtractElementInst>(*It);
345   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
346     return None;
347   unsigned Size =
348       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
349   Value *Vec1 = nullptr;
350   Value *Vec2 = nullptr;
351   enum ShuffleMode { Unknown, Select, Permute };
352   ShuffleMode CommonShuffleMode = Unknown;
353   Mask.assign(VL.size(), UndefMaskElem);
354   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
355     // Undef can be represented as an undef element in a vector.
356     if (isa<UndefValue>(VL[I]))
357       continue;
358     auto *EI = cast<ExtractElementInst>(VL[I]);
359     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
360       return None;
361     auto *Vec = EI->getVectorOperand();
362     // We can extractelement from undef or poison vector.
363     if (isUndefVector(Vec))
364       continue;
365     // All vector operands must have the same number of vector elements.
366     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
367       return None;
368     if (isa<UndefValue>(EI->getIndexOperand()))
369       continue;
370     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
371     if (!Idx)
372       return None;
373     // Undefined behavior if Idx is negative or >= Size.
374     if (Idx->getValue().uge(Size))
375       continue;
376     unsigned IntIdx = Idx->getValue().getZExtValue();
377     Mask[I] = IntIdx;
378     // For correct shuffling we have to have at most 2 different vector operands
379     // in all extractelement instructions.
380     if (!Vec1 || Vec1 == Vec) {
381       Vec1 = Vec;
382     } else if (!Vec2 || Vec2 == Vec) {
383       Vec2 = Vec;
384       Mask[I] += Size;
385     } else {
386       return None;
387     }
388     if (CommonShuffleMode == Permute)
389       continue;
390     // If the extract index is not the same as the operation number, it is a
391     // permutation.
392     if (IntIdx != I) {
393       CommonShuffleMode = Permute;
394       continue;
395     }
396     CommonShuffleMode = Select;
397   }
398   // If we're not crossing lanes in different vectors, consider it as blending.
399   if (CommonShuffleMode == Select && Vec2)
400     return TargetTransformInfo::SK_Select;
401   // If Vec2 was never used, we have a permutation of a single vector, otherwise
402   // we have permutation of 2 vectors.
403   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
404               : TargetTransformInfo::SK_PermuteSingleSrc;
405 }
406 
407 namespace {
408 
409 /// Main data required for vectorization of instructions.
410 struct InstructionsState {
411   /// The very first instruction in the list with the main opcode.
412   Value *OpValue = nullptr;
413 
414   /// The main/alternate instruction.
415   Instruction *MainOp = nullptr;
416   Instruction *AltOp = nullptr;
417 
418   /// The main/alternate opcodes for the list of instructions.
419   unsigned getOpcode() const {
420     return MainOp ? MainOp->getOpcode() : 0;
421   }
422 
423   unsigned getAltOpcode() const {
424     return AltOp ? AltOp->getOpcode() : 0;
425   }
426 
427   /// Some of the instructions in the list have alternate opcodes.
428   bool isAltShuffle() const { return AltOp != MainOp; }
429 
430   bool isOpcodeOrAlt(Instruction *I) const {
431     unsigned CheckedOpcode = I->getOpcode();
432     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
433   }
434 
435   InstructionsState() = delete;
436   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
437       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
438 };
439 
440 } // end anonymous namespace
441 
442 /// Chooses the correct key for scheduling data. If \p Op has the same (or
443 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
444 /// OpValue.
445 static Value *isOneOf(const InstructionsState &S, Value *Op) {
446   auto *I = dyn_cast<Instruction>(Op);
447   if (I && S.isOpcodeOrAlt(I))
448     return Op;
449   return S.OpValue;
450 }
451 
452 /// \returns true if \p Opcode is allowed as part of of the main/alternate
453 /// instruction for SLP vectorization.
454 ///
455 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
456 /// "shuffled out" lane would result in division by zero.
457 static bool isValidForAlternation(unsigned Opcode) {
458   if (Instruction::isIntDivRem(Opcode))
459     return false;
460 
461   return true;
462 }
463 
464 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
465                                        unsigned BaseIndex = 0);
466 
467 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
468 /// compatible instructions or constants, or just some other regular values.
469 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
470                                 Value *Op1) {
471   return (isConstant(BaseOp0) && isConstant(Op0)) ||
472          (isConstant(BaseOp1) && isConstant(Op1)) ||
473          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
474           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
475          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
476          getSameOpcode({BaseOp1, Op1}).getOpcode();
477 }
478 
479 /// \returns analysis of the Instructions in \p VL described in
480 /// InstructionsState, the Opcode that we suppose the whole list
481 /// could be vectorized even if its structure is diverse.
482 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
483                                        unsigned BaseIndex) {
484   // Make sure these are all Instructions.
485   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
486     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
487 
488   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
489   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
490   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
491   CmpInst::Predicate BasePred =
492       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
493               : CmpInst::BAD_ICMP_PREDICATE;
494   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
495   unsigned AltOpcode = Opcode;
496   unsigned AltIndex = BaseIndex;
497 
498   // Check for one alternate opcode from another BinaryOperator.
499   // TODO - generalize to support all operators (types, calls etc.).
500   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
501     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
502     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
503       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
504         continue;
505       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
506           isValidForAlternation(Opcode)) {
507         AltOpcode = InstOpcode;
508         AltIndex = Cnt;
509         continue;
510       }
511     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
512       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
513       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
514       if (Ty0 == Ty1) {
515         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
516           continue;
517         if (Opcode == AltOpcode) {
518           assert(isValidForAlternation(Opcode) &&
519                  isValidForAlternation(InstOpcode) &&
520                  "Cast isn't safe for alternation, logic needs to be updated!");
521           AltOpcode = InstOpcode;
522           AltIndex = Cnt;
523           continue;
524         }
525       }
526     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
527       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
528       auto *Inst = cast<Instruction>(VL[Cnt]);
529       Type *Ty0 = BaseInst->getOperand(0)->getType();
530       Type *Ty1 = Inst->getOperand(0)->getType();
531       if (Ty0 == Ty1) {
532         Value *BaseOp0 = BaseInst->getOperand(0);
533         Value *BaseOp1 = BaseInst->getOperand(1);
534         Value *Op0 = Inst->getOperand(0);
535         Value *Op1 = Inst->getOperand(1);
536         CmpInst::Predicate CurrentPred =
537             cast<CmpInst>(VL[Cnt])->getPredicate();
538         CmpInst::Predicate SwappedCurrentPred =
539             CmpInst::getSwappedPredicate(CurrentPred);
540         // Check for compatible operands. If the corresponding operands are not
541         // compatible - need to perform alternate vectorization.
542         if (InstOpcode == Opcode) {
543           if (BasePred == CurrentPred &&
544               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
545             continue;
546           if (BasePred == SwappedCurrentPred &&
547               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
548             continue;
549           if (E == 2 &&
550               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
551             continue;
552           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
553           CmpInst::Predicate AltPred = AltInst->getPredicate();
554           Value *AltOp0 = AltInst->getOperand(0);
555           Value *AltOp1 = AltInst->getOperand(1);
556           // Check if operands are compatible with alternate operands.
557           if (AltPred == CurrentPred &&
558               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
559             continue;
560           if (AltPred == SwappedCurrentPred &&
561               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
562             continue;
563         }
564         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
565           assert(isValidForAlternation(Opcode) &&
566                  isValidForAlternation(InstOpcode) &&
567                  "Cast isn't safe for alternation, logic needs to be updated!");
568           AltIndex = Cnt;
569           continue;
570         }
571         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
572         CmpInst::Predicate AltPred = AltInst->getPredicate();
573         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
574             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
575           continue;
576       }
577     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
578       continue;
579     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
580   }
581 
582   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
583                            cast<Instruction>(VL[AltIndex]));
584 }
585 
586 /// \returns true if all of the values in \p VL have the same type or false
587 /// otherwise.
588 static bool allSameType(ArrayRef<Value *> VL) {
589   Type *Ty = VL[0]->getType();
590   for (int i = 1, e = VL.size(); i < e; i++)
591     if (VL[i]->getType() != Ty)
592       return false;
593 
594   return true;
595 }
596 
597 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
598 static Optional<unsigned> getExtractIndex(Instruction *E) {
599   unsigned Opcode = E->getOpcode();
600   assert((Opcode == Instruction::ExtractElement ||
601           Opcode == Instruction::ExtractValue) &&
602          "Expected extractelement or extractvalue instruction.");
603   if (Opcode == Instruction::ExtractElement) {
604     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
605     if (!CI)
606       return None;
607     return CI->getZExtValue();
608   }
609   ExtractValueInst *EI = cast<ExtractValueInst>(E);
610   if (EI->getNumIndices() != 1)
611     return None;
612   return *EI->idx_begin();
613 }
614 
615 /// \returns True if in-tree use also needs extract. This refers to
616 /// possible scalar operand in vectorized instruction.
617 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
618                                     TargetLibraryInfo *TLI) {
619   unsigned Opcode = UserInst->getOpcode();
620   switch (Opcode) {
621   case Instruction::Load: {
622     LoadInst *LI = cast<LoadInst>(UserInst);
623     return (LI->getPointerOperand() == Scalar);
624   }
625   case Instruction::Store: {
626     StoreInst *SI = cast<StoreInst>(UserInst);
627     return (SI->getPointerOperand() == Scalar);
628   }
629   case Instruction::Call: {
630     CallInst *CI = cast<CallInst>(UserInst);
631     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
632     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
633       if (hasVectorInstrinsicScalarOpd(ID, i))
634         return (CI->getArgOperand(i) == Scalar);
635     }
636     LLVM_FALLTHROUGH;
637   }
638   default:
639     return false;
640   }
641 }
642 
643 /// \returns the AA location that is being access by the instruction.
644 static MemoryLocation getLocation(Instruction *I) {
645   if (StoreInst *SI = dyn_cast<StoreInst>(I))
646     return MemoryLocation::get(SI);
647   if (LoadInst *LI = dyn_cast<LoadInst>(I))
648     return MemoryLocation::get(LI);
649   return MemoryLocation();
650 }
651 
652 /// \returns True if the instruction is not a volatile or atomic load/store.
653 static bool isSimple(Instruction *I) {
654   if (LoadInst *LI = dyn_cast<LoadInst>(I))
655     return LI->isSimple();
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return SI->isSimple();
658   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
659     return !MI->isVolatile();
660   return true;
661 }
662 
663 /// Shuffles \p Mask in accordance with the given \p SubMask.
664 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
665   if (SubMask.empty())
666     return;
667   if (Mask.empty()) {
668     Mask.append(SubMask.begin(), SubMask.end());
669     return;
670   }
671   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
672   int TermValue = std::min(Mask.size(), SubMask.size());
673   for (int I = 0, E = SubMask.size(); I < E; ++I) {
674     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
675         Mask[SubMask[I]] >= TermValue)
676       continue;
677     NewMask[I] = Mask[SubMask[I]];
678   }
679   Mask.swap(NewMask);
680 }
681 
682 /// Order may have elements assigned special value (size) which is out of
683 /// bounds. Such indices only appear on places which correspond to undef values
684 /// (see canReuseExtract for details) and used in order to avoid undef values
685 /// have effect on operands ordering.
686 /// The first loop below simply finds all unused indices and then the next loop
687 /// nest assigns these indices for undef values positions.
688 /// As an example below Order has two undef positions and they have assigned
689 /// values 3 and 7 respectively:
690 /// before:  6 9 5 4 9 2 1 0
691 /// after:   6 3 5 4 7 2 1 0
692 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
693   const unsigned Sz = Order.size();
694   SmallBitVector UnusedIndices(Sz, /*t=*/true);
695   SmallBitVector MaskedIndices(Sz);
696   for (unsigned I = 0; I < Sz; ++I) {
697     if (Order[I] < Sz)
698       UnusedIndices.reset(Order[I]);
699     else
700       MaskedIndices.set(I);
701   }
702   if (MaskedIndices.none())
703     return;
704   assert(UnusedIndices.count() == MaskedIndices.count() &&
705          "Non-synced masked/available indices.");
706   int Idx = UnusedIndices.find_first();
707   int MIdx = MaskedIndices.find_first();
708   while (MIdx >= 0) {
709     assert(Idx >= 0 && "Indices must be synced.");
710     Order[MIdx] = Idx;
711     Idx = UnusedIndices.find_next(Idx);
712     MIdx = MaskedIndices.find_next(MIdx);
713   }
714 }
715 
716 namespace llvm {
717 
718 static void inversePermutation(ArrayRef<unsigned> Indices,
719                                SmallVectorImpl<int> &Mask) {
720   Mask.clear();
721   const unsigned E = Indices.size();
722   Mask.resize(E, UndefMaskElem);
723   for (unsigned I = 0; I < E; ++I)
724     Mask[Indices[I]] = I;
725 }
726 
727 /// \returns inserting index of InsertElement or InsertValue instruction,
728 /// using Offset as base offset for index.
729 static Optional<unsigned> getInsertIndex(Value *InsertInst,
730                                          unsigned Offset = 0) {
731   int Index = Offset;
732   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
733     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
734       auto *VT = cast<FixedVectorType>(IE->getType());
735       if (CI->getValue().uge(VT->getNumElements()))
736         return None;
737       Index *= VT->getNumElements();
738       Index += CI->getZExtValue();
739       return Index;
740     }
741     return None;
742   }
743 
744   auto *IV = cast<InsertValueInst>(InsertInst);
745   Type *CurrentType = IV->getType();
746   for (unsigned I : IV->indices()) {
747     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
748       Index *= ST->getNumElements();
749       CurrentType = ST->getElementType(I);
750     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
751       Index *= AT->getNumElements();
752       CurrentType = AT->getElementType();
753     } else {
754       return None;
755     }
756     Index += I;
757   }
758   return Index;
759 }
760 
761 /// Reorders the list of scalars in accordance with the given \p Mask.
762 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
763                            ArrayRef<int> Mask) {
764   assert(!Mask.empty() && "Expected non-empty mask.");
765   SmallVector<Value *> Prev(Scalars.size(),
766                             UndefValue::get(Scalars.front()->getType()));
767   Prev.swap(Scalars);
768   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
769     if (Mask[I] != UndefMaskElem)
770       Scalars[Mask[I]] = Prev[I];
771 }
772 
773 /// Checks if the provided value does not require scheduling. It does not
774 /// require scheduling if this is not an instruction or it is an instruction
775 /// that does not read/write memory and all operands are either not instructions
776 /// or phi nodes or instructions from different blocks.
777 static bool areAllOperandsNonInsts(Value *V) {
778   auto *I = dyn_cast<Instruction>(V);
779   if (!I)
780     return true;
781   return !mayHaveNonDefUseDependency(*I) &&
782     all_of(I->operands(), [I](Value *V) {
783       auto *IO = dyn_cast<Instruction>(V);
784       if (!IO)
785         return true;
786       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
787     });
788 }
789 
790 /// Checks if the provided value does not require scheduling. It does not
791 /// require scheduling if this is not an instruction or it is an instruction
792 /// that does not read/write memory and all users are phi nodes or instructions
793 /// from the different blocks.
794 static bool isUsedOutsideBlock(Value *V) {
795   auto *I = dyn_cast<Instruction>(V);
796   if (!I)
797     return true;
798   // Limits the number of uses to save compile time.
799   constexpr int UsesLimit = 8;
800   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
801          all_of(I->users(), [I](User *U) {
802            auto *IU = dyn_cast<Instruction>(U);
803            if (!IU)
804              return true;
805            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
806          });
807 }
808 
809 /// Checks if the specified value does not require scheduling. It does not
810 /// require scheduling if all operands and all users do not need to be scheduled
811 /// in the current basic block.
812 static bool doesNotNeedToBeScheduled(Value *V) {
813   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
814 }
815 
816 /// Checks if the specified array of instructions does not require scheduling.
817 /// It is so if all either instructions have operands that do not require
818 /// scheduling or their users do not require scheduling since they are phis or
819 /// in other basic blocks.
820 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
821   return !VL.empty() &&
822          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
823 }
824 
825 namespace slpvectorizer {
826 
827 /// Bottom Up SLP Vectorizer.
828 class BoUpSLP {
829   struct TreeEntry;
830   struct ScheduleData;
831 
832 public:
833   using ValueList = SmallVector<Value *, 8>;
834   using InstrList = SmallVector<Instruction *, 16>;
835   using ValueSet = SmallPtrSet<Value *, 16>;
836   using StoreList = SmallVector<StoreInst *, 8>;
837   using ExtraValueToDebugLocsMap =
838       MapVector<Value *, SmallVector<Instruction *, 2>>;
839   using OrdersType = SmallVector<unsigned, 4>;
840 
841   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
842           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
843           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
844           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
845       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
846         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
847     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
848     // Use the vector register size specified by the target unless overridden
849     // by a command-line option.
850     // TODO: It would be better to limit the vectorization factor based on
851     //       data type rather than just register size. For example, x86 AVX has
852     //       256-bit registers, but it does not support integer operations
853     //       at that width (that requires AVX2).
854     if (MaxVectorRegSizeOption.getNumOccurrences())
855       MaxVecRegSize = MaxVectorRegSizeOption;
856     else
857       MaxVecRegSize =
858           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
859               .getFixedSize();
860 
861     if (MinVectorRegSizeOption.getNumOccurrences())
862       MinVecRegSize = MinVectorRegSizeOption;
863     else
864       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
865   }
866 
867   /// Vectorize the tree that starts with the elements in \p VL.
868   /// Returns the vectorized root.
869   Value *vectorizeTree();
870 
871   /// Vectorize the tree but with the list of externally used values \p
872   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
873   /// generated extractvalue instructions.
874   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
875 
876   /// \returns the cost incurred by unwanted spills and fills, caused by
877   /// holding live values over call sites.
878   InstructionCost getSpillCost() const;
879 
880   /// \returns the vectorization cost of the subtree that starts at \p VL.
881   /// A negative number means that this is profitable.
882   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
883 
884   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
885   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
886   void buildTree(ArrayRef<Value *> Roots,
887                  ArrayRef<Value *> UserIgnoreLst = None);
888 
889   /// Builds external uses of the vectorized scalars, i.e. the list of
890   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
891   /// ExternallyUsedValues contains additional list of external uses to handle
892   /// vectorization of reductions.
893   void
894   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
895 
896   /// Clear the internal data structures that are created by 'buildTree'.
897   void deleteTree() {
898     VectorizableTree.clear();
899     ScalarToTreeEntry.clear();
900     MustGather.clear();
901     ExternalUses.clear();
902     for (auto &Iter : BlocksSchedules) {
903       BlockScheduling *BS = Iter.second.get();
904       BS->clear();
905     }
906     MinBWs.clear();
907     InstrElementSize.clear();
908   }
909 
910   unsigned getTreeSize() const { return VectorizableTree.size(); }
911 
912   /// Perform LICM and CSE on the newly generated gather sequences.
913   void optimizeGatherSequence();
914 
915   /// Checks if the specified gather tree entry \p TE can be represented as a
916   /// shuffled vector entry + (possibly) permutation with other gathers. It
917   /// implements the checks only for possibly ordered scalars (Loads,
918   /// ExtractElement, ExtractValue), which can be part of the graph.
919   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
920 
921   /// Gets reordering data for the given tree entry. If the entry is vectorized
922   /// - just return ReorderIndices, otherwise check if the scalars can be
923   /// reordered and return the most optimal order.
924   /// \param TopToBottom If true, include the order of vectorized stores and
925   /// insertelement nodes, otherwise skip them.
926   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
927 
928   /// Reorders the current graph to the most profitable order starting from the
929   /// root node to the leaf nodes. The best order is chosen only from the nodes
930   /// of the same size (vectorization factor). Smaller nodes are considered
931   /// parts of subgraph with smaller VF and they are reordered independently. We
932   /// can make it because we still need to extend smaller nodes to the wider VF
933   /// and we can merge reordering shuffles with the widening shuffles.
934   void reorderTopToBottom();
935 
936   /// Reorders the current graph to the most profitable order starting from
937   /// leaves to the root. It allows to rotate small subgraphs and reduce the
938   /// number of reshuffles if the leaf nodes use the same order. In this case we
939   /// can merge the orders and just shuffle user node instead of shuffling its
940   /// operands. Plus, even the leaf nodes have different orders, it allows to
941   /// sink reordering in the graph closer to the root node and merge it later
942   /// during analysis.
943   void reorderBottomToTop(bool IgnoreReorder = false);
944 
945   /// \return The vector element size in bits to use when vectorizing the
946   /// expression tree ending at \p V. If V is a store, the size is the width of
947   /// the stored value. Otherwise, the size is the width of the largest loaded
948   /// value reaching V. This method is used by the vectorizer to calculate
949   /// vectorization factors.
950   unsigned getVectorElementSize(Value *V);
951 
952   /// Compute the minimum type sizes required to represent the entries in a
953   /// vectorizable tree.
954   void computeMinimumValueSizes();
955 
956   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
957   unsigned getMaxVecRegSize() const {
958     return MaxVecRegSize;
959   }
960 
961   // \returns minimum vector register size as set by cl::opt.
962   unsigned getMinVecRegSize() const {
963     return MinVecRegSize;
964   }
965 
966   unsigned getMinVF(unsigned Sz) const {
967     return std::max(2U, getMinVecRegSize() / Sz);
968   }
969 
970   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
971     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
972       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
973     return MaxVF ? MaxVF : UINT_MAX;
974   }
975 
976   /// Check if homogeneous aggregate is isomorphic to some VectorType.
977   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
978   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
979   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
980   ///
981   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
982   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
983 
984   /// \returns True if the VectorizableTree is both tiny and not fully
985   /// vectorizable. We do not vectorize such trees.
986   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
987 
988   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
989   /// can be load combined in the backend. Load combining may not be allowed in
990   /// the IR optimizer, so we do not want to alter the pattern. For example,
991   /// partially transforming a scalar bswap() pattern into vector code is
992   /// effectively impossible for the backend to undo.
993   /// TODO: If load combining is allowed in the IR optimizer, this analysis
994   ///       may not be necessary.
995   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
996 
997   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
998   /// can be load combined in the backend. Load combining may not be allowed in
999   /// the IR optimizer, so we do not want to alter the pattern. For example,
1000   /// partially transforming a scalar bswap() pattern into vector code is
1001   /// effectively impossible for the backend to undo.
1002   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1003   ///       may not be necessary.
1004   bool isLoadCombineCandidate() const;
1005 
1006   OptimizationRemarkEmitter *getORE() { return ORE; }
1007 
1008   /// This structure holds any data we need about the edges being traversed
1009   /// during buildTree_rec(). We keep track of:
1010   /// (i) the user TreeEntry index, and
1011   /// (ii) the index of the edge.
1012   struct EdgeInfo {
1013     EdgeInfo() = default;
1014     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1015         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1016     /// The user TreeEntry.
1017     TreeEntry *UserTE = nullptr;
1018     /// The operand index of the use.
1019     unsigned EdgeIdx = UINT_MAX;
1020 #ifndef NDEBUG
1021     friend inline raw_ostream &operator<<(raw_ostream &OS,
1022                                           const BoUpSLP::EdgeInfo &EI) {
1023       EI.dump(OS);
1024       return OS;
1025     }
1026     /// Debug print.
1027     void dump(raw_ostream &OS) const {
1028       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1029          << " EdgeIdx:" << EdgeIdx << "}";
1030     }
1031     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1032 #endif
1033   };
1034 
1035   /// A helper data structure to hold the operands of a vector of instructions.
1036   /// This supports a fixed vector length for all operand vectors.
1037   class VLOperands {
1038     /// For each operand we need (i) the value, and (ii) the opcode that it
1039     /// would be attached to if the expression was in a left-linearized form.
1040     /// This is required to avoid illegal operand reordering.
1041     /// For example:
1042     /// \verbatim
1043     ///                         0 Op1
1044     ///                         |/
1045     /// Op1 Op2   Linearized    + Op2
1046     ///   \ /     ---------->   |/
1047     ///    -                    -
1048     ///
1049     /// Op1 - Op2            (0 + Op1) - Op2
1050     /// \endverbatim
1051     ///
1052     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1053     ///
1054     /// Another way to think of this is to track all the operations across the
1055     /// path from the operand all the way to the root of the tree and to
1056     /// calculate the operation that corresponds to this path. For example, the
1057     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1058     /// corresponding operation is a '-' (which matches the one in the
1059     /// linearized tree, as shown above).
1060     ///
1061     /// For lack of a better term, we refer to this operation as Accumulated
1062     /// Path Operation (APO).
1063     struct OperandData {
1064       OperandData() = default;
1065       OperandData(Value *V, bool APO, bool IsUsed)
1066           : V(V), APO(APO), IsUsed(IsUsed) {}
1067       /// The operand value.
1068       Value *V = nullptr;
1069       /// TreeEntries only allow a single opcode, or an alternate sequence of
1070       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1071       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1072       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1073       /// (e.g., Add/Mul)
1074       bool APO = false;
1075       /// Helper data for the reordering function.
1076       bool IsUsed = false;
1077     };
1078 
1079     /// During operand reordering, we are trying to select the operand at lane
1080     /// that matches best with the operand at the neighboring lane. Our
1081     /// selection is based on the type of value we are looking for. For example,
1082     /// if the neighboring lane has a load, we need to look for a load that is
1083     /// accessing a consecutive address. These strategies are summarized in the
1084     /// 'ReorderingMode' enumerator.
1085     enum class ReorderingMode {
1086       Load,     ///< Matching loads to consecutive memory addresses
1087       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1088       Constant, ///< Matching constants
1089       Splat,    ///< Matching the same instruction multiple times (broadcast)
1090       Failed,   ///< We failed to create a vectorizable group
1091     };
1092 
1093     using OperandDataVec = SmallVector<OperandData, 2>;
1094 
1095     /// A vector of operand vectors.
1096     SmallVector<OperandDataVec, 4> OpsVec;
1097 
1098     const DataLayout &DL;
1099     ScalarEvolution &SE;
1100     const BoUpSLP &R;
1101 
1102     /// \returns the operand data at \p OpIdx and \p Lane.
1103     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1104       return OpsVec[OpIdx][Lane];
1105     }
1106 
1107     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1108     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1109       return OpsVec[OpIdx][Lane];
1110     }
1111 
1112     /// Clears the used flag for all entries.
1113     void clearUsed() {
1114       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1115            OpIdx != NumOperands; ++OpIdx)
1116         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1117              ++Lane)
1118           OpsVec[OpIdx][Lane].IsUsed = false;
1119     }
1120 
1121     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1122     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1123       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1124     }
1125 
1126     // The hard-coded scores listed here are not very important, though it shall
1127     // be higher for better matches to improve the resulting cost. When
1128     // computing the scores of matching one sub-tree with another, we are
1129     // basically counting the number of values that are matching. So even if all
1130     // scores are set to 1, we would still get a decent matching result.
1131     // However, sometimes we have to break ties. For example we may have to
1132     // choose between matching loads vs matching opcodes. This is what these
1133     // scores are helping us with: they provide the order of preference. Also,
1134     // this is important if the scalar is externally used or used in another
1135     // tree entry node in the different lane.
1136 
1137     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1138     static const int ScoreConsecutiveLoads = 4;
1139     /// The same load multiple times. This should have a better score than
1140     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1141     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1142     /// a vector load and 1.0 for a broadcast.
1143     static const int ScoreSplatLoads = 3;
1144     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1145     static const int ScoreReversedLoads = 3;
1146     /// ExtractElementInst from same vector and consecutive indexes.
1147     static const int ScoreConsecutiveExtracts = 4;
1148     /// ExtractElementInst from same vector and reversed indices.
1149     static const int ScoreReversedExtracts = 3;
1150     /// Constants.
1151     static const int ScoreConstants = 2;
1152     /// Instructions with the same opcode.
1153     static const int ScoreSameOpcode = 2;
1154     /// Instructions with alt opcodes (e.g, add + sub).
1155     static const int ScoreAltOpcodes = 1;
1156     /// Identical instructions (a.k.a. splat or broadcast).
1157     static const int ScoreSplat = 1;
1158     /// Matching with an undef is preferable to failing.
1159     static const int ScoreUndef = 1;
1160     /// Score for failing to find a decent match.
1161     static const int ScoreFail = 0;
1162     /// Score if all users are vectorized.
1163     static const int ScoreAllUserVectorized = 1;
1164 
1165     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1166     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1167     /// MainAltOps.
1168     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1169                                ScalarEvolution &SE, int NumLanes,
1170                                ArrayRef<Value *> MainAltOps,
1171                                const TargetTransformInfo *TTI) {
1172       if (V1 == V2) {
1173         if (isa<LoadInst>(V1)) {
1174           // A broadcast of a load can be cheaper on some targets.
1175           // TODO: For now accept a broadcast load with no other internal uses.
1176           if (TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1177               (int)V1->getNumUses() == NumLanes)
1178             return VLOperands::ScoreSplatLoads;
1179         }
1180         return VLOperands::ScoreSplat;
1181       }
1182 
1183       auto *LI1 = dyn_cast<LoadInst>(V1);
1184       auto *LI2 = dyn_cast<LoadInst>(V2);
1185       if (LI1 && LI2) {
1186         if (LI1->getParent() != LI2->getParent())
1187           return VLOperands::ScoreFail;
1188 
1189         Optional<int> Dist = getPointersDiff(
1190             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1191             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1192         if (!Dist || *Dist == 0)
1193           return VLOperands::ScoreFail;
1194         // The distance is too large - still may be profitable to use masked
1195         // loads/gathers.
1196         if (std::abs(*Dist) > NumLanes / 2)
1197           return VLOperands::ScoreAltOpcodes;
1198         // This still will detect consecutive loads, but we might have "holes"
1199         // in some cases. It is ok for non-power-2 vectorization and may produce
1200         // better results. It should not affect current vectorization.
1201         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1202                            : VLOperands::ScoreReversedLoads;
1203       }
1204 
1205       auto *C1 = dyn_cast<Constant>(V1);
1206       auto *C2 = dyn_cast<Constant>(V2);
1207       if (C1 && C2)
1208         return VLOperands::ScoreConstants;
1209 
1210       // Extracts from consecutive indexes of the same vector better score as
1211       // the extracts could be optimized away.
1212       Value *EV1;
1213       ConstantInt *Ex1Idx;
1214       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1215         // Undefs are always profitable for extractelements.
1216         if (isa<UndefValue>(V2))
1217           return VLOperands::ScoreConsecutiveExtracts;
1218         Value *EV2 = nullptr;
1219         ConstantInt *Ex2Idx = nullptr;
1220         if (match(V2,
1221                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1222                                                          m_Undef())))) {
1223           // Undefs are always profitable for extractelements.
1224           if (!Ex2Idx)
1225             return VLOperands::ScoreConsecutiveExtracts;
1226           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1227             return VLOperands::ScoreConsecutiveExtracts;
1228           if (EV2 == EV1) {
1229             int Idx1 = Ex1Idx->getZExtValue();
1230             int Idx2 = Ex2Idx->getZExtValue();
1231             int Dist = Idx2 - Idx1;
1232             // The distance is too large - still may be profitable to use
1233             // shuffles.
1234             if (std::abs(Dist) == 0)
1235               return VLOperands::ScoreSplat;
1236             if (std::abs(Dist) > NumLanes / 2)
1237               return VLOperands::ScoreSameOpcode;
1238             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1239                               : VLOperands::ScoreReversedExtracts;
1240           }
1241           return VLOperands::ScoreAltOpcodes;
1242         }
1243         return VLOperands::ScoreFail;
1244       }
1245 
1246       auto *I1 = dyn_cast<Instruction>(V1);
1247       auto *I2 = dyn_cast<Instruction>(V2);
1248       if (I1 && I2) {
1249         if (I1->getParent() != I2->getParent())
1250           return VLOperands::ScoreFail;
1251         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1252         Ops.push_back(I1);
1253         Ops.push_back(I2);
1254         InstructionsState S = getSameOpcode(Ops);
1255         // Note: Only consider instructions with <= 2 operands to avoid
1256         // complexity explosion.
1257         if (S.getOpcode() &&
1258             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1259              !S.isAltShuffle()) &&
1260             all_of(Ops, [&S](Value *V) {
1261               return cast<Instruction>(V)->getNumOperands() ==
1262                      S.MainOp->getNumOperands();
1263             }))
1264           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1265                                   : VLOperands::ScoreSameOpcode;
1266       }
1267 
1268       if (isa<UndefValue>(V2))
1269         return VLOperands::ScoreUndef;
1270 
1271       return VLOperands::ScoreFail;
1272     }
1273 
1274     /// \param Lane lane of the operands under analysis.
1275     /// \param OpIdx operand index in \p Lane lane we're looking the best
1276     /// candidate for.
1277     /// \param Idx operand index of the current candidate value.
1278     /// \returns The additional score due to possible broadcasting of the
1279     /// elements in the lane. It is more profitable to have power-of-2 unique
1280     /// elements in the lane, it will be vectorized with higher probability
1281     /// after removing duplicates. Currently the SLP vectorizer supports only
1282     /// vectorization of the power-of-2 number of unique scalars.
1283     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1284       Value *IdxLaneV = getData(Idx, Lane).V;
1285       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1286         return 0;
1287       SmallPtrSet<Value *, 4> Uniques;
1288       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1289         if (Ln == Lane)
1290           continue;
1291         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1292         if (!isa<Instruction>(OpIdxLnV))
1293           return 0;
1294         Uniques.insert(OpIdxLnV);
1295       }
1296       int UniquesCount = Uniques.size();
1297       int UniquesCntWithIdxLaneV =
1298           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1299       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1300       int UniquesCntWithOpIdxLaneV =
1301           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1302       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1303         return 0;
1304       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1305               UniquesCntWithOpIdxLaneV) -
1306              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1307     }
1308 
1309     /// \param Lane lane of the operands under analysis.
1310     /// \param OpIdx operand index in \p Lane lane we're looking the best
1311     /// candidate for.
1312     /// \param Idx operand index of the current candidate value.
1313     /// \returns The additional score for the scalar which users are all
1314     /// vectorized.
1315     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1316       Value *IdxLaneV = getData(Idx, Lane).V;
1317       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1318       // Do not care about number of uses for vector-like instructions
1319       // (extractelement/extractvalue with constant indices), they are extracts
1320       // themselves and already externally used. Vectorization of such
1321       // instructions does not add extra extractelement instruction, just may
1322       // remove it.
1323       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1324           isVectorLikeInstWithConstOps(OpIdxLaneV))
1325         return VLOperands::ScoreAllUserVectorized;
1326       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1327       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1328         return 0;
1329       return R.areAllUsersVectorized(IdxLaneI, None)
1330                  ? VLOperands::ScoreAllUserVectorized
1331                  : 0;
1332     }
1333 
1334     /// Go through the operands of \p LHS and \p RHS recursively until \p
1335     /// MaxLevel, and return the cummulative score. For example:
1336     /// \verbatim
1337     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1338     ///     \ /         \ /         \ /        \ /
1339     ///      +           +           +          +
1340     ///     G1          G2          G3         G4
1341     /// \endverbatim
1342     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1343     /// each level recursively, accumulating the score. It starts from matching
1344     /// the additions at level 0, then moves on to the loads (level 1). The
1345     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1346     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1347     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1348     /// Please note that the order of the operands does not matter, as we
1349     /// evaluate the score of all profitable combinations of operands. In
1350     /// other words the score of G1 and G4 is the same as G1 and G2. This
1351     /// heuristic is based on ideas described in:
1352     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1353     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1354     ///   Luís F. W. Góes
1355     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1356                            ArrayRef<Value *> MainAltOps) {
1357 
1358       // Get the shallow score of V1 and V2.
1359       int ShallowScoreAtThisLevel =
1360           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps, R.TTI);
1361 
1362       // If reached MaxLevel,
1363       //  or if V1 and V2 are not instructions,
1364       //  or if they are SPLAT,
1365       //  or if they are not consecutive,
1366       //  or if profitable to vectorize loads or extractelements, early return
1367       //  the current cost.
1368       auto *I1 = dyn_cast<Instruction>(LHS);
1369       auto *I2 = dyn_cast<Instruction>(RHS);
1370       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1371           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1372           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1373             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1374             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1375            ShallowScoreAtThisLevel))
1376         return ShallowScoreAtThisLevel;
1377       assert(I1 && I2 && "Should have early exited.");
1378 
1379       // Contains the I2 operand indexes that got matched with I1 operands.
1380       SmallSet<unsigned, 4> Op2Used;
1381 
1382       // Recursion towards the operands of I1 and I2. We are trying all possible
1383       // operand pairs, and keeping track of the best score.
1384       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1385            OpIdx1 != NumOperands1; ++OpIdx1) {
1386         // Try to pair op1I with the best operand of I2.
1387         int MaxTmpScore = 0;
1388         unsigned MaxOpIdx2 = 0;
1389         bool FoundBest = false;
1390         // If I2 is commutative try all combinations.
1391         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1392         unsigned ToIdx = isCommutative(I2)
1393                              ? I2->getNumOperands()
1394                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1395         assert(FromIdx <= ToIdx && "Bad index");
1396         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1397           // Skip operands already paired with OpIdx1.
1398           if (Op2Used.count(OpIdx2))
1399             continue;
1400           // Recursively calculate the cost at each level
1401           int TmpScore =
1402               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1403                                  CurrLevel + 1, MaxLevel, None);
1404           // Look for the best score.
1405           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1406             MaxTmpScore = TmpScore;
1407             MaxOpIdx2 = OpIdx2;
1408             FoundBest = true;
1409           }
1410         }
1411         if (FoundBest) {
1412           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1413           Op2Used.insert(MaxOpIdx2);
1414           ShallowScoreAtThisLevel += MaxTmpScore;
1415         }
1416       }
1417       return ShallowScoreAtThisLevel;
1418     }
1419 
1420     /// Score scaling factor for fully compatible instructions but with
1421     /// different number of external uses. Allows better selection of the
1422     /// instructions with less external uses.
1423     static const int ScoreScaleFactor = 10;
1424 
1425     /// \Returns the look-ahead score, which tells us how much the sub-trees
1426     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1427     /// score. This helps break ties in an informed way when we cannot decide on
1428     /// the order of the operands by just considering the immediate
1429     /// predecessors.
1430     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1431                           int Lane, unsigned OpIdx, unsigned Idx,
1432                           bool &IsUsed) {
1433       int Score =
1434           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1435       if (Score) {
1436         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1437         if (Score <= -SplatScore) {
1438           // Set the minimum score for splat-like sequence to avoid setting
1439           // failed state.
1440           Score = 1;
1441         } else {
1442           Score += SplatScore;
1443           // Scale score to see the difference between different operands
1444           // and similar operands but all vectorized/not all vectorized
1445           // uses. It does not affect actual selection of the best
1446           // compatible operand in general, just allows to select the
1447           // operand with all vectorized uses.
1448           Score *= ScoreScaleFactor;
1449           Score += getExternalUseScore(Lane, OpIdx, Idx);
1450           IsUsed = true;
1451         }
1452       }
1453       return Score;
1454     }
1455 
1456     /// Best defined scores per lanes between the passes. Used to choose the
1457     /// best operand (with the highest score) between the passes.
1458     /// The key - {Operand Index, Lane}.
1459     /// The value - the best score between the passes for the lane and the
1460     /// operand.
1461     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1462         BestScoresPerLanes;
1463 
1464     // Search all operands in Ops[*][Lane] for the one that matches best
1465     // Ops[OpIdx][LastLane] and return its opreand index.
1466     // If no good match can be found, return None.
1467     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1468                                       ArrayRef<ReorderingMode> ReorderingModes,
1469                                       ArrayRef<Value *> MainAltOps) {
1470       unsigned NumOperands = getNumOperands();
1471 
1472       // The operand of the previous lane at OpIdx.
1473       Value *OpLastLane = getData(OpIdx, LastLane).V;
1474 
1475       // Our strategy mode for OpIdx.
1476       ReorderingMode RMode = ReorderingModes[OpIdx];
1477       if (RMode == ReorderingMode::Failed)
1478         return None;
1479 
1480       // The linearized opcode of the operand at OpIdx, Lane.
1481       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1482 
1483       // The best operand index and its score.
1484       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1485       // are using the score to differentiate between the two.
1486       struct BestOpData {
1487         Optional<unsigned> Idx = None;
1488         unsigned Score = 0;
1489       } BestOp;
1490       BestOp.Score =
1491           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1492               .first->second;
1493 
1494       // Track if the operand must be marked as used. If the operand is set to
1495       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1496       // want to reestimate the operands again on the following iterations).
1497       bool IsUsed =
1498           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1499       // Iterate through all unused operands and look for the best.
1500       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1501         // Get the operand at Idx and Lane.
1502         OperandData &OpData = getData(Idx, Lane);
1503         Value *Op = OpData.V;
1504         bool OpAPO = OpData.APO;
1505 
1506         // Skip already selected operands.
1507         if (OpData.IsUsed)
1508           continue;
1509 
1510         // Skip if we are trying to move the operand to a position with a
1511         // different opcode in the linearized tree form. This would break the
1512         // semantics.
1513         if (OpAPO != OpIdxAPO)
1514           continue;
1515 
1516         // Look for an operand that matches the current mode.
1517         switch (RMode) {
1518         case ReorderingMode::Load:
1519         case ReorderingMode::Constant:
1520         case ReorderingMode::Opcode: {
1521           bool LeftToRight = Lane > LastLane;
1522           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1523           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1524           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1525                                         OpIdx, Idx, IsUsed);
1526           if (Score > static_cast<int>(BestOp.Score)) {
1527             BestOp.Idx = Idx;
1528             BestOp.Score = Score;
1529             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1530           }
1531           break;
1532         }
1533         case ReorderingMode::Splat:
1534           if (Op == OpLastLane)
1535             BestOp.Idx = Idx;
1536           break;
1537         case ReorderingMode::Failed:
1538           llvm_unreachable("Not expected Failed reordering mode.");
1539         }
1540       }
1541 
1542       if (BestOp.Idx) {
1543         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1544         return BestOp.Idx;
1545       }
1546       // If we could not find a good match return None.
1547       return None;
1548     }
1549 
1550     /// Helper for reorderOperandVecs.
1551     /// \returns the lane that we should start reordering from. This is the one
1552     /// which has the least number of operands that can freely move about or
1553     /// less profitable because it already has the most optimal set of operands.
1554     unsigned getBestLaneToStartReordering() const {
1555       unsigned Min = UINT_MAX;
1556       unsigned SameOpNumber = 0;
1557       // std::pair<unsigned, unsigned> is used to implement a simple voting
1558       // algorithm and choose the lane with the least number of operands that
1559       // can freely move about or less profitable because it already has the
1560       // most optimal set of operands. The first unsigned is a counter for
1561       // voting, the second unsigned is the counter of lanes with instructions
1562       // with same/alternate opcodes and same parent basic block.
1563       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1564       // Try to be closer to the original results, if we have multiple lanes
1565       // with same cost. If 2 lanes have the same cost, use the one with the
1566       // lowest index.
1567       for (int I = getNumLanes(); I > 0; --I) {
1568         unsigned Lane = I - 1;
1569         OperandsOrderData NumFreeOpsHash =
1570             getMaxNumOperandsThatCanBeReordered(Lane);
1571         // Compare the number of operands that can move and choose the one with
1572         // the least number.
1573         if (NumFreeOpsHash.NumOfAPOs < Min) {
1574           Min = NumFreeOpsHash.NumOfAPOs;
1575           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1576           HashMap.clear();
1577           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1578         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1579                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1580           // Select the most optimal lane in terms of number of operands that
1581           // should be moved around.
1582           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1583           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1584         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1585                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1586           auto It = HashMap.find(NumFreeOpsHash.Hash);
1587           if (It == HashMap.end())
1588             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1589           else
1590             ++It->second.first;
1591         }
1592       }
1593       // Select the lane with the minimum counter.
1594       unsigned BestLane = 0;
1595       unsigned CntMin = UINT_MAX;
1596       for (const auto &Data : reverse(HashMap)) {
1597         if (Data.second.first < CntMin) {
1598           CntMin = Data.second.first;
1599           BestLane = Data.second.second;
1600         }
1601       }
1602       return BestLane;
1603     }
1604 
1605     /// Data structure that helps to reorder operands.
1606     struct OperandsOrderData {
1607       /// The best number of operands with the same APOs, which can be
1608       /// reordered.
1609       unsigned NumOfAPOs = UINT_MAX;
1610       /// Number of operands with the same/alternate instruction opcode and
1611       /// parent.
1612       unsigned NumOpsWithSameOpcodeParent = 0;
1613       /// Hash for the actual operands ordering.
1614       /// Used to count operands, actually their position id and opcode
1615       /// value. It is used in the voting mechanism to find the lane with the
1616       /// least number of operands that can freely move about or less profitable
1617       /// because it already has the most optimal set of operands. Can be
1618       /// replaced with SmallVector<unsigned> instead but hash code is faster
1619       /// and requires less memory.
1620       unsigned Hash = 0;
1621     };
1622     /// \returns the maximum number of operands that are allowed to be reordered
1623     /// for \p Lane and the number of compatible instructions(with the same
1624     /// parent/opcode). This is used as a heuristic for selecting the first lane
1625     /// to start operand reordering.
1626     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1627       unsigned CntTrue = 0;
1628       unsigned NumOperands = getNumOperands();
1629       // Operands with the same APO can be reordered. We therefore need to count
1630       // how many of them we have for each APO, like this: Cnt[APO] = x.
1631       // Since we only have two APOs, namely true and false, we can avoid using
1632       // a map. Instead we can simply count the number of operands that
1633       // correspond to one of them (in this case the 'true' APO), and calculate
1634       // the other by subtracting it from the total number of operands.
1635       // Operands with the same instruction opcode and parent are more
1636       // profitable since we don't need to move them in many cases, with a high
1637       // probability such lane already can be vectorized effectively.
1638       bool AllUndefs = true;
1639       unsigned NumOpsWithSameOpcodeParent = 0;
1640       Instruction *OpcodeI = nullptr;
1641       BasicBlock *Parent = nullptr;
1642       unsigned Hash = 0;
1643       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1644         const OperandData &OpData = getData(OpIdx, Lane);
1645         if (OpData.APO)
1646           ++CntTrue;
1647         // Use Boyer-Moore majority voting for finding the majority opcode and
1648         // the number of times it occurs.
1649         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1650           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1651               I->getParent() != Parent) {
1652             if (NumOpsWithSameOpcodeParent == 0) {
1653               NumOpsWithSameOpcodeParent = 1;
1654               OpcodeI = I;
1655               Parent = I->getParent();
1656             } else {
1657               --NumOpsWithSameOpcodeParent;
1658             }
1659           } else {
1660             ++NumOpsWithSameOpcodeParent;
1661           }
1662         }
1663         Hash = hash_combine(
1664             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1665         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1666       }
1667       if (AllUndefs)
1668         return {};
1669       OperandsOrderData Data;
1670       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1671       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1672       Data.Hash = Hash;
1673       return Data;
1674     }
1675 
1676     /// Go through the instructions in VL and append their operands.
1677     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1678       assert(!VL.empty() && "Bad VL");
1679       assert((empty() || VL.size() == getNumLanes()) &&
1680              "Expected same number of lanes");
1681       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1682       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1683       OpsVec.resize(NumOperands);
1684       unsigned NumLanes = VL.size();
1685       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1686         OpsVec[OpIdx].resize(NumLanes);
1687         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1688           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1689           // Our tree has just 3 nodes: the root and two operands.
1690           // It is therefore trivial to get the APO. We only need to check the
1691           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1692           // RHS operand. The LHS operand of both add and sub is never attached
1693           // to an inversese operation in the linearized form, therefore its APO
1694           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1695 
1696           // Since operand reordering is performed on groups of commutative
1697           // operations or alternating sequences (e.g., +, -), we can safely
1698           // tell the inverse operations by checking commutativity.
1699           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1700           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1701           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1702                                  APO, false};
1703         }
1704       }
1705     }
1706 
1707     /// \returns the number of operands.
1708     unsigned getNumOperands() const { return OpsVec.size(); }
1709 
1710     /// \returns the number of lanes.
1711     unsigned getNumLanes() const { return OpsVec[0].size(); }
1712 
1713     /// \returns the operand value at \p OpIdx and \p Lane.
1714     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1715       return getData(OpIdx, Lane).V;
1716     }
1717 
1718     /// \returns true if the data structure is empty.
1719     bool empty() const { return OpsVec.empty(); }
1720 
1721     /// Clears the data.
1722     void clear() { OpsVec.clear(); }
1723 
1724     /// \Returns true if there are enough operands identical to \p Op to fill
1725     /// the whole vector.
1726     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1727     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1728       bool OpAPO = getData(OpIdx, Lane).APO;
1729       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1730         if (Ln == Lane)
1731           continue;
1732         // This is set to true if we found a candidate for broadcast at Lane.
1733         bool FoundCandidate = false;
1734         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1735           OperandData &Data = getData(OpI, Ln);
1736           if (Data.APO != OpAPO || Data.IsUsed)
1737             continue;
1738           if (Data.V == Op) {
1739             FoundCandidate = true;
1740             Data.IsUsed = true;
1741             break;
1742           }
1743         }
1744         if (!FoundCandidate)
1745           return false;
1746       }
1747       return true;
1748     }
1749 
1750   public:
1751     /// Initialize with all the operands of the instruction vector \p RootVL.
1752     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1753                ScalarEvolution &SE, const BoUpSLP &R)
1754         : DL(DL), SE(SE), R(R) {
1755       // Append all the operands of RootVL.
1756       appendOperandsOfVL(RootVL);
1757     }
1758 
1759     /// \Returns a value vector with the operands across all lanes for the
1760     /// opearnd at \p OpIdx.
1761     ValueList getVL(unsigned OpIdx) const {
1762       ValueList OpVL(OpsVec[OpIdx].size());
1763       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1764              "Expected same num of lanes across all operands");
1765       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1766         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1767       return OpVL;
1768     }
1769 
1770     // Performs operand reordering for 2 or more operands.
1771     // The original operands are in OrigOps[OpIdx][Lane].
1772     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1773     void reorder() {
1774       unsigned NumOperands = getNumOperands();
1775       unsigned NumLanes = getNumLanes();
1776       // Each operand has its own mode. We are using this mode to help us select
1777       // the instructions for each lane, so that they match best with the ones
1778       // we have selected so far.
1779       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1780 
1781       // This is a greedy single-pass algorithm. We are going over each lane
1782       // once and deciding on the best order right away with no back-tracking.
1783       // However, in order to increase its effectiveness, we start with the lane
1784       // that has operands that can move the least. For example, given the
1785       // following lanes:
1786       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1787       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1788       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1789       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1790       // we will start at Lane 1, since the operands of the subtraction cannot
1791       // be reordered. Then we will visit the rest of the lanes in a circular
1792       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1793 
1794       // Find the first lane that we will start our search from.
1795       unsigned FirstLane = getBestLaneToStartReordering();
1796 
1797       // Initialize the modes.
1798       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1799         Value *OpLane0 = getValue(OpIdx, FirstLane);
1800         // Keep track if we have instructions with all the same opcode on one
1801         // side.
1802         if (isa<LoadInst>(OpLane0))
1803           ReorderingModes[OpIdx] = ReorderingMode::Load;
1804         else if (isa<Instruction>(OpLane0)) {
1805           // Check if OpLane0 should be broadcast.
1806           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1807             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1808           else
1809             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1810         }
1811         else if (isa<Constant>(OpLane0))
1812           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1813         else if (isa<Argument>(OpLane0))
1814           // Our best hope is a Splat. It may save some cost in some cases.
1815           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1816         else
1817           // NOTE: This should be unreachable.
1818           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1819       }
1820 
1821       // Check that we don't have same operands. No need to reorder if operands
1822       // are just perfect diamond or shuffled diamond match. Do not do it only
1823       // for possible broadcasts or non-power of 2 number of scalars (just for
1824       // now).
1825       auto &&SkipReordering = [this]() {
1826         SmallPtrSet<Value *, 4> UniqueValues;
1827         ArrayRef<OperandData> Op0 = OpsVec.front();
1828         for (const OperandData &Data : Op0)
1829           UniqueValues.insert(Data.V);
1830         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1831           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1832                 return !UniqueValues.contains(Data.V);
1833               }))
1834             return false;
1835         }
1836         // TODO: Check if we can remove a check for non-power-2 number of
1837         // scalars after full support of non-power-2 vectorization.
1838         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1839       };
1840 
1841       // If the initial strategy fails for any of the operand indexes, then we
1842       // perform reordering again in a second pass. This helps avoid assigning
1843       // high priority to the failed strategy, and should improve reordering for
1844       // the non-failed operand indexes.
1845       for (int Pass = 0; Pass != 2; ++Pass) {
1846         // Check if no need to reorder operands since they're are perfect or
1847         // shuffled diamond match.
1848         // Need to to do it to avoid extra external use cost counting for
1849         // shuffled matches, which may cause regressions.
1850         if (SkipReordering())
1851           break;
1852         // Skip the second pass if the first pass did not fail.
1853         bool StrategyFailed = false;
1854         // Mark all operand data as free to use.
1855         clearUsed();
1856         // We keep the original operand order for the FirstLane, so reorder the
1857         // rest of the lanes. We are visiting the nodes in a circular fashion,
1858         // using FirstLane as the center point and increasing the radius
1859         // distance.
1860         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1861         for (unsigned I = 0; I < NumOperands; ++I)
1862           MainAltOps[I].push_back(getData(I, FirstLane).V);
1863 
1864         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1865           // Visit the lane on the right and then the lane on the left.
1866           for (int Direction : {+1, -1}) {
1867             int Lane = FirstLane + Direction * Distance;
1868             if (Lane < 0 || Lane >= (int)NumLanes)
1869               continue;
1870             int LastLane = Lane - Direction;
1871             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1872                    "Out of bounds");
1873             // Look for a good match for each operand.
1874             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1875               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1876               Optional<unsigned> BestIdx = getBestOperand(
1877                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1878               // By not selecting a value, we allow the operands that follow to
1879               // select a better matching value. We will get a non-null value in
1880               // the next run of getBestOperand().
1881               if (BestIdx) {
1882                 // Swap the current operand with the one returned by
1883                 // getBestOperand().
1884                 swap(OpIdx, BestIdx.getValue(), Lane);
1885               } else {
1886                 // We failed to find a best operand, set mode to 'Failed'.
1887                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1888                 // Enable the second pass.
1889                 StrategyFailed = true;
1890               }
1891               // Try to get the alternate opcode and follow it during analysis.
1892               if (MainAltOps[OpIdx].size() != 2) {
1893                 OperandData &AltOp = getData(OpIdx, Lane);
1894                 InstructionsState OpS =
1895                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1896                 if (OpS.getOpcode() && OpS.isAltShuffle())
1897                   MainAltOps[OpIdx].push_back(AltOp.V);
1898               }
1899             }
1900           }
1901         }
1902         // Skip second pass if the strategy did not fail.
1903         if (!StrategyFailed)
1904           break;
1905       }
1906     }
1907 
1908 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1909     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1910       switch (RMode) {
1911       case ReorderingMode::Load:
1912         return "Load";
1913       case ReorderingMode::Opcode:
1914         return "Opcode";
1915       case ReorderingMode::Constant:
1916         return "Constant";
1917       case ReorderingMode::Splat:
1918         return "Splat";
1919       case ReorderingMode::Failed:
1920         return "Failed";
1921       }
1922       llvm_unreachable("Unimplemented Reordering Type");
1923     }
1924 
1925     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1926                                                    raw_ostream &OS) {
1927       return OS << getModeStr(RMode);
1928     }
1929 
1930     /// Debug print.
1931     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1932       printMode(RMode, dbgs());
1933     }
1934 
1935     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1936       return printMode(RMode, OS);
1937     }
1938 
1939     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1940       const unsigned Indent = 2;
1941       unsigned Cnt = 0;
1942       for (const OperandDataVec &OpDataVec : OpsVec) {
1943         OS << "Operand " << Cnt++ << "\n";
1944         for (const OperandData &OpData : OpDataVec) {
1945           OS.indent(Indent) << "{";
1946           if (Value *V = OpData.V)
1947             OS << *V;
1948           else
1949             OS << "null";
1950           OS << ", APO:" << OpData.APO << "}\n";
1951         }
1952         OS << "\n";
1953       }
1954       return OS;
1955     }
1956 
1957     /// Debug print.
1958     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1959 #endif
1960   };
1961 
1962   /// Checks if the instruction is marked for deletion.
1963   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1964 
1965   /// Marks values operands for later deletion by replacing them with Undefs.
1966   void eraseInstructions(ArrayRef<Value *> AV);
1967 
1968   ~BoUpSLP();
1969 
1970 private:
1971   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1972   /// reordering (i.e. the operands can be reordered because they have only one
1973   /// user and reordarable).
1974   /// \param NonVectorized List of all gather nodes that require reordering
1975   /// (e.g., gather of extractlements or partially vectorizable loads).
1976   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1977   /// reordering, subset of \p NonVectorized.
1978   bool
1979   canReorderOperands(TreeEntry *UserTE,
1980                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1981                      ArrayRef<TreeEntry *> ReorderableGathers,
1982                      SmallVectorImpl<TreeEntry *> &GatherOps);
1983 
1984   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1985   /// if any. If it is not vectorized (gather node), returns nullptr.
1986   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1987     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1988     TreeEntry *TE = nullptr;
1989     const auto *It = find_if(VL, [this, &TE](Value *V) {
1990       TE = getTreeEntry(V);
1991       return TE;
1992     });
1993     if (It != VL.end() && TE->isSame(VL))
1994       return TE;
1995     return nullptr;
1996   }
1997 
1998   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1999   /// if any. If it is not vectorized (gather node), returns nullptr.
2000   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2001                                         unsigned OpIdx) const {
2002     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2003         const_cast<TreeEntry *>(UserTE), OpIdx);
2004   }
2005 
2006   /// Checks if all users of \p I are the part of the vectorization tree.
2007   bool areAllUsersVectorized(Instruction *I,
2008                              ArrayRef<Value *> VectorizedVals) const;
2009 
2010   /// \returns the cost of the vectorizable entry.
2011   InstructionCost getEntryCost(const TreeEntry *E,
2012                                ArrayRef<Value *> VectorizedVals);
2013 
2014   /// This is the recursive part of buildTree.
2015   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2016                      const EdgeInfo &EI);
2017 
2018   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2019   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2020   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2021   /// returns false, setting \p CurrentOrder to either an empty vector or a
2022   /// non-identity permutation that allows to reuse extract instructions.
2023   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2024                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2025 
2026   /// Vectorize a single entry in the tree.
2027   Value *vectorizeTree(TreeEntry *E);
2028 
2029   /// Vectorize a single entry in the tree, starting in \p VL.
2030   Value *vectorizeTree(ArrayRef<Value *> VL);
2031 
2032   /// Create a new vector from a list of scalar values.  Produces a sequence
2033   /// which exploits values reused across lanes, and arranges the inserts
2034   /// for ease of later optimization.
2035   Value *createBuildVector(ArrayRef<Value *> VL);
2036 
2037   /// \returns the scalarization cost for this type. Scalarization in this
2038   /// context means the creation of vectors from a group of scalars. If \p
2039   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2040   /// vector elements.
2041   InstructionCost getGatherCost(FixedVectorType *Ty,
2042                                 const APInt &ShuffledIndices,
2043                                 bool NeedToShuffle) const;
2044 
2045   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2046   /// tree entries.
2047   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2048   /// previous tree entries. \p Mask is filled with the shuffle mask.
2049   Optional<TargetTransformInfo::ShuffleKind>
2050   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2051                         SmallVectorImpl<const TreeEntry *> &Entries);
2052 
2053   /// \returns the scalarization cost for this list of values. Assuming that
2054   /// this subtree gets vectorized, we may need to extract the values from the
2055   /// roots. This method calculates the cost of extracting the values.
2056   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2057 
2058   /// Set the Builder insert point to one after the last instruction in
2059   /// the bundle
2060   void setInsertPointAfterBundle(const TreeEntry *E);
2061 
2062   /// \returns a vector from a collection of scalars in \p VL.
2063   Value *gather(ArrayRef<Value *> VL);
2064 
2065   /// \returns whether the VectorizableTree is fully vectorizable and will
2066   /// be beneficial even the tree height is tiny.
2067   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2068 
2069   /// Reorder commutative or alt operands to get better probability of
2070   /// generating vectorized code.
2071   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2072                                              SmallVectorImpl<Value *> &Left,
2073                                              SmallVectorImpl<Value *> &Right,
2074                                              const DataLayout &DL,
2075                                              ScalarEvolution &SE,
2076                                              const BoUpSLP &R);
2077   struct TreeEntry {
2078     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2079     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2080 
2081     /// \returns true if the scalars in VL are equal to this entry.
2082     bool isSame(ArrayRef<Value *> VL) const {
2083       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2084         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2085           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2086         return VL.size() == Mask.size() &&
2087                std::equal(VL.begin(), VL.end(), Mask.begin(),
2088                           [Scalars](Value *V, int Idx) {
2089                             return (isa<UndefValue>(V) &&
2090                                     Idx == UndefMaskElem) ||
2091                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2092                           });
2093       };
2094       if (!ReorderIndices.empty()) {
2095         // TODO: implement matching if the nodes are just reordered, still can
2096         // treat the vector as the same if the list of scalars matches VL
2097         // directly, without reordering.
2098         SmallVector<int> Mask;
2099         inversePermutation(ReorderIndices, Mask);
2100         if (VL.size() == Scalars.size())
2101           return IsSame(Scalars, Mask);
2102         if (VL.size() == ReuseShuffleIndices.size()) {
2103           ::addMask(Mask, ReuseShuffleIndices);
2104           return IsSame(Scalars, Mask);
2105         }
2106         return false;
2107       }
2108       return IsSame(Scalars, ReuseShuffleIndices);
2109     }
2110 
2111     /// \returns true if current entry has same operands as \p TE.
2112     bool hasEqualOperands(const TreeEntry &TE) const {
2113       if (TE.getNumOperands() != getNumOperands())
2114         return false;
2115       SmallBitVector Used(getNumOperands());
2116       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2117         unsigned PrevCount = Used.count();
2118         for (unsigned K = 0; K < E; ++K) {
2119           if (Used.test(K))
2120             continue;
2121           if (getOperand(K) == TE.getOperand(I)) {
2122             Used.set(K);
2123             break;
2124           }
2125         }
2126         // Check if we actually found the matching operand.
2127         if (PrevCount == Used.count())
2128           return false;
2129       }
2130       return true;
2131     }
2132 
2133     /// \return Final vectorization factor for the node. Defined by the total
2134     /// number of vectorized scalars, including those, used several times in the
2135     /// entry and counted in the \a ReuseShuffleIndices, if any.
2136     unsigned getVectorFactor() const {
2137       if (!ReuseShuffleIndices.empty())
2138         return ReuseShuffleIndices.size();
2139       return Scalars.size();
2140     };
2141 
2142     /// A vector of scalars.
2143     ValueList Scalars;
2144 
2145     /// The Scalars are vectorized into this value. It is initialized to Null.
2146     Value *VectorizedValue = nullptr;
2147 
2148     /// Do we need to gather this sequence or vectorize it
2149     /// (either with vector instruction or with scatter/gather
2150     /// intrinsics for store/load)?
2151     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2152     EntryState State;
2153 
2154     /// Does this sequence require some shuffling?
2155     SmallVector<int, 4> ReuseShuffleIndices;
2156 
2157     /// Does this entry require reordering?
2158     SmallVector<unsigned, 4> ReorderIndices;
2159 
2160     /// Points back to the VectorizableTree.
2161     ///
2162     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2163     /// to be a pointer and needs to be able to initialize the child iterator.
2164     /// Thus we need a reference back to the container to translate the indices
2165     /// to entries.
2166     VecTreeTy &Container;
2167 
2168     /// The TreeEntry index containing the user of this entry.  We can actually
2169     /// have multiple users so the data structure is not truly a tree.
2170     SmallVector<EdgeInfo, 1> UserTreeIndices;
2171 
2172     /// The index of this treeEntry in VectorizableTree.
2173     int Idx = -1;
2174 
2175   private:
2176     /// The operands of each instruction in each lane Operands[op_index][lane].
2177     /// Note: This helps avoid the replication of the code that performs the
2178     /// reordering of operands during buildTree_rec() and vectorizeTree().
2179     SmallVector<ValueList, 2> Operands;
2180 
2181     /// The main/alternate instruction.
2182     Instruction *MainOp = nullptr;
2183     Instruction *AltOp = nullptr;
2184 
2185   public:
2186     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2187     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2188       if (Operands.size() < OpIdx + 1)
2189         Operands.resize(OpIdx + 1);
2190       assert(Operands[OpIdx].empty() && "Already resized?");
2191       assert(OpVL.size() <= Scalars.size() &&
2192              "Number of operands is greater than the number of scalars.");
2193       Operands[OpIdx].resize(OpVL.size());
2194       copy(OpVL, Operands[OpIdx].begin());
2195     }
2196 
2197     /// Set the operands of this bundle in their original order.
2198     void setOperandsInOrder() {
2199       assert(Operands.empty() && "Already initialized?");
2200       auto *I0 = cast<Instruction>(Scalars[0]);
2201       Operands.resize(I0->getNumOperands());
2202       unsigned NumLanes = Scalars.size();
2203       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2204            OpIdx != NumOperands; ++OpIdx) {
2205         Operands[OpIdx].resize(NumLanes);
2206         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2207           auto *I = cast<Instruction>(Scalars[Lane]);
2208           assert(I->getNumOperands() == NumOperands &&
2209                  "Expected same number of operands");
2210           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2211         }
2212       }
2213     }
2214 
2215     /// Reorders operands of the node to the given mask \p Mask.
2216     void reorderOperands(ArrayRef<int> Mask) {
2217       for (ValueList &Operand : Operands)
2218         reorderScalars(Operand, Mask);
2219     }
2220 
2221     /// \returns the \p OpIdx operand of this TreeEntry.
2222     ValueList &getOperand(unsigned OpIdx) {
2223       assert(OpIdx < Operands.size() && "Off bounds");
2224       return Operands[OpIdx];
2225     }
2226 
2227     /// \returns the \p OpIdx operand of this TreeEntry.
2228     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2229       assert(OpIdx < Operands.size() && "Off bounds");
2230       return Operands[OpIdx];
2231     }
2232 
2233     /// \returns the number of operands.
2234     unsigned getNumOperands() const { return Operands.size(); }
2235 
2236     /// \return the single \p OpIdx operand.
2237     Value *getSingleOperand(unsigned OpIdx) const {
2238       assert(OpIdx < Operands.size() && "Off bounds");
2239       assert(!Operands[OpIdx].empty() && "No operand available");
2240       return Operands[OpIdx][0];
2241     }
2242 
2243     /// Some of the instructions in the list have alternate opcodes.
2244     bool isAltShuffle() const { return MainOp != AltOp; }
2245 
2246     bool isOpcodeOrAlt(Instruction *I) const {
2247       unsigned CheckedOpcode = I->getOpcode();
2248       return (getOpcode() == CheckedOpcode ||
2249               getAltOpcode() == CheckedOpcode);
2250     }
2251 
2252     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2253     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2254     /// \p OpValue.
2255     Value *isOneOf(Value *Op) const {
2256       auto *I = dyn_cast<Instruction>(Op);
2257       if (I && isOpcodeOrAlt(I))
2258         return Op;
2259       return MainOp;
2260     }
2261 
2262     void setOperations(const InstructionsState &S) {
2263       MainOp = S.MainOp;
2264       AltOp = S.AltOp;
2265     }
2266 
2267     Instruction *getMainOp() const {
2268       return MainOp;
2269     }
2270 
2271     Instruction *getAltOp() const {
2272       return AltOp;
2273     }
2274 
2275     /// The main/alternate opcodes for the list of instructions.
2276     unsigned getOpcode() const {
2277       return MainOp ? MainOp->getOpcode() : 0;
2278     }
2279 
2280     unsigned getAltOpcode() const {
2281       return AltOp ? AltOp->getOpcode() : 0;
2282     }
2283 
2284     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2285     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2286     int findLaneForValue(Value *V) const {
2287       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2288       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2289       if (!ReorderIndices.empty())
2290         FoundLane = ReorderIndices[FoundLane];
2291       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2292       if (!ReuseShuffleIndices.empty()) {
2293         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2294                                   find(ReuseShuffleIndices, FoundLane));
2295       }
2296       return FoundLane;
2297     }
2298 
2299 #ifndef NDEBUG
2300     /// Debug printer.
2301     LLVM_DUMP_METHOD void dump() const {
2302       dbgs() << Idx << ".\n";
2303       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2304         dbgs() << "Operand " << OpI << ":\n";
2305         for (const Value *V : Operands[OpI])
2306           dbgs().indent(2) << *V << "\n";
2307       }
2308       dbgs() << "Scalars: \n";
2309       for (Value *V : Scalars)
2310         dbgs().indent(2) << *V << "\n";
2311       dbgs() << "State: ";
2312       switch (State) {
2313       case Vectorize:
2314         dbgs() << "Vectorize\n";
2315         break;
2316       case ScatterVectorize:
2317         dbgs() << "ScatterVectorize\n";
2318         break;
2319       case NeedToGather:
2320         dbgs() << "NeedToGather\n";
2321         break;
2322       }
2323       dbgs() << "MainOp: ";
2324       if (MainOp)
2325         dbgs() << *MainOp << "\n";
2326       else
2327         dbgs() << "NULL\n";
2328       dbgs() << "AltOp: ";
2329       if (AltOp)
2330         dbgs() << *AltOp << "\n";
2331       else
2332         dbgs() << "NULL\n";
2333       dbgs() << "VectorizedValue: ";
2334       if (VectorizedValue)
2335         dbgs() << *VectorizedValue << "\n";
2336       else
2337         dbgs() << "NULL\n";
2338       dbgs() << "ReuseShuffleIndices: ";
2339       if (ReuseShuffleIndices.empty())
2340         dbgs() << "Empty";
2341       else
2342         for (int ReuseIdx : ReuseShuffleIndices)
2343           dbgs() << ReuseIdx << ", ";
2344       dbgs() << "\n";
2345       dbgs() << "ReorderIndices: ";
2346       for (unsigned ReorderIdx : ReorderIndices)
2347         dbgs() << ReorderIdx << ", ";
2348       dbgs() << "\n";
2349       dbgs() << "UserTreeIndices: ";
2350       for (const auto &EInfo : UserTreeIndices)
2351         dbgs() << EInfo << ", ";
2352       dbgs() << "\n";
2353     }
2354 #endif
2355   };
2356 
2357 #ifndef NDEBUG
2358   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2359                      InstructionCost VecCost,
2360                      InstructionCost ScalarCost) const {
2361     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2362     dbgs() << "SLP: Costs:\n";
2363     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2364     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2365     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2366     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2367                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2368   }
2369 #endif
2370 
2371   /// Create a new VectorizableTree entry.
2372   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2373                           const InstructionsState &S,
2374                           const EdgeInfo &UserTreeIdx,
2375                           ArrayRef<int> ReuseShuffleIndices = None,
2376                           ArrayRef<unsigned> ReorderIndices = None) {
2377     TreeEntry::EntryState EntryState =
2378         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2379     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2380                         ReuseShuffleIndices, ReorderIndices);
2381   }
2382 
2383   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2384                           TreeEntry::EntryState EntryState,
2385                           Optional<ScheduleData *> Bundle,
2386                           const InstructionsState &S,
2387                           const EdgeInfo &UserTreeIdx,
2388                           ArrayRef<int> ReuseShuffleIndices = None,
2389                           ArrayRef<unsigned> ReorderIndices = None) {
2390     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2391             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2392            "Need to vectorize gather entry?");
2393     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2394     TreeEntry *Last = VectorizableTree.back().get();
2395     Last->Idx = VectorizableTree.size() - 1;
2396     Last->State = EntryState;
2397     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2398                                      ReuseShuffleIndices.end());
2399     if (ReorderIndices.empty()) {
2400       Last->Scalars.assign(VL.begin(), VL.end());
2401       Last->setOperations(S);
2402     } else {
2403       // Reorder scalars and build final mask.
2404       Last->Scalars.assign(VL.size(), nullptr);
2405       transform(ReorderIndices, Last->Scalars.begin(),
2406                 [VL](unsigned Idx) -> Value * {
2407                   if (Idx >= VL.size())
2408                     return UndefValue::get(VL.front()->getType());
2409                   return VL[Idx];
2410                 });
2411       InstructionsState S = getSameOpcode(Last->Scalars);
2412       Last->setOperations(S);
2413       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2414     }
2415     if (Last->State != TreeEntry::NeedToGather) {
2416       for (Value *V : VL) {
2417         assert(!getTreeEntry(V) && "Scalar already in tree!");
2418         ScalarToTreeEntry[V] = Last;
2419       }
2420       // Update the scheduler bundle to point to this TreeEntry.
2421       ScheduleData *BundleMember = Bundle.getValue();
2422       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2423               isVectorLikeInstWithConstOps(S.MainOp) ||
2424               doesNotNeedToSchedule(VL)) &&
2425              "Bundle and VL out of sync");
2426       if (BundleMember) {
2427         for (Value *V : VL) {
2428           if (doesNotNeedToBeScheduled(V))
2429             continue;
2430           assert(BundleMember && "Unexpected end of bundle.");
2431           BundleMember->TE = Last;
2432           BundleMember = BundleMember->NextInBundle;
2433         }
2434       }
2435       assert(!BundleMember && "Bundle and VL out of sync");
2436     } else {
2437       MustGather.insert(VL.begin(), VL.end());
2438     }
2439 
2440     if (UserTreeIdx.UserTE)
2441       Last->UserTreeIndices.push_back(UserTreeIdx);
2442 
2443     return Last;
2444   }
2445 
2446   /// -- Vectorization State --
2447   /// Holds all of the tree entries.
2448   TreeEntry::VecTreeTy VectorizableTree;
2449 
2450 #ifndef NDEBUG
2451   /// Debug printer.
2452   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2453     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2454       VectorizableTree[Id]->dump();
2455       dbgs() << "\n";
2456     }
2457   }
2458 #endif
2459 
2460   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2461 
2462   const TreeEntry *getTreeEntry(Value *V) const {
2463     return ScalarToTreeEntry.lookup(V);
2464   }
2465 
2466   /// Maps a specific scalar to its tree entry.
2467   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2468 
2469   /// Maps a value to the proposed vectorizable size.
2470   SmallDenseMap<Value *, unsigned> InstrElementSize;
2471 
2472   /// A list of scalars that we found that we need to keep as scalars.
2473   ValueSet MustGather;
2474 
2475   /// This POD struct describes one external user in the vectorized tree.
2476   struct ExternalUser {
2477     ExternalUser(Value *S, llvm::User *U, int L)
2478         : Scalar(S), User(U), Lane(L) {}
2479 
2480     // Which scalar in our function.
2481     Value *Scalar;
2482 
2483     // Which user that uses the scalar.
2484     llvm::User *User;
2485 
2486     // Which lane does the scalar belong to.
2487     int Lane;
2488   };
2489   using UserList = SmallVector<ExternalUser, 16>;
2490 
2491   /// Checks if two instructions may access the same memory.
2492   ///
2493   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2494   /// is invariant in the calling loop.
2495   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2496                  Instruction *Inst2) {
2497     // First check if the result is already in the cache.
2498     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2499     Optional<bool> &result = AliasCache[key];
2500     if (result.hasValue()) {
2501       return result.getValue();
2502     }
2503     bool aliased = true;
2504     if (Loc1.Ptr && isSimple(Inst1))
2505       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2506     // Store the result in the cache.
2507     result = aliased;
2508     return aliased;
2509   }
2510 
2511   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2512 
2513   /// Cache for alias results.
2514   /// TODO: consider moving this to the AliasAnalysis itself.
2515   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2516 
2517   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2518   // globally through SLP because we don't perform any action which
2519   // invalidates capture results.
2520   BatchAAResults BatchAA;
2521 
2522   /// Removes an instruction from its block and eventually deletes it.
2523   /// It's like Instruction::eraseFromParent() except that the actual deletion
2524   /// is delayed until BoUpSLP is destructed.
2525   /// This is required to ensure that there are no incorrect collisions in the
2526   /// AliasCache, which can happen if a new instruction is allocated at the
2527   /// same address as a previously deleted instruction.
2528   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2529     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2530     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2531   }
2532 
2533   /// Temporary store for deleted instructions. Instructions will be deleted
2534   /// eventually when the BoUpSLP is destructed.
2535   DenseMap<Instruction *, bool> DeletedInstructions;
2536 
2537   /// A list of values that need to extracted out of the tree.
2538   /// This list holds pairs of (Internal Scalar : External User). External User
2539   /// can be nullptr, it means that this Internal Scalar will be used later,
2540   /// after vectorization.
2541   UserList ExternalUses;
2542 
2543   /// Values used only by @llvm.assume calls.
2544   SmallPtrSet<const Value *, 32> EphValues;
2545 
2546   /// Holds all of the instructions that we gathered.
2547   SetVector<Instruction *> GatherShuffleSeq;
2548 
2549   /// A list of blocks that we are going to CSE.
2550   SetVector<BasicBlock *> CSEBlocks;
2551 
2552   /// Contains all scheduling relevant data for an instruction.
2553   /// A ScheduleData either represents a single instruction or a member of an
2554   /// instruction bundle (= a group of instructions which is combined into a
2555   /// vector instruction).
2556   struct ScheduleData {
2557     // The initial value for the dependency counters. It means that the
2558     // dependencies are not calculated yet.
2559     enum { InvalidDeps = -1 };
2560 
2561     ScheduleData() = default;
2562 
2563     void init(int BlockSchedulingRegionID, Value *OpVal) {
2564       FirstInBundle = this;
2565       NextInBundle = nullptr;
2566       NextLoadStore = nullptr;
2567       IsScheduled = false;
2568       SchedulingRegionID = BlockSchedulingRegionID;
2569       clearDependencies();
2570       OpValue = OpVal;
2571       TE = nullptr;
2572     }
2573 
2574     /// Verify basic self consistency properties
2575     void verify() {
2576       if (hasValidDependencies()) {
2577         assert(UnscheduledDeps <= Dependencies && "invariant");
2578       } else {
2579         assert(UnscheduledDeps == Dependencies && "invariant");
2580       }
2581 
2582       if (IsScheduled) {
2583         assert(isSchedulingEntity() &&
2584                 "unexpected scheduled state");
2585         for (const ScheduleData *BundleMember = this; BundleMember;
2586              BundleMember = BundleMember->NextInBundle) {
2587           assert(BundleMember->hasValidDependencies() &&
2588                  BundleMember->UnscheduledDeps == 0 &&
2589                  "unexpected scheduled state");
2590           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2591                  "only bundle is marked scheduled");
2592         }
2593       }
2594 
2595       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2596              "all bundle members must be in same basic block");
2597     }
2598 
2599     /// Returns true if the dependency information has been calculated.
2600     /// Note that depenendency validity can vary between instructions within
2601     /// a single bundle.
2602     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2603 
2604     /// Returns true for single instructions and for bundle representatives
2605     /// (= the head of a bundle).
2606     bool isSchedulingEntity() const { return FirstInBundle == this; }
2607 
2608     /// Returns true if it represents an instruction bundle and not only a
2609     /// single instruction.
2610     bool isPartOfBundle() const {
2611       return NextInBundle != nullptr || FirstInBundle != this || TE;
2612     }
2613 
2614     /// Returns true if it is ready for scheduling, i.e. it has no more
2615     /// unscheduled depending instructions/bundles.
2616     bool isReady() const {
2617       assert(isSchedulingEntity() &&
2618              "can't consider non-scheduling entity for ready list");
2619       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2620     }
2621 
2622     /// Modifies the number of unscheduled dependencies for this instruction,
2623     /// and returns the number of remaining dependencies for the containing
2624     /// bundle.
2625     int incrementUnscheduledDeps(int Incr) {
2626       assert(hasValidDependencies() &&
2627              "increment of unscheduled deps would be meaningless");
2628       UnscheduledDeps += Incr;
2629       return FirstInBundle->unscheduledDepsInBundle();
2630     }
2631 
2632     /// Sets the number of unscheduled dependencies to the number of
2633     /// dependencies.
2634     void resetUnscheduledDeps() {
2635       UnscheduledDeps = Dependencies;
2636     }
2637 
2638     /// Clears all dependency information.
2639     void clearDependencies() {
2640       Dependencies = InvalidDeps;
2641       resetUnscheduledDeps();
2642       MemoryDependencies.clear();
2643       ControlDependencies.clear();
2644     }
2645 
2646     int unscheduledDepsInBundle() const {
2647       assert(isSchedulingEntity() && "only meaningful on the bundle");
2648       int Sum = 0;
2649       for (const ScheduleData *BundleMember = this; BundleMember;
2650            BundleMember = BundleMember->NextInBundle) {
2651         if (BundleMember->UnscheduledDeps == InvalidDeps)
2652           return InvalidDeps;
2653         Sum += BundleMember->UnscheduledDeps;
2654       }
2655       return Sum;
2656     }
2657 
2658     void dump(raw_ostream &os) const {
2659       if (!isSchedulingEntity()) {
2660         os << "/ " << *Inst;
2661       } else if (NextInBundle) {
2662         os << '[' << *Inst;
2663         ScheduleData *SD = NextInBundle;
2664         while (SD) {
2665           os << ';' << *SD->Inst;
2666           SD = SD->NextInBundle;
2667         }
2668         os << ']';
2669       } else {
2670         os << *Inst;
2671       }
2672     }
2673 
2674     Instruction *Inst = nullptr;
2675 
2676     /// Opcode of the current instruction in the schedule data.
2677     Value *OpValue = nullptr;
2678 
2679     /// The TreeEntry that this instruction corresponds to.
2680     TreeEntry *TE = nullptr;
2681 
2682     /// Points to the head in an instruction bundle (and always to this for
2683     /// single instructions).
2684     ScheduleData *FirstInBundle = nullptr;
2685 
2686     /// Single linked list of all instructions in a bundle. Null if it is a
2687     /// single instruction.
2688     ScheduleData *NextInBundle = nullptr;
2689 
2690     /// Single linked list of all memory instructions (e.g. load, store, call)
2691     /// in the block - until the end of the scheduling region.
2692     ScheduleData *NextLoadStore = nullptr;
2693 
2694     /// The dependent memory instructions.
2695     /// This list is derived on demand in calculateDependencies().
2696     SmallVector<ScheduleData *, 4> MemoryDependencies;
2697 
2698     /// List of instructions which this instruction could be control dependent
2699     /// on.  Allowing such nodes to be scheduled below this one could introduce
2700     /// a runtime fault which didn't exist in the original program.
2701     /// ex: this is a load or udiv following a readonly call which inf loops
2702     SmallVector<ScheduleData *, 4> ControlDependencies;
2703 
2704     /// This ScheduleData is in the current scheduling region if this matches
2705     /// the current SchedulingRegionID of BlockScheduling.
2706     int SchedulingRegionID = 0;
2707 
2708     /// Used for getting a "good" final ordering of instructions.
2709     int SchedulingPriority = 0;
2710 
2711     /// The number of dependencies. Constitutes of the number of users of the
2712     /// instruction plus the number of dependent memory instructions (if any).
2713     /// This value is calculated on demand.
2714     /// If InvalidDeps, the number of dependencies is not calculated yet.
2715     int Dependencies = InvalidDeps;
2716 
2717     /// The number of dependencies minus the number of dependencies of scheduled
2718     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2719     /// for scheduling.
2720     /// Note that this is negative as long as Dependencies is not calculated.
2721     int UnscheduledDeps = InvalidDeps;
2722 
2723     /// True if this instruction is scheduled (or considered as scheduled in the
2724     /// dry-run).
2725     bool IsScheduled = false;
2726   };
2727 
2728 #ifndef NDEBUG
2729   friend inline raw_ostream &operator<<(raw_ostream &os,
2730                                         const BoUpSLP::ScheduleData &SD) {
2731     SD.dump(os);
2732     return os;
2733   }
2734 #endif
2735 
2736   friend struct GraphTraits<BoUpSLP *>;
2737   friend struct DOTGraphTraits<BoUpSLP *>;
2738 
2739   /// Contains all scheduling data for a basic block.
2740   /// It does not schedules instructions, which are not memory read/write
2741   /// instructions and their operands are either constants, or arguments, or
2742   /// phis, or instructions from others blocks, or their users are phis or from
2743   /// the other blocks. The resulting vector instructions can be placed at the
2744   /// beginning of the basic block without scheduling (if operands does not need
2745   /// to be scheduled) or at the end of the block (if users are outside of the
2746   /// block). It allows to save some compile time and memory used by the
2747   /// compiler.
2748   /// ScheduleData is assigned for each instruction in between the boundaries of
2749   /// the tree entry, even for those, which are not part of the graph. It is
2750   /// required to correctly follow the dependencies between the instructions and
2751   /// their correct scheduling. The ScheduleData is not allocated for the
2752   /// instructions, which do not require scheduling, like phis, nodes with
2753   /// extractelements/insertelements only or nodes with instructions, with
2754   /// uses/operands outside of the block.
2755   struct BlockScheduling {
2756     BlockScheduling(BasicBlock *BB)
2757         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2758 
2759     void clear() {
2760       ReadyInsts.clear();
2761       ScheduleStart = nullptr;
2762       ScheduleEnd = nullptr;
2763       FirstLoadStoreInRegion = nullptr;
2764       LastLoadStoreInRegion = nullptr;
2765 
2766       // Reduce the maximum schedule region size by the size of the
2767       // previous scheduling run.
2768       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2769       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2770         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2771       ScheduleRegionSize = 0;
2772 
2773       // Make a new scheduling region, i.e. all existing ScheduleData is not
2774       // in the new region yet.
2775       ++SchedulingRegionID;
2776     }
2777 
2778     ScheduleData *getScheduleData(Instruction *I) {
2779       if (BB != I->getParent())
2780         // Avoid lookup if can't possibly be in map.
2781         return nullptr;
2782       ScheduleData *SD = ScheduleDataMap.lookup(I);
2783       if (SD && isInSchedulingRegion(SD))
2784         return SD;
2785       return nullptr;
2786     }
2787 
2788     ScheduleData *getScheduleData(Value *V) {
2789       if (auto *I = dyn_cast<Instruction>(V))
2790         return getScheduleData(I);
2791       return nullptr;
2792     }
2793 
2794     ScheduleData *getScheduleData(Value *V, Value *Key) {
2795       if (V == Key)
2796         return getScheduleData(V);
2797       auto I = ExtraScheduleDataMap.find(V);
2798       if (I != ExtraScheduleDataMap.end()) {
2799         ScheduleData *SD = I->second.lookup(Key);
2800         if (SD && isInSchedulingRegion(SD))
2801           return SD;
2802       }
2803       return nullptr;
2804     }
2805 
2806     bool isInSchedulingRegion(ScheduleData *SD) const {
2807       return SD->SchedulingRegionID == SchedulingRegionID;
2808     }
2809 
2810     /// Marks an instruction as scheduled and puts all dependent ready
2811     /// instructions into the ready-list.
2812     template <typename ReadyListType>
2813     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2814       SD->IsScheduled = true;
2815       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2816 
2817       for (ScheduleData *BundleMember = SD; BundleMember;
2818            BundleMember = BundleMember->NextInBundle) {
2819         if (BundleMember->Inst != BundleMember->OpValue)
2820           continue;
2821 
2822         // Handle the def-use chain dependencies.
2823 
2824         // Decrement the unscheduled counter and insert to ready list if ready.
2825         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2826           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2827             if (OpDef && OpDef->hasValidDependencies() &&
2828                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2829               // There are no more unscheduled dependencies after
2830               // decrementing, so we can put the dependent instruction
2831               // into the ready list.
2832               ScheduleData *DepBundle = OpDef->FirstInBundle;
2833               assert(!DepBundle->IsScheduled &&
2834                      "already scheduled bundle gets ready");
2835               ReadyList.insert(DepBundle);
2836               LLVM_DEBUG(dbgs()
2837                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2838             }
2839           });
2840         };
2841 
2842         // If BundleMember is a vector bundle, its operands may have been
2843         // reordered during buildTree(). We therefore need to get its operands
2844         // through the TreeEntry.
2845         if (TreeEntry *TE = BundleMember->TE) {
2846           // Need to search for the lane since the tree entry can be reordered.
2847           int Lane = std::distance(TE->Scalars.begin(),
2848                                    find(TE->Scalars, BundleMember->Inst));
2849           assert(Lane >= 0 && "Lane not set");
2850 
2851           // Since vectorization tree is being built recursively this assertion
2852           // ensures that the tree entry has all operands set before reaching
2853           // this code. Couple of exceptions known at the moment are extracts
2854           // where their second (immediate) operand is not added. Since
2855           // immediates do not affect scheduler behavior this is considered
2856           // okay.
2857           auto *In = BundleMember->Inst;
2858           assert(In &&
2859                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2860                   In->getNumOperands() == TE->getNumOperands()) &&
2861                  "Missed TreeEntry operands?");
2862           (void)In; // fake use to avoid build failure when assertions disabled
2863 
2864           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2865                OpIdx != NumOperands; ++OpIdx)
2866             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2867               DecrUnsched(I);
2868         } else {
2869           // If BundleMember is a stand-alone instruction, no operand reordering
2870           // has taken place, so we directly access its operands.
2871           for (Use &U : BundleMember->Inst->operands())
2872             if (auto *I = dyn_cast<Instruction>(U.get()))
2873               DecrUnsched(I);
2874         }
2875         // Handle the memory dependencies.
2876         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2877           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2878             // There are no more unscheduled dependencies after decrementing,
2879             // so we can put the dependent instruction into the ready list.
2880             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2881             assert(!DepBundle->IsScheduled &&
2882                    "already scheduled bundle gets ready");
2883             ReadyList.insert(DepBundle);
2884             LLVM_DEBUG(dbgs()
2885                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2886           }
2887         }
2888         // Handle the control dependencies.
2889         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2890           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2891             // There are no more unscheduled dependencies after decrementing,
2892             // so we can put the dependent instruction into the ready list.
2893             ScheduleData *DepBundle = DepSD->FirstInBundle;
2894             assert(!DepBundle->IsScheduled &&
2895                    "already scheduled bundle gets ready");
2896             ReadyList.insert(DepBundle);
2897             LLVM_DEBUG(dbgs()
2898                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2899           }
2900         }
2901 
2902       }
2903     }
2904 
2905     /// Verify basic self consistency properties of the data structure.
2906     void verify() {
2907       if (!ScheduleStart)
2908         return;
2909 
2910       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2911              ScheduleStart->comesBefore(ScheduleEnd) &&
2912              "Not a valid scheduling region?");
2913 
2914       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2915         auto *SD = getScheduleData(I);
2916         if (!SD)
2917           continue;
2918         assert(isInSchedulingRegion(SD) &&
2919                "primary schedule data not in window?");
2920         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2921                "entire bundle in window!");
2922         (void)SD;
2923         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2924       }
2925 
2926       for (auto *SD : ReadyInsts) {
2927         assert(SD->isSchedulingEntity() && SD->isReady() &&
2928                "item in ready list not ready?");
2929         (void)SD;
2930       }
2931     }
2932 
2933     void doForAllOpcodes(Value *V,
2934                          function_ref<void(ScheduleData *SD)> Action) {
2935       if (ScheduleData *SD = getScheduleData(V))
2936         Action(SD);
2937       auto I = ExtraScheduleDataMap.find(V);
2938       if (I != ExtraScheduleDataMap.end())
2939         for (auto &P : I->second)
2940           if (isInSchedulingRegion(P.second))
2941             Action(P.second);
2942     }
2943 
2944     /// Put all instructions into the ReadyList which are ready for scheduling.
2945     template <typename ReadyListType>
2946     void initialFillReadyList(ReadyListType &ReadyList) {
2947       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2948         doForAllOpcodes(I, [&](ScheduleData *SD) {
2949           if (SD->isSchedulingEntity() && SD->isReady()) {
2950             ReadyList.insert(SD);
2951             LLVM_DEBUG(dbgs()
2952                        << "SLP:    initially in ready list: " << *SD << "\n");
2953           }
2954         });
2955       }
2956     }
2957 
2958     /// Build a bundle from the ScheduleData nodes corresponding to the
2959     /// scalar instruction for each lane.
2960     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2961 
2962     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2963     /// cyclic dependencies. This is only a dry-run, no instructions are
2964     /// actually moved at this stage.
2965     /// \returns the scheduling bundle. The returned Optional value is non-None
2966     /// if \p VL is allowed to be scheduled.
2967     Optional<ScheduleData *>
2968     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2969                       const InstructionsState &S);
2970 
2971     /// Un-bundles a group of instructions.
2972     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2973 
2974     /// Allocates schedule data chunk.
2975     ScheduleData *allocateScheduleDataChunks();
2976 
2977     /// Extends the scheduling region so that V is inside the region.
2978     /// \returns true if the region size is within the limit.
2979     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2980 
2981     /// Initialize the ScheduleData structures for new instructions in the
2982     /// scheduling region.
2983     void initScheduleData(Instruction *FromI, Instruction *ToI,
2984                           ScheduleData *PrevLoadStore,
2985                           ScheduleData *NextLoadStore);
2986 
2987     /// Updates the dependency information of a bundle and of all instructions/
2988     /// bundles which depend on the original bundle.
2989     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2990                                BoUpSLP *SLP);
2991 
2992     /// Sets all instruction in the scheduling region to un-scheduled.
2993     void resetSchedule();
2994 
2995     BasicBlock *BB;
2996 
2997     /// Simple memory allocation for ScheduleData.
2998     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2999 
3000     /// The size of a ScheduleData array in ScheduleDataChunks.
3001     int ChunkSize;
3002 
3003     /// The allocator position in the current chunk, which is the last entry
3004     /// of ScheduleDataChunks.
3005     int ChunkPos;
3006 
3007     /// Attaches ScheduleData to Instruction.
3008     /// Note that the mapping survives during all vectorization iterations, i.e.
3009     /// ScheduleData structures are recycled.
3010     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3011 
3012     /// Attaches ScheduleData to Instruction with the leading key.
3013     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3014         ExtraScheduleDataMap;
3015 
3016     /// The ready-list for scheduling (only used for the dry-run).
3017     SetVector<ScheduleData *> ReadyInsts;
3018 
3019     /// The first instruction of the scheduling region.
3020     Instruction *ScheduleStart = nullptr;
3021 
3022     /// The first instruction _after_ the scheduling region.
3023     Instruction *ScheduleEnd = nullptr;
3024 
3025     /// The first memory accessing instruction in the scheduling region
3026     /// (can be null).
3027     ScheduleData *FirstLoadStoreInRegion = nullptr;
3028 
3029     /// The last memory accessing instruction in the scheduling region
3030     /// (can be null).
3031     ScheduleData *LastLoadStoreInRegion = nullptr;
3032 
3033     /// The current size of the scheduling region.
3034     int ScheduleRegionSize = 0;
3035 
3036     /// The maximum size allowed for the scheduling region.
3037     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3038 
3039     /// The ID of the scheduling region. For a new vectorization iteration this
3040     /// is incremented which "removes" all ScheduleData from the region.
3041     /// Make sure that the initial SchedulingRegionID is greater than the
3042     /// initial SchedulingRegionID in ScheduleData (which is 0).
3043     int SchedulingRegionID = 1;
3044   };
3045 
3046   /// Attaches the BlockScheduling structures to basic blocks.
3047   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3048 
3049   /// Performs the "real" scheduling. Done before vectorization is actually
3050   /// performed in a basic block.
3051   void scheduleBlock(BlockScheduling *BS);
3052 
3053   /// List of users to ignore during scheduling and that don't need extracting.
3054   ArrayRef<Value *> UserIgnoreList;
3055 
3056   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3057   /// sorted SmallVectors of unsigned.
3058   struct OrdersTypeDenseMapInfo {
3059     static OrdersType getEmptyKey() {
3060       OrdersType V;
3061       V.push_back(~1U);
3062       return V;
3063     }
3064 
3065     static OrdersType getTombstoneKey() {
3066       OrdersType V;
3067       V.push_back(~2U);
3068       return V;
3069     }
3070 
3071     static unsigned getHashValue(const OrdersType &V) {
3072       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3073     }
3074 
3075     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3076       return LHS == RHS;
3077     }
3078   };
3079 
3080   // Analysis and block reference.
3081   Function *F;
3082   ScalarEvolution *SE;
3083   TargetTransformInfo *TTI;
3084   TargetLibraryInfo *TLI;
3085   LoopInfo *LI;
3086   DominatorTree *DT;
3087   AssumptionCache *AC;
3088   DemandedBits *DB;
3089   const DataLayout *DL;
3090   OptimizationRemarkEmitter *ORE;
3091 
3092   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3093   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3094 
3095   /// Instruction builder to construct the vectorized tree.
3096   IRBuilder<> Builder;
3097 
3098   /// A map of scalar integer values to the smallest bit width with which they
3099   /// can legally be represented. The values map to (width, signed) pairs,
3100   /// where "width" indicates the minimum bit width and "signed" is True if the
3101   /// value must be signed-extended, rather than zero-extended, back to its
3102   /// original width.
3103   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3104 };
3105 
3106 } // end namespace slpvectorizer
3107 
3108 template <> struct GraphTraits<BoUpSLP *> {
3109   using TreeEntry = BoUpSLP::TreeEntry;
3110 
3111   /// NodeRef has to be a pointer per the GraphWriter.
3112   using NodeRef = TreeEntry *;
3113 
3114   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3115 
3116   /// Add the VectorizableTree to the index iterator to be able to return
3117   /// TreeEntry pointers.
3118   struct ChildIteratorType
3119       : public iterator_adaptor_base<
3120             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3121     ContainerTy &VectorizableTree;
3122 
3123     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3124                       ContainerTy &VT)
3125         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3126 
3127     NodeRef operator*() { return I->UserTE; }
3128   };
3129 
3130   static NodeRef getEntryNode(BoUpSLP &R) {
3131     return R.VectorizableTree[0].get();
3132   }
3133 
3134   static ChildIteratorType child_begin(NodeRef N) {
3135     return {N->UserTreeIndices.begin(), N->Container};
3136   }
3137 
3138   static ChildIteratorType child_end(NodeRef N) {
3139     return {N->UserTreeIndices.end(), N->Container};
3140   }
3141 
3142   /// For the node iterator we just need to turn the TreeEntry iterator into a
3143   /// TreeEntry* iterator so that it dereferences to NodeRef.
3144   class nodes_iterator {
3145     using ItTy = ContainerTy::iterator;
3146     ItTy It;
3147 
3148   public:
3149     nodes_iterator(const ItTy &It2) : It(It2) {}
3150     NodeRef operator*() { return It->get(); }
3151     nodes_iterator operator++() {
3152       ++It;
3153       return *this;
3154     }
3155     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3156   };
3157 
3158   static nodes_iterator nodes_begin(BoUpSLP *R) {
3159     return nodes_iterator(R->VectorizableTree.begin());
3160   }
3161 
3162   static nodes_iterator nodes_end(BoUpSLP *R) {
3163     return nodes_iterator(R->VectorizableTree.end());
3164   }
3165 
3166   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3167 };
3168 
3169 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3170   using TreeEntry = BoUpSLP::TreeEntry;
3171 
3172   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3173 
3174   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3175     std::string Str;
3176     raw_string_ostream OS(Str);
3177     if (isSplat(Entry->Scalars))
3178       OS << "<splat> ";
3179     for (auto V : Entry->Scalars) {
3180       OS << *V;
3181       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3182             return EU.Scalar == V;
3183           }))
3184         OS << " <extract>";
3185       OS << "\n";
3186     }
3187     return Str;
3188   }
3189 
3190   static std::string getNodeAttributes(const TreeEntry *Entry,
3191                                        const BoUpSLP *) {
3192     if (Entry->State == TreeEntry::NeedToGather)
3193       return "color=red";
3194     return "";
3195   }
3196 };
3197 
3198 } // end namespace llvm
3199 
3200 BoUpSLP::~BoUpSLP() {
3201   for (const auto &Pair : DeletedInstructions) {
3202     // Replace operands of ignored instructions with Undefs in case if they were
3203     // marked for deletion.
3204     if (Pair.getSecond()) {
3205       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3206       Pair.getFirst()->replaceAllUsesWith(Undef);
3207     }
3208     Pair.getFirst()->dropAllReferences();
3209   }
3210   for (const auto &Pair : DeletedInstructions) {
3211     assert(Pair.getFirst()->use_empty() &&
3212            "trying to erase instruction with users.");
3213     Pair.getFirst()->eraseFromParent();
3214   }
3215 #ifdef EXPENSIVE_CHECKS
3216   // If we could guarantee that this call is not extremely slow, we could
3217   // remove the ifdef limitation (see PR47712).
3218   assert(!verifyFunction(*F, &dbgs()));
3219 #endif
3220 }
3221 
3222 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3223   for (auto *V : AV) {
3224     if (auto *I = dyn_cast<Instruction>(V))
3225       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3226   };
3227 }
3228 
3229 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3230 /// contains original mask for the scalars reused in the node. Procedure
3231 /// transform this mask in accordance with the given \p Mask.
3232 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3233   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3234          "Expected non-empty mask.");
3235   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3236   Prev.swap(Reuses);
3237   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3238     if (Mask[I] != UndefMaskElem)
3239       Reuses[Mask[I]] = Prev[I];
3240 }
3241 
3242 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3243 /// the original order of the scalars. Procedure transforms the provided order
3244 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3245 /// identity order, \p Order is cleared.
3246 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3247   assert(!Mask.empty() && "Expected non-empty mask.");
3248   SmallVector<int> MaskOrder;
3249   if (Order.empty()) {
3250     MaskOrder.resize(Mask.size());
3251     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3252   } else {
3253     inversePermutation(Order, MaskOrder);
3254   }
3255   reorderReuses(MaskOrder, Mask);
3256   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3257     Order.clear();
3258     return;
3259   }
3260   Order.assign(Mask.size(), Mask.size());
3261   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3262     if (MaskOrder[I] != UndefMaskElem)
3263       Order[MaskOrder[I]] = I;
3264   fixupOrderingIndices(Order);
3265 }
3266 
3267 Optional<BoUpSLP::OrdersType>
3268 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3269   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3270   unsigned NumScalars = TE.Scalars.size();
3271   OrdersType CurrentOrder(NumScalars, NumScalars);
3272   SmallVector<int> Positions;
3273   SmallBitVector UsedPositions(NumScalars);
3274   const TreeEntry *STE = nullptr;
3275   // Try to find all gathered scalars that are gets vectorized in other
3276   // vectorize node. Here we can have only one single tree vector node to
3277   // correctly identify order of the gathered scalars.
3278   for (unsigned I = 0; I < NumScalars; ++I) {
3279     Value *V = TE.Scalars[I];
3280     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3281       continue;
3282     if (const auto *LocalSTE = getTreeEntry(V)) {
3283       if (!STE)
3284         STE = LocalSTE;
3285       else if (STE != LocalSTE)
3286         // Take the order only from the single vector node.
3287         return None;
3288       unsigned Lane =
3289           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3290       if (Lane >= NumScalars)
3291         return None;
3292       if (CurrentOrder[Lane] != NumScalars) {
3293         if (Lane != I)
3294           continue;
3295         UsedPositions.reset(CurrentOrder[Lane]);
3296       }
3297       // The partial identity (where only some elements of the gather node are
3298       // in the identity order) is good.
3299       CurrentOrder[Lane] = I;
3300       UsedPositions.set(I);
3301     }
3302   }
3303   // Need to keep the order if we have a vector entry and at least 2 scalars or
3304   // the vectorized entry has just 2 scalars.
3305   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3306     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3307       for (unsigned I = 0; I < NumScalars; ++I)
3308         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3309           return false;
3310       return true;
3311     };
3312     if (IsIdentityOrder(CurrentOrder)) {
3313       CurrentOrder.clear();
3314       return CurrentOrder;
3315     }
3316     auto *It = CurrentOrder.begin();
3317     for (unsigned I = 0; I < NumScalars;) {
3318       if (UsedPositions.test(I)) {
3319         ++I;
3320         continue;
3321       }
3322       if (*It == NumScalars) {
3323         *It = I;
3324         ++I;
3325       }
3326       ++It;
3327     }
3328     return CurrentOrder;
3329   }
3330   return None;
3331 }
3332 
3333 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3334                                                          bool TopToBottom) {
3335   // No need to reorder if need to shuffle reuses, still need to shuffle the
3336   // node.
3337   if (!TE.ReuseShuffleIndices.empty())
3338     return None;
3339   if (TE.State == TreeEntry::Vectorize &&
3340       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3341        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3342       !TE.isAltShuffle())
3343     return TE.ReorderIndices;
3344   if (TE.State == TreeEntry::NeedToGather) {
3345     // TODO: add analysis of other gather nodes with extractelement
3346     // instructions and other values/instructions, not only undefs.
3347     if (((TE.getOpcode() == Instruction::ExtractElement &&
3348           !TE.isAltShuffle()) ||
3349          (all_of(TE.Scalars,
3350                  [](Value *V) {
3351                    return isa<UndefValue, ExtractElementInst>(V);
3352                  }) &&
3353           any_of(TE.Scalars,
3354                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3355         all_of(TE.Scalars,
3356                [](Value *V) {
3357                  auto *EE = dyn_cast<ExtractElementInst>(V);
3358                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3359                }) &&
3360         allSameType(TE.Scalars)) {
3361       // Check that gather of extractelements can be represented as
3362       // just a shuffle of a single vector.
3363       OrdersType CurrentOrder;
3364       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3365       if (Reuse || !CurrentOrder.empty()) {
3366         if (!CurrentOrder.empty())
3367           fixupOrderingIndices(CurrentOrder);
3368         return CurrentOrder;
3369       }
3370     }
3371     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3372       return CurrentOrder;
3373   }
3374   return None;
3375 }
3376 
3377 void BoUpSLP::reorderTopToBottom() {
3378   // Maps VF to the graph nodes.
3379   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3380   // ExtractElement gather nodes which can be vectorized and need to handle
3381   // their ordering.
3382   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3383   // Find all reorderable nodes with the given VF.
3384   // Currently the are vectorized stores,loads,extracts + some gathering of
3385   // extracts.
3386   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3387                                  const std::unique_ptr<TreeEntry> &TE) {
3388     if (Optional<OrdersType> CurrentOrder =
3389             getReorderingData(*TE, /*TopToBottom=*/true)) {
3390       // Do not include ordering for nodes used in the alt opcode vectorization,
3391       // better to reorder them during bottom-to-top stage. If follow the order
3392       // here, it causes reordering of the whole graph though actually it is
3393       // profitable just to reorder the subgraph that starts from the alternate
3394       // opcode vectorization node. Such nodes already end-up with the shuffle
3395       // instruction and it is just enough to change this shuffle rather than
3396       // rotate the scalars for the whole graph.
3397       unsigned Cnt = 0;
3398       const TreeEntry *UserTE = TE.get();
3399       while (UserTE && Cnt < RecursionMaxDepth) {
3400         if (UserTE->UserTreeIndices.size() != 1)
3401           break;
3402         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3403               return EI.UserTE->State == TreeEntry::Vectorize &&
3404                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3405             }))
3406           return;
3407         if (UserTE->UserTreeIndices.empty())
3408           UserTE = nullptr;
3409         else
3410           UserTE = UserTE->UserTreeIndices.back().UserTE;
3411         ++Cnt;
3412       }
3413       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3414       if (TE->State != TreeEntry::Vectorize)
3415         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3416     }
3417   });
3418 
3419   // Reorder the graph nodes according to their vectorization factor.
3420   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3421        VF /= 2) {
3422     auto It = VFToOrderedEntries.find(VF);
3423     if (It == VFToOrderedEntries.end())
3424       continue;
3425     // Try to find the most profitable order. We just are looking for the most
3426     // used order and reorder scalar elements in the nodes according to this
3427     // mostly used order.
3428     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3429     // All operands are reordered and used only in this node - propagate the
3430     // most used order to the user node.
3431     MapVector<OrdersType, unsigned,
3432               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3433         OrdersUses;
3434     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3435     for (const TreeEntry *OpTE : OrderedEntries) {
3436       // No need to reorder this nodes, still need to extend and to use shuffle,
3437       // just need to merge reordering shuffle and the reuse shuffle.
3438       if (!OpTE->ReuseShuffleIndices.empty())
3439         continue;
3440       // Count number of orders uses.
3441       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3442         if (OpTE->State == TreeEntry::NeedToGather)
3443           return GathersToOrders.find(OpTE)->second;
3444         return OpTE->ReorderIndices;
3445       }();
3446       // Stores actually store the mask, not the order, need to invert.
3447       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3448           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3449         SmallVector<int> Mask;
3450         inversePermutation(Order, Mask);
3451         unsigned E = Order.size();
3452         OrdersType CurrentOrder(E, E);
3453         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3454           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3455         });
3456         fixupOrderingIndices(CurrentOrder);
3457         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3458       } else {
3459         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3460       }
3461     }
3462     // Set order of the user node.
3463     if (OrdersUses.empty())
3464       continue;
3465     // Choose the most used order.
3466     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3467     unsigned Cnt = OrdersUses.front().second;
3468     for (const auto &Pair : drop_begin(OrdersUses)) {
3469       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3470         BestOrder = Pair.first;
3471         Cnt = Pair.second;
3472       }
3473     }
3474     // Set order of the user node.
3475     if (BestOrder.empty())
3476       continue;
3477     SmallVector<int> Mask;
3478     inversePermutation(BestOrder, Mask);
3479     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3480     unsigned E = BestOrder.size();
3481     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3482       return I < E ? static_cast<int>(I) : UndefMaskElem;
3483     });
3484     // Do an actual reordering, if profitable.
3485     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3486       // Just do the reordering for the nodes with the given VF.
3487       if (TE->Scalars.size() != VF) {
3488         if (TE->ReuseShuffleIndices.size() == VF) {
3489           // Need to reorder the reuses masks of the operands with smaller VF to
3490           // be able to find the match between the graph nodes and scalar
3491           // operands of the given node during vectorization/cost estimation.
3492           assert(all_of(TE->UserTreeIndices,
3493                         [VF, &TE](const EdgeInfo &EI) {
3494                           return EI.UserTE->Scalars.size() == VF ||
3495                                  EI.UserTE->Scalars.size() ==
3496                                      TE->Scalars.size();
3497                         }) &&
3498                  "All users must be of VF size.");
3499           // Update ordering of the operands with the smaller VF than the given
3500           // one.
3501           reorderReuses(TE->ReuseShuffleIndices, Mask);
3502         }
3503         continue;
3504       }
3505       if (TE->State == TreeEntry::Vectorize &&
3506           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3507               InsertElementInst>(TE->getMainOp()) &&
3508           !TE->isAltShuffle()) {
3509         // Build correct orders for extract{element,value}, loads and
3510         // stores.
3511         reorderOrder(TE->ReorderIndices, Mask);
3512         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3513           TE->reorderOperands(Mask);
3514       } else {
3515         // Reorder the node and its operands.
3516         TE->reorderOperands(Mask);
3517         assert(TE->ReorderIndices.empty() &&
3518                "Expected empty reorder sequence.");
3519         reorderScalars(TE->Scalars, Mask);
3520       }
3521       if (!TE->ReuseShuffleIndices.empty()) {
3522         // Apply reversed order to keep the original ordering of the reused
3523         // elements to avoid extra reorder indices shuffling.
3524         OrdersType CurrentOrder;
3525         reorderOrder(CurrentOrder, MaskOrder);
3526         SmallVector<int> NewReuses;
3527         inversePermutation(CurrentOrder, NewReuses);
3528         addMask(NewReuses, TE->ReuseShuffleIndices);
3529         TE->ReuseShuffleIndices.swap(NewReuses);
3530       }
3531     }
3532   }
3533 }
3534 
3535 bool BoUpSLP::canReorderOperands(
3536     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3537     ArrayRef<TreeEntry *> ReorderableGathers,
3538     SmallVectorImpl<TreeEntry *> &GatherOps) {
3539   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3540     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3541           return OpData.first == I &&
3542                  OpData.second->State == TreeEntry::Vectorize;
3543         }))
3544       continue;
3545     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3546       // Do not reorder if operand node is used by many user nodes.
3547       if (any_of(TE->UserTreeIndices,
3548                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3549         return false;
3550       // Add the node to the list of the ordered nodes with the identity
3551       // order.
3552       Edges.emplace_back(I, TE);
3553       continue;
3554     }
3555     ArrayRef<Value *> VL = UserTE->getOperand(I);
3556     TreeEntry *Gather = nullptr;
3557     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3558           assert(TE->State != TreeEntry::Vectorize &&
3559                  "Only non-vectorized nodes are expected.");
3560           if (TE->isSame(VL)) {
3561             Gather = TE;
3562             return true;
3563           }
3564           return false;
3565         }) > 1)
3566       return false;
3567     if (Gather)
3568       GatherOps.push_back(Gather);
3569   }
3570   return true;
3571 }
3572 
3573 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3574   SetVector<TreeEntry *> OrderedEntries;
3575   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3576   // Find all reorderable leaf nodes with the given VF.
3577   // Currently the are vectorized loads,extracts without alternate operands +
3578   // some gathering of extracts.
3579   SmallVector<TreeEntry *> NonVectorized;
3580   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3581                               &NonVectorized](
3582                                  const std::unique_ptr<TreeEntry> &TE) {
3583     if (TE->State != TreeEntry::Vectorize)
3584       NonVectorized.push_back(TE.get());
3585     if (Optional<OrdersType> CurrentOrder =
3586             getReorderingData(*TE, /*TopToBottom=*/false)) {
3587       OrderedEntries.insert(TE.get());
3588       if (TE->State != TreeEntry::Vectorize)
3589         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3590     }
3591   });
3592 
3593   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3594   // I.e., if the node has operands, that are reordered, try to make at least
3595   // one operand order in the natural order and reorder others + reorder the
3596   // user node itself.
3597   SmallPtrSet<const TreeEntry *, 4> Visited;
3598   while (!OrderedEntries.empty()) {
3599     // 1. Filter out only reordered nodes.
3600     // 2. If the entry has multiple uses - skip it and jump to the next node.
3601     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3602     SmallVector<TreeEntry *> Filtered;
3603     for (TreeEntry *TE : OrderedEntries) {
3604       if (!(TE->State == TreeEntry::Vectorize ||
3605             (TE->State == TreeEntry::NeedToGather &&
3606              GathersToOrders.count(TE))) ||
3607           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3608           !all_of(drop_begin(TE->UserTreeIndices),
3609                   [TE](const EdgeInfo &EI) {
3610                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3611                   }) ||
3612           !Visited.insert(TE).second) {
3613         Filtered.push_back(TE);
3614         continue;
3615       }
3616       // Build a map between user nodes and their operands order to speedup
3617       // search. The graph currently does not provide this dependency directly.
3618       for (EdgeInfo &EI : TE->UserTreeIndices) {
3619         TreeEntry *UserTE = EI.UserTE;
3620         auto It = Users.find(UserTE);
3621         if (It == Users.end())
3622           It = Users.insert({UserTE, {}}).first;
3623         It->second.emplace_back(EI.EdgeIdx, TE);
3624       }
3625     }
3626     // Erase filtered entries.
3627     for_each(Filtered,
3628              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3629     for (auto &Data : Users) {
3630       // Check that operands are used only in the User node.
3631       SmallVector<TreeEntry *> GatherOps;
3632       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3633                               GatherOps)) {
3634         for_each(Data.second,
3635                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3636                    OrderedEntries.remove(Op.second);
3637                  });
3638         continue;
3639       }
3640       // All operands are reordered and used only in this node - propagate the
3641       // most used order to the user node.
3642       MapVector<OrdersType, unsigned,
3643                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3644           OrdersUses;
3645       // Do the analysis for each tree entry only once, otherwise the order of
3646       // the same node my be considered several times, though might be not
3647       // profitable.
3648       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3649       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3650       for (const auto &Op : Data.second) {
3651         TreeEntry *OpTE = Op.second;
3652         if (!VisitedOps.insert(OpTE).second)
3653           continue;
3654         if (!OpTE->ReuseShuffleIndices.empty() ||
3655             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3656           continue;
3657         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3658           if (OpTE->State == TreeEntry::NeedToGather)
3659             return GathersToOrders.find(OpTE)->second;
3660           return OpTE->ReorderIndices;
3661         }();
3662         unsigned NumOps = count_if(
3663             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3664               return P.second == OpTE;
3665             });
3666         // Stores actually store the mask, not the order, need to invert.
3667         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3668             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3669           SmallVector<int> Mask;
3670           inversePermutation(Order, Mask);
3671           unsigned E = Order.size();
3672           OrdersType CurrentOrder(E, E);
3673           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3674             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3675           });
3676           fixupOrderingIndices(CurrentOrder);
3677           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3678               NumOps;
3679         } else {
3680           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3681         }
3682         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3683         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3684                                             const TreeEntry *TE) {
3685           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3686               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3687               (IgnoreReorder && TE->Idx == 0))
3688             return true;
3689           if (TE->State == TreeEntry::NeedToGather) {
3690             auto It = GathersToOrders.find(TE);
3691             if (It != GathersToOrders.end())
3692               return !It->second.empty();
3693             return true;
3694           }
3695           return false;
3696         };
3697         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3698           TreeEntry *UserTE = EI.UserTE;
3699           if (!VisitedUsers.insert(UserTE).second)
3700             continue;
3701           // May reorder user node if it requires reordering, has reused
3702           // scalars, is an alternate op vectorize node or its op nodes require
3703           // reordering.
3704           if (AllowsReordering(UserTE))
3705             continue;
3706           // Check if users allow reordering.
3707           // Currently look up just 1 level of operands to avoid increase of
3708           // the compile time.
3709           // Profitable to reorder if definitely more operands allow
3710           // reordering rather than those with natural order.
3711           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3712           if (static_cast<unsigned>(count_if(
3713                   Ops, [UserTE, &AllowsReordering](
3714                            const std::pair<unsigned, TreeEntry *> &Op) {
3715                     return AllowsReordering(Op.second) &&
3716                            all_of(Op.second->UserTreeIndices,
3717                                   [UserTE](const EdgeInfo &EI) {
3718                                     return EI.UserTE == UserTE;
3719                                   });
3720                   })) <= Ops.size() / 2)
3721             ++Res.first->second;
3722         }
3723       }
3724       // If no orders - skip current nodes and jump to the next one, if any.
3725       if (OrdersUses.empty()) {
3726         for_each(Data.second,
3727                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3728                    OrderedEntries.remove(Op.second);
3729                  });
3730         continue;
3731       }
3732       // Choose the best order.
3733       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3734       unsigned Cnt = OrdersUses.front().second;
3735       for (const auto &Pair : drop_begin(OrdersUses)) {
3736         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3737           BestOrder = Pair.first;
3738           Cnt = Pair.second;
3739         }
3740       }
3741       // Set order of the user node (reordering of operands and user nodes).
3742       if (BestOrder.empty()) {
3743         for_each(Data.second,
3744                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3745                    OrderedEntries.remove(Op.second);
3746                  });
3747         continue;
3748       }
3749       // Erase operands from OrderedEntries list and adjust their orders.
3750       VisitedOps.clear();
3751       SmallVector<int> Mask;
3752       inversePermutation(BestOrder, Mask);
3753       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3754       unsigned E = BestOrder.size();
3755       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3756         return I < E ? static_cast<int>(I) : UndefMaskElem;
3757       });
3758       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3759         TreeEntry *TE = Op.second;
3760         OrderedEntries.remove(TE);
3761         if (!VisitedOps.insert(TE).second)
3762           continue;
3763         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3764           // Just reorder reuses indices.
3765           reorderReuses(TE->ReuseShuffleIndices, Mask);
3766           continue;
3767         }
3768         // Gathers are processed separately.
3769         if (TE->State != TreeEntry::Vectorize)
3770           continue;
3771         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3772                 TE->ReorderIndices.empty()) &&
3773                "Non-matching sizes of user/operand entries.");
3774         reorderOrder(TE->ReorderIndices, Mask);
3775       }
3776       // For gathers just need to reorder its scalars.
3777       for (TreeEntry *Gather : GatherOps) {
3778         assert(Gather->ReorderIndices.empty() &&
3779                "Unexpected reordering of gathers.");
3780         if (!Gather->ReuseShuffleIndices.empty()) {
3781           // Just reorder reuses indices.
3782           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3783           continue;
3784         }
3785         reorderScalars(Gather->Scalars, Mask);
3786         OrderedEntries.remove(Gather);
3787       }
3788       // Reorder operands of the user node and set the ordering for the user
3789       // node itself.
3790       if (Data.first->State != TreeEntry::Vectorize ||
3791           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3792               Data.first->getMainOp()) ||
3793           Data.first->isAltShuffle())
3794         Data.first->reorderOperands(Mask);
3795       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3796           Data.first->isAltShuffle()) {
3797         reorderScalars(Data.first->Scalars, Mask);
3798         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3799         if (Data.first->ReuseShuffleIndices.empty() &&
3800             !Data.first->ReorderIndices.empty() &&
3801             !Data.first->isAltShuffle()) {
3802           // Insert user node to the list to try to sink reordering deeper in
3803           // the graph.
3804           OrderedEntries.insert(Data.first);
3805         }
3806       } else {
3807         reorderOrder(Data.first->ReorderIndices, Mask);
3808       }
3809     }
3810   }
3811   // If the reordering is unnecessary, just remove the reorder.
3812   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3813       VectorizableTree.front()->ReuseShuffleIndices.empty())
3814     VectorizableTree.front()->ReorderIndices.clear();
3815 }
3816 
3817 void BoUpSLP::buildExternalUses(
3818     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3819   // Collect the values that we need to extract from the tree.
3820   for (auto &TEPtr : VectorizableTree) {
3821     TreeEntry *Entry = TEPtr.get();
3822 
3823     // No need to handle users of gathered values.
3824     if (Entry->State == TreeEntry::NeedToGather)
3825       continue;
3826 
3827     // For each lane:
3828     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3829       Value *Scalar = Entry->Scalars[Lane];
3830       int FoundLane = Entry->findLaneForValue(Scalar);
3831 
3832       // Check if the scalar is externally used as an extra arg.
3833       auto ExtI = ExternallyUsedValues.find(Scalar);
3834       if (ExtI != ExternallyUsedValues.end()) {
3835         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3836                           << Lane << " from " << *Scalar << ".\n");
3837         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3838       }
3839       for (User *U : Scalar->users()) {
3840         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3841 
3842         Instruction *UserInst = dyn_cast<Instruction>(U);
3843         if (!UserInst)
3844           continue;
3845 
3846         if (isDeleted(UserInst))
3847           continue;
3848 
3849         // Skip in-tree scalars that become vectors
3850         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3851           Value *UseScalar = UseEntry->Scalars[0];
3852           // Some in-tree scalars will remain as scalar in vectorized
3853           // instructions. If that is the case, the one in Lane 0 will
3854           // be used.
3855           if (UseScalar != U ||
3856               UseEntry->State == TreeEntry::ScatterVectorize ||
3857               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3858             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3859                               << ".\n");
3860             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3861             continue;
3862           }
3863         }
3864 
3865         // Ignore users in the user ignore list.
3866         if (is_contained(UserIgnoreList, UserInst))
3867           continue;
3868 
3869         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3870                           << Lane << " from " << *Scalar << ".\n");
3871         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3872       }
3873     }
3874   }
3875 }
3876 
3877 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3878                         ArrayRef<Value *> UserIgnoreLst) {
3879   deleteTree();
3880   UserIgnoreList = UserIgnoreLst;
3881   if (!allSameType(Roots))
3882     return;
3883   buildTree_rec(Roots, 0, EdgeInfo());
3884 }
3885 
3886 namespace {
3887 /// Tracks the state we can represent the loads in the given sequence.
3888 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3889 } // anonymous namespace
3890 
3891 /// Checks if the given array of loads can be represented as a vectorized,
3892 /// scatter or just simple gather.
3893 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3894                                     const TargetTransformInfo &TTI,
3895                                     const DataLayout &DL, ScalarEvolution &SE,
3896                                     SmallVectorImpl<unsigned> &Order,
3897                                     SmallVectorImpl<Value *> &PointerOps) {
3898   // Check that a vectorized load would load the same memory as a scalar
3899   // load. For example, we don't want to vectorize loads that are smaller
3900   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3901   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3902   // from such a struct, we read/write packed bits disagreeing with the
3903   // unvectorized version.
3904   Type *ScalarTy = VL0->getType();
3905 
3906   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3907     return LoadsState::Gather;
3908 
3909   // Make sure all loads in the bundle are simple - we can't vectorize
3910   // atomic or volatile loads.
3911   PointerOps.clear();
3912   PointerOps.resize(VL.size());
3913   auto *POIter = PointerOps.begin();
3914   for (Value *V : VL) {
3915     auto *L = cast<LoadInst>(V);
3916     if (!L->isSimple())
3917       return LoadsState::Gather;
3918     *POIter = L->getPointerOperand();
3919     ++POIter;
3920   }
3921 
3922   Order.clear();
3923   // Check the order of pointer operands.
3924   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3925     Value *Ptr0;
3926     Value *PtrN;
3927     if (Order.empty()) {
3928       Ptr0 = PointerOps.front();
3929       PtrN = PointerOps.back();
3930     } else {
3931       Ptr0 = PointerOps[Order.front()];
3932       PtrN = PointerOps[Order.back()];
3933     }
3934     Optional<int> Diff =
3935         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3936     // Check that the sorted loads are consecutive.
3937     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3938       return LoadsState::Vectorize;
3939     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3940     for (Value *V : VL)
3941       CommonAlignment =
3942           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3943     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3944                                 CommonAlignment))
3945       return LoadsState::ScatterVectorize;
3946   }
3947 
3948   return LoadsState::Gather;
3949 }
3950 
3951 /// \return true if the specified list of values has only one instruction that
3952 /// requires scheduling, false otherwise.
3953 #ifndef NDEBUG
3954 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3955   Value *NeedsScheduling = nullptr;
3956   for (Value *V : VL) {
3957     if (doesNotNeedToBeScheduled(V))
3958       continue;
3959     if (!NeedsScheduling) {
3960       NeedsScheduling = V;
3961       continue;
3962     }
3963     return false;
3964   }
3965   return NeedsScheduling;
3966 }
3967 #endif
3968 
3969 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3970                             const EdgeInfo &UserTreeIdx) {
3971   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3972 
3973   SmallVector<int> ReuseShuffleIndicies;
3974   SmallVector<Value *> UniqueValues;
3975   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3976                                 &UserTreeIdx,
3977                                 this](const InstructionsState &S) {
3978     // Check that every instruction appears once in this bundle.
3979     DenseMap<Value *, unsigned> UniquePositions;
3980     for (Value *V : VL) {
3981       if (isConstant(V)) {
3982         ReuseShuffleIndicies.emplace_back(
3983             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3984         UniqueValues.emplace_back(V);
3985         continue;
3986       }
3987       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3988       ReuseShuffleIndicies.emplace_back(Res.first->second);
3989       if (Res.second)
3990         UniqueValues.emplace_back(V);
3991     }
3992     size_t NumUniqueScalarValues = UniqueValues.size();
3993     if (NumUniqueScalarValues == VL.size()) {
3994       ReuseShuffleIndicies.clear();
3995     } else {
3996       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3997       if (NumUniqueScalarValues <= 1 ||
3998           (UniquePositions.size() == 1 && all_of(UniqueValues,
3999                                                  [](Value *V) {
4000                                                    return isa<UndefValue>(V) ||
4001                                                           !isConstant(V);
4002                                                  })) ||
4003           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4004         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4005         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4006         return false;
4007       }
4008       VL = UniqueValues;
4009     }
4010     return true;
4011   };
4012 
4013   InstructionsState S = getSameOpcode(VL);
4014   if (Depth == RecursionMaxDepth) {
4015     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4016     if (TryToFindDuplicates(S))
4017       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4018                    ReuseShuffleIndicies);
4019     return;
4020   }
4021 
4022   // Don't handle scalable vectors
4023   if (S.getOpcode() == Instruction::ExtractElement &&
4024       isa<ScalableVectorType>(
4025           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4026     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4027     if (TryToFindDuplicates(S))
4028       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4029                    ReuseShuffleIndicies);
4030     return;
4031   }
4032 
4033   // Don't handle vectors.
4034   if (S.OpValue->getType()->isVectorTy() &&
4035       !isa<InsertElementInst>(S.OpValue)) {
4036     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4037     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4038     return;
4039   }
4040 
4041   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4042     if (SI->getValueOperand()->getType()->isVectorTy()) {
4043       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4044       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4045       return;
4046     }
4047 
4048   // If all of the operands are identical or constant we have a simple solution.
4049   // If we deal with insert/extract instructions, they all must have constant
4050   // indices, otherwise we should gather them, not try to vectorize.
4051   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4052       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4053        !all_of(VL, isVectorLikeInstWithConstOps))) {
4054     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4055     if (TryToFindDuplicates(S))
4056       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4057                    ReuseShuffleIndicies);
4058     return;
4059   }
4060 
4061   // We now know that this is a vector of instructions of the same type from
4062   // the same block.
4063 
4064   // Don't vectorize ephemeral values.
4065   for (Value *V : VL) {
4066     if (EphValues.count(V)) {
4067       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4068                         << ") is ephemeral.\n");
4069       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4070       return;
4071     }
4072   }
4073 
4074   // Check if this is a duplicate of another entry.
4075   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4076     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4077     if (!E->isSame(VL)) {
4078       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4079       if (TryToFindDuplicates(S))
4080         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4081                      ReuseShuffleIndicies);
4082       return;
4083     }
4084     // Record the reuse of the tree node.  FIXME, currently this is only used to
4085     // properly draw the graph rather than for the actual vectorization.
4086     E->UserTreeIndices.push_back(UserTreeIdx);
4087     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4088                       << ".\n");
4089     return;
4090   }
4091 
4092   // Check that none of the instructions in the bundle are already in the tree.
4093   for (Value *V : VL) {
4094     auto *I = dyn_cast<Instruction>(V);
4095     if (!I)
4096       continue;
4097     if (getTreeEntry(I)) {
4098       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4099                         << ") is already in tree.\n");
4100       if (TryToFindDuplicates(S))
4101         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4102                      ReuseShuffleIndicies);
4103       return;
4104     }
4105   }
4106 
4107   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4108   for (Value *V : VL) {
4109     if (is_contained(UserIgnoreList, V)) {
4110       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4111       if (TryToFindDuplicates(S))
4112         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4113                      ReuseShuffleIndicies);
4114       return;
4115     }
4116   }
4117 
4118   // Check that all of the users of the scalars that we want to vectorize are
4119   // schedulable.
4120   auto *VL0 = cast<Instruction>(S.OpValue);
4121   BasicBlock *BB = VL0->getParent();
4122 
4123   if (!DT->isReachableFromEntry(BB)) {
4124     // Don't go into unreachable blocks. They may contain instructions with
4125     // dependency cycles which confuse the final scheduling.
4126     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4127     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4128     return;
4129   }
4130 
4131   // Check that every instruction appears once in this bundle.
4132   if (!TryToFindDuplicates(S))
4133     return;
4134 
4135   auto &BSRef = BlocksSchedules[BB];
4136   if (!BSRef)
4137     BSRef = std::make_unique<BlockScheduling>(BB);
4138 
4139   BlockScheduling &BS = *BSRef;
4140 
4141   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4142 #ifdef EXPENSIVE_CHECKS
4143   // Make sure we didn't break any internal invariants
4144   BS.verify();
4145 #endif
4146   if (!Bundle) {
4147     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4148     assert((!BS.getScheduleData(VL0) ||
4149             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4150            "tryScheduleBundle should cancelScheduling on failure");
4151     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4152                  ReuseShuffleIndicies);
4153     return;
4154   }
4155   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4156 
4157   unsigned ShuffleOrOp = S.isAltShuffle() ?
4158                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4159   switch (ShuffleOrOp) {
4160     case Instruction::PHI: {
4161       auto *PH = cast<PHINode>(VL0);
4162 
4163       // Check for terminator values (e.g. invoke).
4164       for (Value *V : VL)
4165         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4166           Instruction *Term = dyn_cast<Instruction>(Incoming);
4167           if (Term && Term->isTerminator()) {
4168             LLVM_DEBUG(dbgs()
4169                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4170             BS.cancelScheduling(VL, VL0);
4171             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4172                          ReuseShuffleIndicies);
4173             return;
4174           }
4175         }
4176 
4177       TreeEntry *TE =
4178           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4179       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4180 
4181       // Keeps the reordered operands to avoid code duplication.
4182       SmallVector<ValueList, 2> OperandsVec;
4183       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4184         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4185           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4186           TE->setOperand(I, Operands);
4187           OperandsVec.push_back(Operands);
4188           continue;
4189         }
4190         ValueList Operands;
4191         // Prepare the operand vector.
4192         for (Value *V : VL)
4193           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4194               PH->getIncomingBlock(I)));
4195         TE->setOperand(I, Operands);
4196         OperandsVec.push_back(Operands);
4197       }
4198       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4199         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4200       return;
4201     }
4202     case Instruction::ExtractValue:
4203     case Instruction::ExtractElement: {
4204       OrdersType CurrentOrder;
4205       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4206       if (Reuse) {
4207         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4208         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4209                      ReuseShuffleIndicies);
4210         // This is a special case, as it does not gather, but at the same time
4211         // we are not extending buildTree_rec() towards the operands.
4212         ValueList Op0;
4213         Op0.assign(VL.size(), VL0->getOperand(0));
4214         VectorizableTree.back()->setOperand(0, Op0);
4215         return;
4216       }
4217       if (!CurrentOrder.empty()) {
4218         LLVM_DEBUG({
4219           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4220                     "with order";
4221           for (unsigned Idx : CurrentOrder)
4222             dbgs() << " " << Idx;
4223           dbgs() << "\n";
4224         });
4225         fixupOrderingIndices(CurrentOrder);
4226         // Insert new order with initial value 0, if it does not exist,
4227         // otherwise return the iterator to the existing one.
4228         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4229                      ReuseShuffleIndicies, CurrentOrder);
4230         // This is a special case, as it does not gather, but at the same time
4231         // we are not extending buildTree_rec() towards the operands.
4232         ValueList Op0;
4233         Op0.assign(VL.size(), VL0->getOperand(0));
4234         VectorizableTree.back()->setOperand(0, Op0);
4235         return;
4236       }
4237       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4238       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4239                    ReuseShuffleIndicies);
4240       BS.cancelScheduling(VL, VL0);
4241       return;
4242     }
4243     case Instruction::InsertElement: {
4244       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4245 
4246       // Check that we have a buildvector and not a shuffle of 2 or more
4247       // different vectors.
4248       ValueSet SourceVectors;
4249       for (Value *V : VL) {
4250         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4251         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4252       }
4253 
4254       if (count_if(VL, [&SourceVectors](Value *V) {
4255             return !SourceVectors.contains(V);
4256           }) >= 2) {
4257         // Found 2nd source vector - cancel.
4258         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4259                              "different source vectors.\n");
4260         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4261         BS.cancelScheduling(VL, VL0);
4262         return;
4263       }
4264 
4265       auto OrdCompare = [](const std::pair<int, int> &P1,
4266                            const std::pair<int, int> &P2) {
4267         return P1.first > P2.first;
4268       };
4269       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4270                     decltype(OrdCompare)>
4271           Indices(OrdCompare);
4272       for (int I = 0, E = VL.size(); I < E; ++I) {
4273         unsigned Idx = *getInsertIndex(VL[I]);
4274         Indices.emplace(Idx, I);
4275       }
4276       OrdersType CurrentOrder(VL.size(), VL.size());
4277       bool IsIdentity = true;
4278       for (int I = 0, E = VL.size(); I < E; ++I) {
4279         CurrentOrder[Indices.top().second] = I;
4280         IsIdentity &= Indices.top().second == I;
4281         Indices.pop();
4282       }
4283       if (IsIdentity)
4284         CurrentOrder.clear();
4285       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4286                                    None, CurrentOrder);
4287       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4288 
4289       constexpr int NumOps = 2;
4290       ValueList VectorOperands[NumOps];
4291       for (int I = 0; I < NumOps; ++I) {
4292         for (Value *V : VL)
4293           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4294 
4295         TE->setOperand(I, VectorOperands[I]);
4296       }
4297       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4298       return;
4299     }
4300     case Instruction::Load: {
4301       // Check that a vectorized load would load the same memory as a scalar
4302       // load. For example, we don't want to vectorize loads that are smaller
4303       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4304       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4305       // from such a struct, we read/write packed bits disagreeing with the
4306       // unvectorized version.
4307       SmallVector<Value *> PointerOps;
4308       OrdersType CurrentOrder;
4309       TreeEntry *TE = nullptr;
4310       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4311                                 PointerOps)) {
4312       case LoadsState::Vectorize:
4313         if (CurrentOrder.empty()) {
4314           // Original loads are consecutive and does not require reordering.
4315           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4316                             ReuseShuffleIndicies);
4317           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4318         } else {
4319           fixupOrderingIndices(CurrentOrder);
4320           // Need to reorder.
4321           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4322                             ReuseShuffleIndicies, CurrentOrder);
4323           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4324         }
4325         TE->setOperandsInOrder();
4326         break;
4327       case LoadsState::ScatterVectorize:
4328         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4329         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4330                           UserTreeIdx, ReuseShuffleIndicies);
4331         TE->setOperandsInOrder();
4332         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4333         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4334         break;
4335       case LoadsState::Gather:
4336         BS.cancelScheduling(VL, VL0);
4337         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4338                      ReuseShuffleIndicies);
4339 #ifndef NDEBUG
4340         Type *ScalarTy = VL0->getType();
4341         if (DL->getTypeSizeInBits(ScalarTy) !=
4342             DL->getTypeAllocSizeInBits(ScalarTy))
4343           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4344         else if (any_of(VL, [](Value *V) {
4345                    return !cast<LoadInst>(V)->isSimple();
4346                  }))
4347           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4348         else
4349           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4350 #endif // NDEBUG
4351         break;
4352       }
4353       return;
4354     }
4355     case Instruction::ZExt:
4356     case Instruction::SExt:
4357     case Instruction::FPToUI:
4358     case Instruction::FPToSI:
4359     case Instruction::FPExt:
4360     case Instruction::PtrToInt:
4361     case Instruction::IntToPtr:
4362     case Instruction::SIToFP:
4363     case Instruction::UIToFP:
4364     case Instruction::Trunc:
4365     case Instruction::FPTrunc:
4366     case Instruction::BitCast: {
4367       Type *SrcTy = VL0->getOperand(0)->getType();
4368       for (Value *V : VL) {
4369         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4370         if (Ty != SrcTy || !isValidElementType(Ty)) {
4371           BS.cancelScheduling(VL, VL0);
4372           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4373                        ReuseShuffleIndicies);
4374           LLVM_DEBUG(dbgs()
4375                      << "SLP: Gathering casts with different src types.\n");
4376           return;
4377         }
4378       }
4379       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4380                                    ReuseShuffleIndicies);
4381       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4382 
4383       TE->setOperandsInOrder();
4384       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4385         ValueList Operands;
4386         // Prepare the operand vector.
4387         for (Value *V : VL)
4388           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4389 
4390         buildTree_rec(Operands, Depth + 1, {TE, i});
4391       }
4392       return;
4393     }
4394     case Instruction::ICmp:
4395     case Instruction::FCmp: {
4396       // Check that all of the compares have the same predicate.
4397       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4398       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4399       Type *ComparedTy = VL0->getOperand(0)->getType();
4400       for (Value *V : VL) {
4401         CmpInst *Cmp = cast<CmpInst>(V);
4402         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4403             Cmp->getOperand(0)->getType() != ComparedTy) {
4404           BS.cancelScheduling(VL, VL0);
4405           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4406                        ReuseShuffleIndicies);
4407           LLVM_DEBUG(dbgs()
4408                      << "SLP: Gathering cmp with different predicate.\n");
4409           return;
4410         }
4411       }
4412 
4413       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4414                                    ReuseShuffleIndicies);
4415       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4416 
4417       ValueList Left, Right;
4418       if (cast<CmpInst>(VL0)->isCommutative()) {
4419         // Commutative predicate - collect + sort operands of the instructions
4420         // so that each side is more likely to have the same opcode.
4421         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4422         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4423       } else {
4424         // Collect operands - commute if it uses the swapped predicate.
4425         for (Value *V : VL) {
4426           auto *Cmp = cast<CmpInst>(V);
4427           Value *LHS = Cmp->getOperand(0);
4428           Value *RHS = Cmp->getOperand(1);
4429           if (Cmp->getPredicate() != P0)
4430             std::swap(LHS, RHS);
4431           Left.push_back(LHS);
4432           Right.push_back(RHS);
4433         }
4434       }
4435       TE->setOperand(0, Left);
4436       TE->setOperand(1, Right);
4437       buildTree_rec(Left, Depth + 1, {TE, 0});
4438       buildTree_rec(Right, Depth + 1, {TE, 1});
4439       return;
4440     }
4441     case Instruction::Select:
4442     case Instruction::FNeg:
4443     case Instruction::Add:
4444     case Instruction::FAdd:
4445     case Instruction::Sub:
4446     case Instruction::FSub:
4447     case Instruction::Mul:
4448     case Instruction::FMul:
4449     case Instruction::UDiv:
4450     case Instruction::SDiv:
4451     case Instruction::FDiv:
4452     case Instruction::URem:
4453     case Instruction::SRem:
4454     case Instruction::FRem:
4455     case Instruction::Shl:
4456     case Instruction::LShr:
4457     case Instruction::AShr:
4458     case Instruction::And:
4459     case Instruction::Or:
4460     case Instruction::Xor: {
4461       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4462                                    ReuseShuffleIndicies);
4463       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4464 
4465       // Sort operands of the instructions so that each side is more likely to
4466       // have the same opcode.
4467       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4468         ValueList Left, Right;
4469         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4470         TE->setOperand(0, Left);
4471         TE->setOperand(1, Right);
4472         buildTree_rec(Left, Depth + 1, {TE, 0});
4473         buildTree_rec(Right, Depth + 1, {TE, 1});
4474         return;
4475       }
4476 
4477       TE->setOperandsInOrder();
4478       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4479         ValueList Operands;
4480         // Prepare the operand vector.
4481         for (Value *V : VL)
4482           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4483 
4484         buildTree_rec(Operands, Depth + 1, {TE, i});
4485       }
4486       return;
4487     }
4488     case Instruction::GetElementPtr: {
4489       // We don't combine GEPs with complicated (nested) indexing.
4490       for (Value *V : VL) {
4491         if (cast<Instruction>(V)->getNumOperands() != 2) {
4492           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4493           BS.cancelScheduling(VL, VL0);
4494           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4495                        ReuseShuffleIndicies);
4496           return;
4497         }
4498       }
4499 
4500       // We can't combine several GEPs into one vector if they operate on
4501       // different types.
4502       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4503       for (Value *V : VL) {
4504         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4505         if (Ty0 != CurTy) {
4506           LLVM_DEBUG(dbgs()
4507                      << "SLP: not-vectorizable GEP (different types).\n");
4508           BS.cancelScheduling(VL, VL0);
4509           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4510                        ReuseShuffleIndicies);
4511           return;
4512         }
4513       }
4514 
4515       // We don't combine GEPs with non-constant indexes.
4516       Type *Ty1 = VL0->getOperand(1)->getType();
4517       for (Value *V : VL) {
4518         auto Op = cast<Instruction>(V)->getOperand(1);
4519         if (!isa<ConstantInt>(Op) ||
4520             (Op->getType() != Ty1 &&
4521              Op->getType()->getScalarSizeInBits() >
4522                  DL->getIndexSizeInBits(
4523                      V->getType()->getPointerAddressSpace()))) {
4524           LLVM_DEBUG(dbgs()
4525                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4526           BS.cancelScheduling(VL, VL0);
4527           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4528                        ReuseShuffleIndicies);
4529           return;
4530         }
4531       }
4532 
4533       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4534                                    ReuseShuffleIndicies);
4535       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4536       SmallVector<ValueList, 2> Operands(2);
4537       // Prepare the operand vector for pointer operands.
4538       for (Value *V : VL)
4539         Operands.front().push_back(
4540             cast<GetElementPtrInst>(V)->getPointerOperand());
4541       TE->setOperand(0, Operands.front());
4542       // Need to cast all indices to the same type before vectorization to
4543       // avoid crash.
4544       // Required to be able to find correct matches between different gather
4545       // nodes and reuse the vectorized values rather than trying to gather them
4546       // again.
4547       int IndexIdx = 1;
4548       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4549       Type *Ty = all_of(VL,
4550                         [VL0Ty, IndexIdx](Value *V) {
4551                           return VL0Ty == cast<GetElementPtrInst>(V)
4552                                               ->getOperand(IndexIdx)
4553                                               ->getType();
4554                         })
4555                      ? VL0Ty
4556                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4557                                             ->getPointerOperandType()
4558                                             ->getScalarType());
4559       // Prepare the operand vector.
4560       for (Value *V : VL) {
4561         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4562         auto *CI = cast<ConstantInt>(Op);
4563         Operands.back().push_back(ConstantExpr::getIntegerCast(
4564             CI, Ty, CI->getValue().isSignBitSet()));
4565       }
4566       TE->setOperand(IndexIdx, Operands.back());
4567 
4568       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4569         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4570       return;
4571     }
4572     case Instruction::Store: {
4573       // Check if the stores are consecutive or if we need to swizzle them.
4574       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4575       // Avoid types that are padded when being allocated as scalars, while
4576       // being packed together in a vector (such as i1).
4577       if (DL->getTypeSizeInBits(ScalarTy) !=
4578           DL->getTypeAllocSizeInBits(ScalarTy)) {
4579         BS.cancelScheduling(VL, VL0);
4580         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4581                      ReuseShuffleIndicies);
4582         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4583         return;
4584       }
4585       // Make sure all stores in the bundle are simple - we can't vectorize
4586       // atomic or volatile stores.
4587       SmallVector<Value *, 4> PointerOps(VL.size());
4588       ValueList Operands(VL.size());
4589       auto POIter = PointerOps.begin();
4590       auto OIter = Operands.begin();
4591       for (Value *V : VL) {
4592         auto *SI = cast<StoreInst>(V);
4593         if (!SI->isSimple()) {
4594           BS.cancelScheduling(VL, VL0);
4595           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4596                        ReuseShuffleIndicies);
4597           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4598           return;
4599         }
4600         *POIter = SI->getPointerOperand();
4601         *OIter = SI->getValueOperand();
4602         ++POIter;
4603         ++OIter;
4604       }
4605 
4606       OrdersType CurrentOrder;
4607       // Check the order of pointer operands.
4608       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4609         Value *Ptr0;
4610         Value *PtrN;
4611         if (CurrentOrder.empty()) {
4612           Ptr0 = PointerOps.front();
4613           PtrN = PointerOps.back();
4614         } else {
4615           Ptr0 = PointerOps[CurrentOrder.front()];
4616           PtrN = PointerOps[CurrentOrder.back()];
4617         }
4618         Optional<int> Dist =
4619             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4620         // Check that the sorted pointer operands are consecutive.
4621         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4622           if (CurrentOrder.empty()) {
4623             // Original stores are consecutive and does not require reordering.
4624             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4625                                          UserTreeIdx, ReuseShuffleIndicies);
4626             TE->setOperandsInOrder();
4627             buildTree_rec(Operands, Depth + 1, {TE, 0});
4628             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4629           } else {
4630             fixupOrderingIndices(CurrentOrder);
4631             TreeEntry *TE =
4632                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4633                              ReuseShuffleIndicies, CurrentOrder);
4634             TE->setOperandsInOrder();
4635             buildTree_rec(Operands, Depth + 1, {TE, 0});
4636             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4637           }
4638           return;
4639         }
4640       }
4641 
4642       BS.cancelScheduling(VL, VL0);
4643       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4644                    ReuseShuffleIndicies);
4645       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4646       return;
4647     }
4648     case Instruction::Call: {
4649       // Check if the calls are all to the same vectorizable intrinsic or
4650       // library function.
4651       CallInst *CI = cast<CallInst>(VL0);
4652       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4653 
4654       VFShape Shape = VFShape::get(
4655           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4656           false /*HasGlobalPred*/);
4657       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4658 
4659       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4660         BS.cancelScheduling(VL, VL0);
4661         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4662                      ReuseShuffleIndicies);
4663         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4664         return;
4665       }
4666       Function *F = CI->getCalledFunction();
4667       unsigned NumArgs = CI->arg_size();
4668       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4669       for (unsigned j = 0; j != NumArgs; ++j)
4670         if (hasVectorInstrinsicScalarOpd(ID, j))
4671           ScalarArgs[j] = CI->getArgOperand(j);
4672       for (Value *V : VL) {
4673         CallInst *CI2 = dyn_cast<CallInst>(V);
4674         if (!CI2 || CI2->getCalledFunction() != F ||
4675             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4676             (VecFunc &&
4677              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4678             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4679           BS.cancelScheduling(VL, VL0);
4680           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4681                        ReuseShuffleIndicies);
4682           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4683                             << "\n");
4684           return;
4685         }
4686         // Some intrinsics have scalar arguments and should be same in order for
4687         // them to be vectorized.
4688         for (unsigned j = 0; j != NumArgs; ++j) {
4689           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4690             Value *A1J = CI2->getArgOperand(j);
4691             if (ScalarArgs[j] != A1J) {
4692               BS.cancelScheduling(VL, VL0);
4693               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4694                            ReuseShuffleIndicies);
4695               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4696                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4697                                 << "\n");
4698               return;
4699             }
4700           }
4701         }
4702         // Verify that the bundle operands are identical between the two calls.
4703         if (CI->hasOperandBundles() &&
4704             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4705                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4706                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4707           BS.cancelScheduling(VL, VL0);
4708           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4709                        ReuseShuffleIndicies);
4710           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4711                             << *CI << "!=" << *V << '\n');
4712           return;
4713         }
4714       }
4715 
4716       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4717                                    ReuseShuffleIndicies);
4718       TE->setOperandsInOrder();
4719       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4720         // For scalar operands no need to to create an entry since no need to
4721         // vectorize it.
4722         if (hasVectorInstrinsicScalarOpd(ID, i))
4723           continue;
4724         ValueList Operands;
4725         // Prepare the operand vector.
4726         for (Value *V : VL) {
4727           auto *CI2 = cast<CallInst>(V);
4728           Operands.push_back(CI2->getArgOperand(i));
4729         }
4730         buildTree_rec(Operands, Depth + 1, {TE, i});
4731       }
4732       return;
4733     }
4734     case Instruction::ShuffleVector: {
4735       // If this is not an alternate sequence of opcode like add-sub
4736       // then do not vectorize this instruction.
4737       if (!S.isAltShuffle()) {
4738         BS.cancelScheduling(VL, VL0);
4739         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4740                      ReuseShuffleIndicies);
4741         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4742         return;
4743       }
4744       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4745                                    ReuseShuffleIndicies);
4746       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4747 
4748       // Reorder operands if reordering would enable vectorization.
4749       auto *CI = dyn_cast<CmpInst>(VL0);
4750       if (isa<BinaryOperator>(VL0) || CI) {
4751         ValueList Left, Right;
4752         if (!CI || all_of(VL, [](Value *V) {
4753               return cast<CmpInst>(V)->isCommutative();
4754             })) {
4755           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4756         } else {
4757           CmpInst::Predicate P0 = CI->getPredicate();
4758           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4759           assert(P0 != AltP0 &&
4760                  "Expected different main/alternate predicates.");
4761           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4762           Value *BaseOp0 = VL0->getOperand(0);
4763           Value *BaseOp1 = VL0->getOperand(1);
4764           // Collect operands - commute if it uses the swapped predicate or
4765           // alternate operation.
4766           for (Value *V : VL) {
4767             auto *Cmp = cast<CmpInst>(V);
4768             Value *LHS = Cmp->getOperand(0);
4769             Value *RHS = Cmp->getOperand(1);
4770             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4771             if (P0 == AltP0Swapped) {
4772               if (CI != Cmp && S.AltOp != Cmp &&
4773                   ((P0 == CurrentPred &&
4774                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4775                    (AltP0 == CurrentPred &&
4776                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4777                 std::swap(LHS, RHS);
4778             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4779               std::swap(LHS, RHS);
4780             }
4781             Left.push_back(LHS);
4782             Right.push_back(RHS);
4783           }
4784         }
4785         TE->setOperand(0, Left);
4786         TE->setOperand(1, Right);
4787         buildTree_rec(Left, Depth + 1, {TE, 0});
4788         buildTree_rec(Right, Depth + 1, {TE, 1});
4789         return;
4790       }
4791 
4792       TE->setOperandsInOrder();
4793       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4794         ValueList Operands;
4795         // Prepare the operand vector.
4796         for (Value *V : VL)
4797           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4798 
4799         buildTree_rec(Operands, Depth + 1, {TE, i});
4800       }
4801       return;
4802     }
4803     default:
4804       BS.cancelScheduling(VL, VL0);
4805       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4806                    ReuseShuffleIndicies);
4807       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4808       return;
4809   }
4810 }
4811 
4812 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4813   unsigned N = 1;
4814   Type *EltTy = T;
4815 
4816   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4817          isa<VectorType>(EltTy)) {
4818     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4819       // Check that struct is homogeneous.
4820       for (const auto *Ty : ST->elements())
4821         if (Ty != *ST->element_begin())
4822           return 0;
4823       N *= ST->getNumElements();
4824       EltTy = *ST->element_begin();
4825     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4826       N *= AT->getNumElements();
4827       EltTy = AT->getElementType();
4828     } else {
4829       auto *VT = cast<FixedVectorType>(EltTy);
4830       N *= VT->getNumElements();
4831       EltTy = VT->getElementType();
4832     }
4833   }
4834 
4835   if (!isValidElementType(EltTy))
4836     return 0;
4837   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4838   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4839     return 0;
4840   return N;
4841 }
4842 
4843 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4844                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4845   const auto *It = find_if(VL, [](Value *V) {
4846     return isa<ExtractElementInst, ExtractValueInst>(V);
4847   });
4848   assert(It != VL.end() && "Expected at least one extract instruction.");
4849   auto *E0 = cast<Instruction>(*It);
4850   assert(all_of(VL,
4851                 [](Value *V) {
4852                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4853                       V);
4854                 }) &&
4855          "Invalid opcode");
4856   // Check if all of the extracts come from the same vector and from the
4857   // correct offset.
4858   Value *Vec = E0->getOperand(0);
4859 
4860   CurrentOrder.clear();
4861 
4862   // We have to extract from a vector/aggregate with the same number of elements.
4863   unsigned NElts;
4864   if (E0->getOpcode() == Instruction::ExtractValue) {
4865     const DataLayout &DL = E0->getModule()->getDataLayout();
4866     NElts = canMapToVector(Vec->getType(), DL);
4867     if (!NElts)
4868       return false;
4869     // Check if load can be rewritten as load of vector.
4870     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4871     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4872       return false;
4873   } else {
4874     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4875   }
4876 
4877   if (NElts != VL.size())
4878     return false;
4879 
4880   // Check that all of the indices extract from the correct offset.
4881   bool ShouldKeepOrder = true;
4882   unsigned E = VL.size();
4883   // Assign to all items the initial value E + 1 so we can check if the extract
4884   // instruction index was used already.
4885   // Also, later we can check that all the indices are used and we have a
4886   // consecutive access in the extract instructions, by checking that no
4887   // element of CurrentOrder still has value E + 1.
4888   CurrentOrder.assign(E, E);
4889   unsigned I = 0;
4890   for (; I < E; ++I) {
4891     auto *Inst = dyn_cast<Instruction>(VL[I]);
4892     if (!Inst)
4893       continue;
4894     if (Inst->getOperand(0) != Vec)
4895       break;
4896     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4897       if (isa<UndefValue>(EE->getIndexOperand()))
4898         continue;
4899     Optional<unsigned> Idx = getExtractIndex(Inst);
4900     if (!Idx)
4901       break;
4902     const unsigned ExtIdx = *Idx;
4903     if (ExtIdx != I) {
4904       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4905         break;
4906       ShouldKeepOrder = false;
4907       CurrentOrder[ExtIdx] = I;
4908     } else {
4909       if (CurrentOrder[I] != E)
4910         break;
4911       CurrentOrder[I] = I;
4912     }
4913   }
4914   if (I < E) {
4915     CurrentOrder.clear();
4916     return false;
4917   }
4918   if (ShouldKeepOrder)
4919     CurrentOrder.clear();
4920 
4921   return ShouldKeepOrder;
4922 }
4923 
4924 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4925                                     ArrayRef<Value *> VectorizedVals) const {
4926   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4927          all_of(I->users(), [this](User *U) {
4928            return ScalarToTreeEntry.count(U) > 0 ||
4929                   isVectorLikeInstWithConstOps(U) ||
4930                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4931          });
4932 }
4933 
4934 static std::pair<InstructionCost, InstructionCost>
4935 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4936                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4937   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4938 
4939   // Calculate the cost of the scalar and vector calls.
4940   SmallVector<Type *, 4> VecTys;
4941   for (Use &Arg : CI->args())
4942     VecTys.push_back(
4943         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4944   FastMathFlags FMF;
4945   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4946     FMF = FPCI->getFastMathFlags();
4947   SmallVector<const Value *> Arguments(CI->args());
4948   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4949                                     dyn_cast<IntrinsicInst>(CI));
4950   auto IntrinsicCost =
4951     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4952 
4953   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4954                                      VecTy->getNumElements())),
4955                             false /*HasGlobalPred*/);
4956   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4957   auto LibCost = IntrinsicCost;
4958   if (!CI->isNoBuiltin() && VecFunc) {
4959     // Calculate the cost of the vector library call.
4960     // If the corresponding vector call is cheaper, return its cost.
4961     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4962                                     TTI::TCK_RecipThroughput);
4963   }
4964   return {IntrinsicCost, LibCost};
4965 }
4966 
4967 /// Compute the cost of creating a vector of type \p VecTy containing the
4968 /// extracted values from \p VL.
4969 static InstructionCost
4970 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4971                    TargetTransformInfo::ShuffleKind ShuffleKind,
4972                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4973   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4974 
4975   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4976       VecTy->getNumElements() < NumOfParts)
4977     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4978 
4979   bool AllConsecutive = true;
4980   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4981   unsigned Idx = -1;
4982   InstructionCost Cost = 0;
4983 
4984   // Process extracts in blocks of EltsPerVector to check if the source vector
4985   // operand can be re-used directly. If not, add the cost of creating a shuffle
4986   // to extract the values into a vector register.
4987   for (auto *V : VL) {
4988     ++Idx;
4989 
4990     // Need to exclude undefs from analysis.
4991     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4992       continue;
4993 
4994     // Reached the start of a new vector registers.
4995     if (Idx % EltsPerVector == 0) {
4996       AllConsecutive = true;
4997       continue;
4998     }
4999 
5000     // Check all extracts for a vector register on the target directly
5001     // extract values in order.
5002     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5003     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5004       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5005       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5006                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5007     }
5008 
5009     if (AllConsecutive)
5010       continue;
5011 
5012     // Skip all indices, except for the last index per vector block.
5013     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5014       continue;
5015 
5016     // If we have a series of extracts which are not consecutive and hence
5017     // cannot re-use the source vector register directly, compute the shuffle
5018     // cost to extract the a vector with EltsPerVector elements.
5019     Cost += TTI.getShuffleCost(
5020         TargetTransformInfo::SK_PermuteSingleSrc,
5021         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5022   }
5023   return Cost;
5024 }
5025 
5026 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5027 /// operations operands.
5028 static void
5029 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5030                       ArrayRef<int> ReusesIndices,
5031                       const function_ref<bool(Instruction *)> IsAltOp,
5032                       SmallVectorImpl<int> &Mask,
5033                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5034                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5035   unsigned Sz = VL.size();
5036   Mask.assign(Sz, UndefMaskElem);
5037   SmallVector<int> OrderMask;
5038   if (!ReorderIndices.empty())
5039     inversePermutation(ReorderIndices, OrderMask);
5040   for (unsigned I = 0; I < Sz; ++I) {
5041     unsigned Idx = I;
5042     if (!ReorderIndices.empty())
5043       Idx = OrderMask[I];
5044     auto *OpInst = cast<Instruction>(VL[Idx]);
5045     if (IsAltOp(OpInst)) {
5046       Mask[I] = Sz + Idx;
5047       if (AltScalars)
5048         AltScalars->push_back(OpInst);
5049     } else {
5050       Mask[I] = Idx;
5051       if (OpScalars)
5052         OpScalars->push_back(OpInst);
5053     }
5054   }
5055   if (!ReusesIndices.empty()) {
5056     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5057     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5058       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5059     });
5060     Mask.swap(NewMask);
5061   }
5062 }
5063 
5064 /// Checks if the specified instruction \p I is an alternate operation for the
5065 /// given \p MainOp and \p AltOp instructions.
5066 static bool isAlternateInstruction(const Instruction *I,
5067                                    const Instruction *MainOp,
5068                                    const Instruction *AltOp) {
5069   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5070     auto *AltCI0 = cast<CmpInst>(AltOp);
5071     auto *CI = cast<CmpInst>(I);
5072     CmpInst::Predicate P0 = CI0->getPredicate();
5073     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5074     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5075     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5076     CmpInst::Predicate CurrentPred = CI->getPredicate();
5077     if (P0 == AltP0Swapped)
5078       return I == AltCI0 ||
5079              (I != MainOp &&
5080               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5081                                    CI->getOperand(0), CI->getOperand(1)));
5082     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5083   }
5084   return I->getOpcode() == AltOp->getOpcode();
5085 }
5086 
5087 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5088                                       ArrayRef<Value *> VectorizedVals) {
5089   ArrayRef<Value*> VL = E->Scalars;
5090 
5091   Type *ScalarTy = VL[0]->getType();
5092   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5093     ScalarTy = SI->getValueOperand()->getType();
5094   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5095     ScalarTy = CI->getOperand(0)->getType();
5096   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5097     ScalarTy = IE->getOperand(1)->getType();
5098   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5099   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5100 
5101   // If we have computed a smaller type for the expression, update VecTy so
5102   // that the costs will be accurate.
5103   if (MinBWs.count(VL[0]))
5104     VecTy = FixedVectorType::get(
5105         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5106   unsigned EntryVF = E->getVectorFactor();
5107   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5108 
5109   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5110   // FIXME: it tries to fix a problem with MSVC buildbots.
5111   TargetTransformInfo &TTIRef = *TTI;
5112   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5113                                VectorizedVals, E](InstructionCost &Cost) {
5114     DenseMap<Value *, int> ExtractVectorsTys;
5115     SmallPtrSet<Value *, 4> CheckedExtracts;
5116     for (auto *V : VL) {
5117       if (isa<UndefValue>(V))
5118         continue;
5119       // If all users of instruction are going to be vectorized and this
5120       // instruction itself is not going to be vectorized, consider this
5121       // instruction as dead and remove its cost from the final cost of the
5122       // vectorized tree.
5123       // Also, avoid adjusting the cost for extractelements with multiple uses
5124       // in different graph entries.
5125       const TreeEntry *VE = getTreeEntry(V);
5126       if (!CheckedExtracts.insert(V).second ||
5127           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5128           (VE && VE != E))
5129         continue;
5130       auto *EE = cast<ExtractElementInst>(V);
5131       Optional<unsigned> EEIdx = getExtractIndex(EE);
5132       if (!EEIdx)
5133         continue;
5134       unsigned Idx = *EEIdx;
5135       if (TTIRef.getNumberOfParts(VecTy) !=
5136           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5137         auto It =
5138             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5139         It->getSecond() = std::min<int>(It->second, Idx);
5140       }
5141       // Take credit for instruction that will become dead.
5142       if (EE->hasOneUse()) {
5143         Instruction *Ext = EE->user_back();
5144         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5145             all_of(Ext->users(),
5146                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5147           // Use getExtractWithExtendCost() to calculate the cost of
5148           // extractelement/ext pair.
5149           Cost -=
5150               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5151                                               EE->getVectorOperandType(), Idx);
5152           // Add back the cost of s|zext which is subtracted separately.
5153           Cost += TTIRef.getCastInstrCost(
5154               Ext->getOpcode(), Ext->getType(), EE->getType(),
5155               TTI::getCastContextHint(Ext), CostKind, Ext);
5156           continue;
5157         }
5158       }
5159       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5160                                         EE->getVectorOperandType(), Idx);
5161     }
5162     // Add a cost for subvector extracts/inserts if required.
5163     for (const auto &Data : ExtractVectorsTys) {
5164       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5165       unsigned NumElts = VecTy->getNumElements();
5166       if (Data.second % NumElts == 0)
5167         continue;
5168       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5169         unsigned Idx = (Data.second / NumElts) * NumElts;
5170         unsigned EENumElts = EEVTy->getNumElements();
5171         if (Idx + NumElts <= EENumElts) {
5172           Cost +=
5173               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5174                                     EEVTy, None, Idx, VecTy);
5175         } else {
5176           // Need to round up the subvector type vectorization factor to avoid a
5177           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5178           // <= EENumElts.
5179           auto *SubVT =
5180               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5181           Cost +=
5182               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5183                                     EEVTy, None, Idx, SubVT);
5184         }
5185       } else {
5186         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5187                                       VecTy, None, 0, EEVTy);
5188       }
5189     }
5190   };
5191   if (E->State == TreeEntry::NeedToGather) {
5192     if (allConstant(VL))
5193       return 0;
5194     if (isa<InsertElementInst>(VL[0]))
5195       return InstructionCost::getInvalid();
5196     SmallVector<int> Mask;
5197     SmallVector<const TreeEntry *> Entries;
5198     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5199         isGatherShuffledEntry(E, Mask, Entries);
5200     if (Shuffle.hasValue()) {
5201       InstructionCost GatherCost = 0;
5202       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5203         // Perfect match in the graph, will reuse the previously vectorized
5204         // node. Cost is 0.
5205         LLVM_DEBUG(
5206             dbgs()
5207             << "SLP: perfect diamond match for gather bundle that starts with "
5208             << *VL.front() << ".\n");
5209         if (NeedToShuffleReuses)
5210           GatherCost =
5211               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5212                                   FinalVecTy, E->ReuseShuffleIndices);
5213       } else {
5214         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5215                           << " entries for bundle that starts with "
5216                           << *VL.front() << ".\n");
5217         // Detected that instead of gather we can emit a shuffle of single/two
5218         // previously vectorized nodes. Add the cost of the permutation rather
5219         // than gather.
5220         ::addMask(Mask, E->ReuseShuffleIndices);
5221         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5222       }
5223       return GatherCost;
5224     }
5225     if ((E->getOpcode() == Instruction::ExtractElement ||
5226          all_of(E->Scalars,
5227                 [](Value *V) {
5228                   return isa<ExtractElementInst, UndefValue>(V);
5229                 })) &&
5230         allSameType(VL)) {
5231       // Check that gather of extractelements can be represented as just a
5232       // shuffle of a single/two vectors the scalars are extracted from.
5233       SmallVector<int> Mask;
5234       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5235           isFixedVectorShuffle(VL, Mask);
5236       if (ShuffleKind.hasValue()) {
5237         // Found the bunch of extractelement instructions that must be gathered
5238         // into a vector and can be represented as a permutation elements in a
5239         // single input vector or of 2 input vectors.
5240         InstructionCost Cost =
5241             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5242         AdjustExtractsCost(Cost);
5243         if (NeedToShuffleReuses)
5244           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5245                                       FinalVecTy, E->ReuseShuffleIndices);
5246         return Cost;
5247       }
5248     }
5249     if (isSplat(VL)) {
5250       // Found the broadcasting of the single scalar, calculate the cost as the
5251       // broadcast.
5252       assert(VecTy == FinalVecTy &&
5253              "No reused scalars expected for broadcast.");
5254       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5255                                  /*Mask=*/None, /*Index=*/0,
5256                                  /*SubTp=*/nullptr, /*Args=*/VL);
5257     }
5258     InstructionCost ReuseShuffleCost = 0;
5259     if (NeedToShuffleReuses)
5260       ReuseShuffleCost = TTI->getShuffleCost(
5261           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5262     // Improve gather cost for gather of loads, if we can group some of the
5263     // loads into vector loads.
5264     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5265         !E->isAltShuffle()) {
5266       BoUpSLP::ValueSet VectorizedLoads;
5267       unsigned StartIdx = 0;
5268       unsigned VF = VL.size() / 2;
5269       unsigned VectorizedCnt = 0;
5270       unsigned ScatterVectorizeCnt = 0;
5271       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5272       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5273         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5274              Cnt += VF) {
5275           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5276           if (!VectorizedLoads.count(Slice.front()) &&
5277               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5278             SmallVector<Value *> PointerOps;
5279             OrdersType CurrentOrder;
5280             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5281                                               *SE, CurrentOrder, PointerOps);
5282             switch (LS) {
5283             case LoadsState::Vectorize:
5284             case LoadsState::ScatterVectorize:
5285               // Mark the vectorized loads so that we don't vectorize them
5286               // again.
5287               if (LS == LoadsState::Vectorize)
5288                 ++VectorizedCnt;
5289               else
5290                 ++ScatterVectorizeCnt;
5291               VectorizedLoads.insert(Slice.begin(), Slice.end());
5292               // If we vectorized initial block, no need to try to vectorize it
5293               // again.
5294               if (Cnt == StartIdx)
5295                 StartIdx += VF;
5296               break;
5297             case LoadsState::Gather:
5298               break;
5299             }
5300           }
5301         }
5302         // Check if the whole array was vectorized already - exit.
5303         if (StartIdx >= VL.size())
5304           break;
5305         // Found vectorizable parts - exit.
5306         if (!VectorizedLoads.empty())
5307           break;
5308       }
5309       if (!VectorizedLoads.empty()) {
5310         InstructionCost GatherCost = 0;
5311         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5312         bool NeedInsertSubvectorAnalysis =
5313             !NumParts || (VL.size() / VF) > NumParts;
5314         // Get the cost for gathered loads.
5315         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5316           if (VectorizedLoads.contains(VL[I]))
5317             continue;
5318           GatherCost += getGatherCost(VL.slice(I, VF));
5319         }
5320         // The cost for vectorized loads.
5321         InstructionCost ScalarsCost = 0;
5322         for (Value *V : VectorizedLoads) {
5323           auto *LI = cast<LoadInst>(V);
5324           ScalarsCost += TTI->getMemoryOpCost(
5325               Instruction::Load, LI->getType(), LI->getAlign(),
5326               LI->getPointerAddressSpace(), CostKind, LI);
5327         }
5328         auto *LI = cast<LoadInst>(E->getMainOp());
5329         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5330         Align Alignment = LI->getAlign();
5331         GatherCost +=
5332             VectorizedCnt *
5333             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5334                                  LI->getPointerAddressSpace(), CostKind, LI);
5335         GatherCost += ScatterVectorizeCnt *
5336                       TTI->getGatherScatterOpCost(
5337                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5338                           /*VariableMask=*/false, Alignment, CostKind, LI);
5339         if (NeedInsertSubvectorAnalysis) {
5340           // Add the cost for the subvectors insert.
5341           for (int I = VF, E = VL.size(); I < E; I += VF)
5342             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5343                                               None, I, LoadTy);
5344         }
5345         return ReuseShuffleCost + GatherCost - ScalarsCost;
5346       }
5347     }
5348     return ReuseShuffleCost + getGatherCost(VL);
5349   }
5350   InstructionCost CommonCost = 0;
5351   SmallVector<int> Mask;
5352   if (!E->ReorderIndices.empty()) {
5353     SmallVector<int> NewMask;
5354     if (E->getOpcode() == Instruction::Store) {
5355       // For stores the order is actually a mask.
5356       NewMask.resize(E->ReorderIndices.size());
5357       copy(E->ReorderIndices, NewMask.begin());
5358     } else {
5359       inversePermutation(E->ReorderIndices, NewMask);
5360     }
5361     ::addMask(Mask, NewMask);
5362   }
5363   if (NeedToShuffleReuses)
5364     ::addMask(Mask, E->ReuseShuffleIndices);
5365   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5366     CommonCost =
5367         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5368   assert((E->State == TreeEntry::Vectorize ||
5369           E->State == TreeEntry::ScatterVectorize) &&
5370          "Unhandled state");
5371   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5372   Instruction *VL0 = E->getMainOp();
5373   unsigned ShuffleOrOp =
5374       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5375   switch (ShuffleOrOp) {
5376     case Instruction::PHI:
5377       return 0;
5378 
5379     case Instruction::ExtractValue:
5380     case Instruction::ExtractElement: {
5381       // The common cost of removal ExtractElement/ExtractValue instructions +
5382       // the cost of shuffles, if required to resuffle the original vector.
5383       if (NeedToShuffleReuses) {
5384         unsigned Idx = 0;
5385         for (unsigned I : E->ReuseShuffleIndices) {
5386           if (ShuffleOrOp == Instruction::ExtractElement) {
5387             auto *EE = cast<ExtractElementInst>(VL[I]);
5388             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5389                                                   EE->getVectorOperandType(),
5390                                                   *getExtractIndex(EE));
5391           } else {
5392             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5393                                                   VecTy, Idx);
5394             ++Idx;
5395           }
5396         }
5397         Idx = EntryVF;
5398         for (Value *V : VL) {
5399           if (ShuffleOrOp == Instruction::ExtractElement) {
5400             auto *EE = cast<ExtractElementInst>(V);
5401             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5402                                                   EE->getVectorOperandType(),
5403                                                   *getExtractIndex(EE));
5404           } else {
5405             --Idx;
5406             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5407                                                   VecTy, Idx);
5408           }
5409         }
5410       }
5411       if (ShuffleOrOp == Instruction::ExtractValue) {
5412         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5413           auto *EI = cast<Instruction>(VL[I]);
5414           // Take credit for instruction that will become dead.
5415           if (EI->hasOneUse()) {
5416             Instruction *Ext = EI->user_back();
5417             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5418                 all_of(Ext->users(),
5419                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5420               // Use getExtractWithExtendCost() to calculate the cost of
5421               // extractelement/ext pair.
5422               CommonCost -= TTI->getExtractWithExtendCost(
5423                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5424               // Add back the cost of s|zext which is subtracted separately.
5425               CommonCost += TTI->getCastInstrCost(
5426                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5427                   TTI::getCastContextHint(Ext), CostKind, Ext);
5428               continue;
5429             }
5430           }
5431           CommonCost -=
5432               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5433         }
5434       } else {
5435         AdjustExtractsCost(CommonCost);
5436       }
5437       return CommonCost;
5438     }
5439     case Instruction::InsertElement: {
5440       assert(E->ReuseShuffleIndices.empty() &&
5441              "Unique insertelements only are expected.");
5442       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5443 
5444       unsigned const NumElts = SrcVecTy->getNumElements();
5445       unsigned const NumScalars = VL.size();
5446       APInt DemandedElts = APInt::getZero(NumElts);
5447       // TODO: Add support for Instruction::InsertValue.
5448       SmallVector<int> Mask;
5449       if (!E->ReorderIndices.empty()) {
5450         inversePermutation(E->ReorderIndices, Mask);
5451         Mask.append(NumElts - NumScalars, UndefMaskElem);
5452       } else {
5453         Mask.assign(NumElts, UndefMaskElem);
5454         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5455       }
5456       unsigned Offset = *getInsertIndex(VL0);
5457       bool IsIdentity = true;
5458       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5459       Mask.swap(PrevMask);
5460       for (unsigned I = 0; I < NumScalars; ++I) {
5461         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5462         DemandedElts.setBit(InsertIdx);
5463         IsIdentity &= InsertIdx - Offset == I;
5464         Mask[InsertIdx - Offset] = I;
5465       }
5466       assert(Offset < NumElts && "Failed to find vector index offset");
5467 
5468       InstructionCost Cost = 0;
5469       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5470                                             /*Insert*/ true, /*Extract*/ false);
5471 
5472       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5473         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5474         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5475         Cost += TTI->getShuffleCost(
5476             TargetTransformInfo::SK_PermuteSingleSrc,
5477             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5478       } else if (!IsIdentity) {
5479         auto *FirstInsert =
5480             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5481               return !is_contained(E->Scalars,
5482                                    cast<Instruction>(V)->getOperand(0));
5483             }));
5484         if (isUndefVector(FirstInsert->getOperand(0))) {
5485           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5486         } else {
5487           SmallVector<int> InsertMask(NumElts);
5488           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5489           for (unsigned I = 0; I < NumElts; I++) {
5490             if (Mask[I] != UndefMaskElem)
5491               InsertMask[Offset + I] = NumElts + I;
5492           }
5493           Cost +=
5494               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5495         }
5496       }
5497 
5498       return Cost;
5499     }
5500     case Instruction::ZExt:
5501     case Instruction::SExt:
5502     case Instruction::FPToUI:
5503     case Instruction::FPToSI:
5504     case Instruction::FPExt:
5505     case Instruction::PtrToInt:
5506     case Instruction::IntToPtr:
5507     case Instruction::SIToFP:
5508     case Instruction::UIToFP:
5509     case Instruction::Trunc:
5510     case Instruction::FPTrunc:
5511     case Instruction::BitCast: {
5512       Type *SrcTy = VL0->getOperand(0)->getType();
5513       InstructionCost ScalarEltCost =
5514           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5515                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5516       if (NeedToShuffleReuses) {
5517         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5518       }
5519 
5520       // Calculate the cost of this instruction.
5521       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5522 
5523       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5524       InstructionCost VecCost = 0;
5525       // Check if the values are candidates to demote.
5526       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5527         VecCost = CommonCost + TTI->getCastInstrCost(
5528                                    E->getOpcode(), VecTy, SrcVecTy,
5529                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5530       }
5531       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5532       return VecCost - ScalarCost;
5533     }
5534     case Instruction::FCmp:
5535     case Instruction::ICmp:
5536     case Instruction::Select: {
5537       // Calculate the cost of this instruction.
5538       InstructionCost ScalarEltCost =
5539           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5540                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5541       if (NeedToShuffleReuses) {
5542         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5543       }
5544       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5545       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5546 
5547       // Check if all entries in VL are either compares or selects with compares
5548       // as condition that have the same predicates.
5549       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5550       bool First = true;
5551       for (auto *V : VL) {
5552         CmpInst::Predicate CurrentPred;
5553         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5554         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5555              !match(V, MatchCmp)) ||
5556             (!First && VecPred != CurrentPred)) {
5557           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5558           break;
5559         }
5560         First = false;
5561         VecPred = CurrentPred;
5562       }
5563 
5564       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5565           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5566       // Check if it is possible and profitable to use min/max for selects in
5567       // VL.
5568       //
5569       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5570       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5571         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5572                                           {VecTy, VecTy});
5573         InstructionCost IntrinsicCost =
5574             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5575         // If the selects are the only uses of the compares, they will be dead
5576         // and we can adjust the cost by removing their cost.
5577         if (IntrinsicAndUse.second)
5578           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5579                                                    MaskTy, VecPred, CostKind);
5580         VecCost = std::min(VecCost, IntrinsicCost);
5581       }
5582       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5583       return CommonCost + VecCost - ScalarCost;
5584     }
5585     case Instruction::FNeg:
5586     case Instruction::Add:
5587     case Instruction::FAdd:
5588     case Instruction::Sub:
5589     case Instruction::FSub:
5590     case Instruction::Mul:
5591     case Instruction::FMul:
5592     case Instruction::UDiv:
5593     case Instruction::SDiv:
5594     case Instruction::FDiv:
5595     case Instruction::URem:
5596     case Instruction::SRem:
5597     case Instruction::FRem:
5598     case Instruction::Shl:
5599     case Instruction::LShr:
5600     case Instruction::AShr:
5601     case Instruction::And:
5602     case Instruction::Or:
5603     case Instruction::Xor: {
5604       // Certain instructions can be cheaper to vectorize if they have a
5605       // constant second vector operand.
5606       TargetTransformInfo::OperandValueKind Op1VK =
5607           TargetTransformInfo::OK_AnyValue;
5608       TargetTransformInfo::OperandValueKind Op2VK =
5609           TargetTransformInfo::OK_UniformConstantValue;
5610       TargetTransformInfo::OperandValueProperties Op1VP =
5611           TargetTransformInfo::OP_None;
5612       TargetTransformInfo::OperandValueProperties Op2VP =
5613           TargetTransformInfo::OP_PowerOf2;
5614 
5615       // If all operands are exactly the same ConstantInt then set the
5616       // operand kind to OK_UniformConstantValue.
5617       // If instead not all operands are constants, then set the operand kind
5618       // to OK_AnyValue. If all operands are constants but not the same,
5619       // then set the operand kind to OK_NonUniformConstantValue.
5620       ConstantInt *CInt0 = nullptr;
5621       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5622         const Instruction *I = cast<Instruction>(VL[i]);
5623         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5624         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5625         if (!CInt) {
5626           Op2VK = TargetTransformInfo::OK_AnyValue;
5627           Op2VP = TargetTransformInfo::OP_None;
5628           break;
5629         }
5630         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5631             !CInt->getValue().isPowerOf2())
5632           Op2VP = TargetTransformInfo::OP_None;
5633         if (i == 0) {
5634           CInt0 = CInt;
5635           continue;
5636         }
5637         if (CInt0 != CInt)
5638           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5639       }
5640 
5641       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5642       InstructionCost ScalarEltCost =
5643           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5644                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5645       if (NeedToShuffleReuses) {
5646         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5647       }
5648       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5649       InstructionCost VecCost =
5650           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5651                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5652       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5653       return CommonCost + VecCost - ScalarCost;
5654     }
5655     case Instruction::GetElementPtr: {
5656       TargetTransformInfo::OperandValueKind Op1VK =
5657           TargetTransformInfo::OK_AnyValue;
5658       TargetTransformInfo::OperandValueKind Op2VK =
5659           TargetTransformInfo::OK_UniformConstantValue;
5660 
5661       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5662           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5663       if (NeedToShuffleReuses) {
5664         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5665       }
5666       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5667       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5668           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5669       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5670       return CommonCost + VecCost - ScalarCost;
5671     }
5672     case Instruction::Load: {
5673       // Cost of wide load - cost of scalar loads.
5674       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5675       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5676           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5677       if (NeedToShuffleReuses) {
5678         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5679       }
5680       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5681       InstructionCost VecLdCost;
5682       if (E->State == TreeEntry::Vectorize) {
5683         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5684                                          CostKind, VL0);
5685       } else {
5686         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5687         Align CommonAlignment = Alignment;
5688         for (Value *V : VL)
5689           CommonAlignment =
5690               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5691         VecLdCost = TTI->getGatherScatterOpCost(
5692             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5693             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5694       }
5695       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5696       return CommonCost + VecLdCost - ScalarLdCost;
5697     }
5698     case Instruction::Store: {
5699       // We know that we can merge the stores. Calculate the cost.
5700       bool IsReorder = !E->ReorderIndices.empty();
5701       auto *SI =
5702           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5703       Align Alignment = SI->getAlign();
5704       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5705           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5706       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5707       InstructionCost VecStCost = TTI->getMemoryOpCost(
5708           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5709       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5710       return CommonCost + VecStCost - ScalarStCost;
5711     }
5712     case Instruction::Call: {
5713       CallInst *CI = cast<CallInst>(VL0);
5714       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5715 
5716       // Calculate the cost of the scalar and vector calls.
5717       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5718       InstructionCost ScalarEltCost =
5719           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5720       if (NeedToShuffleReuses) {
5721         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5722       }
5723       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5724 
5725       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5726       InstructionCost VecCallCost =
5727           std::min(VecCallCosts.first, VecCallCosts.second);
5728 
5729       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5730                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5731                         << " for " << *CI << "\n");
5732 
5733       return CommonCost + VecCallCost - ScalarCallCost;
5734     }
5735     case Instruction::ShuffleVector: {
5736       assert(E->isAltShuffle() &&
5737              ((Instruction::isBinaryOp(E->getOpcode()) &&
5738                Instruction::isBinaryOp(E->getAltOpcode())) ||
5739               (Instruction::isCast(E->getOpcode()) &&
5740                Instruction::isCast(E->getAltOpcode())) ||
5741               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5742              "Invalid Shuffle Vector Operand");
5743       InstructionCost ScalarCost = 0;
5744       if (NeedToShuffleReuses) {
5745         for (unsigned Idx : E->ReuseShuffleIndices) {
5746           Instruction *I = cast<Instruction>(VL[Idx]);
5747           CommonCost -= TTI->getInstructionCost(I, CostKind);
5748         }
5749         for (Value *V : VL) {
5750           Instruction *I = cast<Instruction>(V);
5751           CommonCost += TTI->getInstructionCost(I, CostKind);
5752         }
5753       }
5754       for (Value *V : VL) {
5755         Instruction *I = cast<Instruction>(V);
5756         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5757         ScalarCost += TTI->getInstructionCost(I, CostKind);
5758       }
5759       // VecCost is equal to sum of the cost of creating 2 vectors
5760       // and the cost of creating shuffle.
5761       InstructionCost VecCost = 0;
5762       // Try to find the previous shuffle node with the same operands and same
5763       // main/alternate ops.
5764       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5765         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5766           if (TE.get() == E)
5767             break;
5768           if (TE->isAltShuffle() &&
5769               ((TE->getOpcode() == E->getOpcode() &&
5770                 TE->getAltOpcode() == E->getAltOpcode()) ||
5771                (TE->getOpcode() == E->getAltOpcode() &&
5772                 TE->getAltOpcode() == E->getOpcode())) &&
5773               TE->hasEqualOperands(*E))
5774             return true;
5775         }
5776         return false;
5777       };
5778       if (TryFindNodeWithEqualOperands()) {
5779         LLVM_DEBUG({
5780           dbgs() << "SLP: diamond match for alternate node found.\n";
5781           E->dump();
5782         });
5783         // No need to add new vector costs here since we're going to reuse
5784         // same main/alternate vector ops, just do different shuffling.
5785       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5786         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5787         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5788                                                CostKind);
5789       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5790         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5791                                           Builder.getInt1Ty(),
5792                                           CI0->getPredicate(), CostKind, VL0);
5793         VecCost += TTI->getCmpSelInstrCost(
5794             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5795             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5796             E->getAltOp());
5797       } else {
5798         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5799         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5800         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5801         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5802         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5803                                         TTI::CastContextHint::None, CostKind);
5804         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5805                                          TTI::CastContextHint::None, CostKind);
5806       }
5807 
5808       SmallVector<int> Mask;
5809       buildShuffleEntryMask(
5810           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5811           [E](Instruction *I) {
5812             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5813             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5814           },
5815           Mask);
5816       CommonCost =
5817           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5818       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5819       return CommonCost + VecCost - ScalarCost;
5820     }
5821     default:
5822       llvm_unreachable("Unknown instruction");
5823   }
5824 }
5825 
5826 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5827   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5828                     << VectorizableTree.size() << " is fully vectorizable .\n");
5829 
5830   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5831     SmallVector<int> Mask;
5832     return TE->State == TreeEntry::NeedToGather &&
5833            !any_of(TE->Scalars,
5834                    [this](Value *V) { return EphValues.contains(V); }) &&
5835            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5836             TE->Scalars.size() < Limit ||
5837             ((TE->getOpcode() == Instruction::ExtractElement ||
5838               all_of(TE->Scalars,
5839                      [](Value *V) {
5840                        return isa<ExtractElementInst, UndefValue>(V);
5841                      })) &&
5842              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5843             (TE->State == TreeEntry::NeedToGather &&
5844              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5845   };
5846 
5847   // We only handle trees of heights 1 and 2.
5848   if (VectorizableTree.size() == 1 &&
5849       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5850        (ForReduction &&
5851         AreVectorizableGathers(VectorizableTree[0].get(),
5852                                VectorizableTree[0]->Scalars.size()) &&
5853         VectorizableTree[0]->getVectorFactor() > 2)))
5854     return true;
5855 
5856   if (VectorizableTree.size() != 2)
5857     return false;
5858 
5859   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5860   // with the second gather nodes if they have less scalar operands rather than
5861   // the initial tree element (may be profitable to shuffle the second gather)
5862   // or they are extractelements, which form shuffle.
5863   SmallVector<int> Mask;
5864   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5865       AreVectorizableGathers(VectorizableTree[1].get(),
5866                              VectorizableTree[0]->Scalars.size()))
5867     return true;
5868 
5869   // Gathering cost would be too much for tiny trees.
5870   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5871       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5872        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5873     return false;
5874 
5875   return true;
5876 }
5877 
5878 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5879                                        TargetTransformInfo *TTI,
5880                                        bool MustMatchOrInst) {
5881   // Look past the root to find a source value. Arbitrarily follow the
5882   // path through operand 0 of any 'or'. Also, peek through optional
5883   // shift-left-by-multiple-of-8-bits.
5884   Value *ZextLoad = Root;
5885   const APInt *ShAmtC;
5886   bool FoundOr = false;
5887   while (!isa<ConstantExpr>(ZextLoad) &&
5888          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5889           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5890            ShAmtC->urem(8) == 0))) {
5891     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5892     ZextLoad = BinOp->getOperand(0);
5893     if (BinOp->getOpcode() == Instruction::Or)
5894       FoundOr = true;
5895   }
5896   // Check if the input is an extended load of the required or/shift expression.
5897   Value *Load;
5898   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5899       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5900     return false;
5901 
5902   // Require that the total load bit width is a legal integer type.
5903   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5904   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5905   Type *SrcTy = Load->getType();
5906   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5907   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5908     return false;
5909 
5910   // Everything matched - assume that we can fold the whole sequence using
5911   // load combining.
5912   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5913              << *(cast<Instruction>(Root)) << "\n");
5914 
5915   return true;
5916 }
5917 
5918 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5919   if (RdxKind != RecurKind::Or)
5920     return false;
5921 
5922   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5923   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5924   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5925                                     /* MatchOr */ false);
5926 }
5927 
5928 bool BoUpSLP::isLoadCombineCandidate() const {
5929   // Peek through a final sequence of stores and check if all operations are
5930   // likely to be load-combined.
5931   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5932   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5933     Value *X;
5934     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5935         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5936       return false;
5937   }
5938   return true;
5939 }
5940 
5941 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5942   // No need to vectorize inserts of gathered values.
5943   if (VectorizableTree.size() == 2 &&
5944       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5945       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5946     return true;
5947 
5948   // We can vectorize the tree if its size is greater than or equal to the
5949   // minimum size specified by the MinTreeSize command line option.
5950   if (VectorizableTree.size() >= MinTreeSize)
5951     return false;
5952 
5953   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5954   // can vectorize it if we can prove it fully vectorizable.
5955   if (isFullyVectorizableTinyTree(ForReduction))
5956     return false;
5957 
5958   assert(VectorizableTree.empty()
5959              ? ExternalUses.empty()
5960              : true && "We shouldn't have any external users");
5961 
5962   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5963   // vectorizable.
5964   return true;
5965 }
5966 
5967 InstructionCost BoUpSLP::getSpillCost() const {
5968   // Walk from the bottom of the tree to the top, tracking which values are
5969   // live. When we see a call instruction that is not part of our tree,
5970   // query TTI to see if there is a cost to keeping values live over it
5971   // (for example, if spills and fills are required).
5972   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5973   InstructionCost Cost = 0;
5974 
5975   SmallPtrSet<Instruction*, 4> LiveValues;
5976   Instruction *PrevInst = nullptr;
5977 
5978   // The entries in VectorizableTree are not necessarily ordered by their
5979   // position in basic blocks. Collect them and order them by dominance so later
5980   // instructions are guaranteed to be visited first. For instructions in
5981   // different basic blocks, we only scan to the beginning of the block, so
5982   // their order does not matter, as long as all instructions in a basic block
5983   // are grouped together. Using dominance ensures a deterministic order.
5984   SmallVector<Instruction *, 16> OrderedScalars;
5985   for (const auto &TEPtr : VectorizableTree) {
5986     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5987     if (!Inst)
5988       continue;
5989     OrderedScalars.push_back(Inst);
5990   }
5991   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5992     auto *NodeA = DT->getNode(A->getParent());
5993     auto *NodeB = DT->getNode(B->getParent());
5994     assert(NodeA && "Should only process reachable instructions");
5995     assert(NodeB && "Should only process reachable instructions");
5996     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5997            "Different nodes should have different DFS numbers");
5998     if (NodeA != NodeB)
5999       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6000     return B->comesBefore(A);
6001   });
6002 
6003   for (Instruction *Inst : OrderedScalars) {
6004     if (!PrevInst) {
6005       PrevInst = Inst;
6006       continue;
6007     }
6008 
6009     // Update LiveValues.
6010     LiveValues.erase(PrevInst);
6011     for (auto &J : PrevInst->operands()) {
6012       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6013         LiveValues.insert(cast<Instruction>(&*J));
6014     }
6015 
6016     LLVM_DEBUG({
6017       dbgs() << "SLP: #LV: " << LiveValues.size();
6018       for (auto *X : LiveValues)
6019         dbgs() << " " << X->getName();
6020       dbgs() << ", Looking at ";
6021       Inst->dump();
6022     });
6023 
6024     // Now find the sequence of instructions between PrevInst and Inst.
6025     unsigned NumCalls = 0;
6026     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6027                                  PrevInstIt =
6028                                      PrevInst->getIterator().getReverse();
6029     while (InstIt != PrevInstIt) {
6030       if (PrevInstIt == PrevInst->getParent()->rend()) {
6031         PrevInstIt = Inst->getParent()->rbegin();
6032         continue;
6033       }
6034 
6035       // Debug information does not impact spill cost.
6036       if ((isa<CallInst>(&*PrevInstIt) &&
6037            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6038           &*PrevInstIt != PrevInst)
6039         NumCalls++;
6040 
6041       ++PrevInstIt;
6042     }
6043 
6044     if (NumCalls) {
6045       SmallVector<Type*, 4> V;
6046       for (auto *II : LiveValues) {
6047         auto *ScalarTy = II->getType();
6048         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6049           ScalarTy = VectorTy->getElementType();
6050         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6051       }
6052       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6053     }
6054 
6055     PrevInst = Inst;
6056   }
6057 
6058   return Cost;
6059 }
6060 
6061 /// Check if two insertelement instructions are from the same buildvector.
6062 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6063                                             InsertElementInst *V) {
6064   // Instructions must be from the same basic blocks.
6065   if (VU->getParent() != V->getParent())
6066     return false;
6067   // Checks if 2 insertelements are from the same buildvector.
6068   if (VU->getType() != V->getType())
6069     return false;
6070   // Multiple used inserts are separate nodes.
6071   if (!VU->hasOneUse() && !V->hasOneUse())
6072     return false;
6073   auto *IE1 = VU;
6074   auto *IE2 = V;
6075   // Go through the vector operand of insertelement instructions trying to find
6076   // either VU as the original vector for IE2 or V as the original vector for
6077   // IE1.
6078   do {
6079     if (IE2 == VU || IE1 == V)
6080       return true;
6081     if (IE1) {
6082       if (IE1 != VU && !IE1->hasOneUse())
6083         IE1 = nullptr;
6084       else
6085         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6086     }
6087     if (IE2) {
6088       if (IE2 != V && !IE2->hasOneUse())
6089         IE2 = nullptr;
6090       else
6091         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6092     }
6093   } while (IE1 || IE2);
6094   return false;
6095 }
6096 
6097 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6098   InstructionCost Cost = 0;
6099   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6100                     << VectorizableTree.size() << ".\n");
6101 
6102   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6103 
6104   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6105     TreeEntry &TE = *VectorizableTree[I];
6106 
6107     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6108     Cost += C;
6109     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6110                       << " for bundle that starts with " << *TE.Scalars[0]
6111                       << ".\n"
6112                       << "SLP: Current total cost = " << Cost << "\n");
6113   }
6114 
6115   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6116   InstructionCost ExtractCost = 0;
6117   SmallVector<unsigned> VF;
6118   SmallVector<SmallVector<int>> ShuffleMask;
6119   SmallVector<Value *> FirstUsers;
6120   SmallVector<APInt> DemandedElts;
6121   for (ExternalUser &EU : ExternalUses) {
6122     // We only add extract cost once for the same scalar.
6123     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6124         !ExtractCostCalculated.insert(EU.Scalar).second)
6125       continue;
6126 
6127     // Uses by ephemeral values are free (because the ephemeral value will be
6128     // removed prior to code generation, and so the extraction will be
6129     // removed as well).
6130     if (EphValues.count(EU.User))
6131       continue;
6132 
6133     // No extract cost for vector "scalar"
6134     if (isa<FixedVectorType>(EU.Scalar->getType()))
6135       continue;
6136 
6137     // Already counted the cost for external uses when tried to adjust the cost
6138     // for extractelements, no need to add it again.
6139     if (isa<ExtractElementInst>(EU.Scalar))
6140       continue;
6141 
6142     // If found user is an insertelement, do not calculate extract cost but try
6143     // to detect it as a final shuffled/identity match.
6144     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6145       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6146         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6147         if (InsertIdx) {
6148           auto *It = find_if(FirstUsers, [VU](Value *V) {
6149             return areTwoInsertFromSameBuildVector(VU,
6150                                                    cast<InsertElementInst>(V));
6151           });
6152           int VecId = -1;
6153           if (It == FirstUsers.end()) {
6154             VF.push_back(FTy->getNumElements());
6155             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6156             // Find the insertvector, vectorized in tree, if any.
6157             Value *Base = VU;
6158             while (isa<InsertElementInst>(Base)) {
6159               // Build the mask for the vectorized insertelement instructions.
6160               if (const TreeEntry *E = getTreeEntry(Base)) {
6161                 VU = cast<InsertElementInst>(Base);
6162                 do {
6163                   int Idx = E->findLaneForValue(Base);
6164                   ShuffleMask.back()[Idx] = Idx;
6165                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6166                 } while (E == getTreeEntry(Base));
6167                 break;
6168               }
6169               Base = cast<InsertElementInst>(Base)->getOperand(0);
6170             }
6171             FirstUsers.push_back(VU);
6172             DemandedElts.push_back(APInt::getZero(VF.back()));
6173             VecId = FirstUsers.size() - 1;
6174           } else {
6175             VecId = std::distance(FirstUsers.begin(), It);
6176           }
6177           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6178           DemandedElts[VecId].setBit(*InsertIdx);
6179           continue;
6180         }
6181       }
6182     }
6183 
6184     // If we plan to rewrite the tree in a smaller type, we will need to sign
6185     // extend the extracted value back to the original type. Here, we account
6186     // for the extract and the added cost of the sign extend if needed.
6187     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6188     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6189     if (MinBWs.count(ScalarRoot)) {
6190       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6191       auto Extend =
6192           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6193       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6194       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6195                                                    VecTy, EU.Lane);
6196     } else {
6197       ExtractCost +=
6198           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6199     }
6200   }
6201 
6202   InstructionCost SpillCost = getSpillCost();
6203   Cost += SpillCost + ExtractCost;
6204   if (FirstUsers.size() == 1) {
6205     int Limit = ShuffleMask.front().size() * 2;
6206     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6207         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6208       InstructionCost C = TTI->getShuffleCost(
6209           TTI::SK_PermuteSingleSrc,
6210           cast<FixedVectorType>(FirstUsers.front()->getType()),
6211           ShuffleMask.front());
6212       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6213                         << " for final shuffle of insertelement external users "
6214                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6215                         << "SLP: Current total cost = " << Cost << "\n");
6216       Cost += C;
6217     }
6218     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6219         cast<FixedVectorType>(FirstUsers.front()->getType()),
6220         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6221     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6222                       << " for insertelements gather.\n"
6223                       << "SLP: Current total cost = " << Cost << "\n");
6224     Cost -= InsertCost;
6225   } else if (FirstUsers.size() >= 2) {
6226     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6227     // Combined masks of the first 2 vectors.
6228     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6229     copy(ShuffleMask.front(), CombinedMask.begin());
6230     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6231     auto *VecTy = FixedVectorType::get(
6232         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6233         MaxVF);
6234     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6235       if (ShuffleMask[1][I] != UndefMaskElem) {
6236         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6237         CombinedDemandedElts.setBit(I);
6238       }
6239     }
6240     InstructionCost C =
6241         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6242     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6243                       << " for final shuffle of vector node and external "
6244                          "insertelement users "
6245                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6246                       << "SLP: Current total cost = " << Cost << "\n");
6247     Cost += C;
6248     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6249         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6250     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6251                       << " for insertelements gather.\n"
6252                       << "SLP: Current total cost = " << Cost << "\n");
6253     Cost -= InsertCost;
6254     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6255       // Other elements - permutation of 2 vectors (the initial one and the
6256       // next Ith incoming vector).
6257       unsigned VF = ShuffleMask[I].size();
6258       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6259         int Mask = ShuffleMask[I][Idx];
6260         if (Mask != UndefMaskElem)
6261           CombinedMask[Idx] = MaxVF + Mask;
6262         else if (CombinedMask[Idx] != UndefMaskElem)
6263           CombinedMask[Idx] = Idx;
6264       }
6265       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6266         if (CombinedMask[Idx] != UndefMaskElem)
6267           CombinedMask[Idx] = Idx;
6268       InstructionCost C =
6269           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6270       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6271                         << " for final shuffle of vector node and external "
6272                            "insertelement users "
6273                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6274                         << "SLP: Current total cost = " << Cost << "\n");
6275       Cost += C;
6276       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6277           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6278           /*Insert*/ true, /*Extract*/ false);
6279       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6280                         << " for insertelements gather.\n"
6281                         << "SLP: Current total cost = " << Cost << "\n");
6282       Cost -= InsertCost;
6283     }
6284   }
6285 
6286 #ifndef NDEBUG
6287   SmallString<256> Str;
6288   {
6289     raw_svector_ostream OS(Str);
6290     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6291        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6292        << "SLP: Total Cost = " << Cost << ".\n";
6293   }
6294   LLVM_DEBUG(dbgs() << Str);
6295   if (ViewSLPTree)
6296     ViewGraph(this, "SLP" + F->getName(), false, Str);
6297 #endif
6298 
6299   return Cost;
6300 }
6301 
6302 Optional<TargetTransformInfo::ShuffleKind>
6303 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6304                                SmallVectorImpl<const TreeEntry *> &Entries) {
6305   // TODO: currently checking only for Scalars in the tree entry, need to count
6306   // reused elements too for better cost estimation.
6307   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6308   Entries.clear();
6309   // Build a lists of values to tree entries.
6310   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6311   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6312     if (EntryPtr.get() == TE)
6313       break;
6314     if (EntryPtr->State != TreeEntry::NeedToGather)
6315       continue;
6316     for (Value *V : EntryPtr->Scalars)
6317       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6318   }
6319   // Find all tree entries used by the gathered values. If no common entries
6320   // found - not a shuffle.
6321   // Here we build a set of tree nodes for each gathered value and trying to
6322   // find the intersection between these sets. If we have at least one common
6323   // tree node for each gathered value - we have just a permutation of the
6324   // single vector. If we have 2 different sets, we're in situation where we
6325   // have a permutation of 2 input vectors.
6326   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6327   DenseMap<Value *, int> UsedValuesEntry;
6328   for (Value *V : TE->Scalars) {
6329     if (isa<UndefValue>(V))
6330       continue;
6331     // Build a list of tree entries where V is used.
6332     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6333     auto It = ValueToTEs.find(V);
6334     if (It != ValueToTEs.end())
6335       VToTEs = It->second;
6336     if (const TreeEntry *VTE = getTreeEntry(V))
6337       VToTEs.insert(VTE);
6338     if (VToTEs.empty())
6339       return None;
6340     if (UsedTEs.empty()) {
6341       // The first iteration, just insert the list of nodes to vector.
6342       UsedTEs.push_back(VToTEs);
6343     } else {
6344       // Need to check if there are any previously used tree nodes which use V.
6345       // If there are no such nodes, consider that we have another one input
6346       // vector.
6347       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6348       unsigned Idx = 0;
6349       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6350         // Do we have a non-empty intersection of previously listed tree entries
6351         // and tree entries using current V?
6352         set_intersect(VToTEs, Set);
6353         if (!VToTEs.empty()) {
6354           // Yes, write the new subset and continue analysis for the next
6355           // scalar.
6356           Set.swap(VToTEs);
6357           break;
6358         }
6359         VToTEs = SavedVToTEs;
6360         ++Idx;
6361       }
6362       // No non-empty intersection found - need to add a second set of possible
6363       // source vectors.
6364       if (Idx == UsedTEs.size()) {
6365         // If the number of input vectors is greater than 2 - not a permutation,
6366         // fallback to the regular gather.
6367         if (UsedTEs.size() == 2)
6368           return None;
6369         UsedTEs.push_back(SavedVToTEs);
6370         Idx = UsedTEs.size() - 1;
6371       }
6372       UsedValuesEntry.try_emplace(V, Idx);
6373     }
6374   }
6375 
6376   unsigned VF = 0;
6377   if (UsedTEs.size() == 1) {
6378     // Try to find the perfect match in another gather node at first.
6379     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6380       return EntryPtr->isSame(TE->Scalars);
6381     });
6382     if (It != UsedTEs.front().end()) {
6383       Entries.push_back(*It);
6384       std::iota(Mask.begin(), Mask.end(), 0);
6385       return TargetTransformInfo::SK_PermuteSingleSrc;
6386     }
6387     // No perfect match, just shuffle, so choose the first tree node.
6388     Entries.push_back(*UsedTEs.front().begin());
6389   } else {
6390     // Try to find nodes with the same vector factor.
6391     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6392     DenseMap<int, const TreeEntry *> VFToTE;
6393     for (const TreeEntry *TE : UsedTEs.front())
6394       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6395     for (const TreeEntry *TE : UsedTEs.back()) {
6396       auto It = VFToTE.find(TE->getVectorFactor());
6397       if (It != VFToTE.end()) {
6398         VF = It->first;
6399         Entries.push_back(It->second);
6400         Entries.push_back(TE);
6401         break;
6402       }
6403     }
6404     // No 2 source vectors with the same vector factor - give up and do regular
6405     // gather.
6406     if (Entries.empty())
6407       return None;
6408   }
6409 
6410   // Build a shuffle mask for better cost estimation and vector emission.
6411   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6412     Value *V = TE->Scalars[I];
6413     if (isa<UndefValue>(V))
6414       continue;
6415     unsigned Idx = UsedValuesEntry.lookup(V);
6416     const TreeEntry *VTE = Entries[Idx];
6417     int FoundLane = VTE->findLaneForValue(V);
6418     Mask[I] = Idx * VF + FoundLane;
6419     // Extra check required by isSingleSourceMaskImpl function (called by
6420     // ShuffleVectorInst::isSingleSourceMask).
6421     if (Mask[I] >= 2 * E)
6422       return None;
6423   }
6424   switch (Entries.size()) {
6425   case 1:
6426     return TargetTransformInfo::SK_PermuteSingleSrc;
6427   case 2:
6428     return TargetTransformInfo::SK_PermuteTwoSrc;
6429   default:
6430     break;
6431   }
6432   return None;
6433 }
6434 
6435 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6436                                        const APInt &ShuffledIndices,
6437                                        bool NeedToShuffle) const {
6438   InstructionCost Cost =
6439       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6440                                     /*Extract*/ false);
6441   if (NeedToShuffle)
6442     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6443   return Cost;
6444 }
6445 
6446 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6447   // Find the type of the operands in VL.
6448   Type *ScalarTy = VL[0]->getType();
6449   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6450     ScalarTy = SI->getValueOperand()->getType();
6451   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6452   bool DuplicateNonConst = false;
6453   // Find the cost of inserting/extracting values from the vector.
6454   // Check if the same elements are inserted several times and count them as
6455   // shuffle candidates.
6456   APInt ShuffledElements = APInt::getZero(VL.size());
6457   DenseSet<Value *> UniqueElements;
6458   // Iterate in reverse order to consider insert elements with the high cost.
6459   for (unsigned I = VL.size(); I > 0; --I) {
6460     unsigned Idx = I - 1;
6461     // No need to shuffle duplicates for constants.
6462     if (isConstant(VL[Idx])) {
6463       ShuffledElements.setBit(Idx);
6464       continue;
6465     }
6466     if (!UniqueElements.insert(VL[Idx]).second) {
6467       DuplicateNonConst = true;
6468       ShuffledElements.setBit(Idx);
6469     }
6470   }
6471   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6472 }
6473 
6474 // Perform operand reordering on the instructions in VL and return the reordered
6475 // operands in Left and Right.
6476 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6477                                              SmallVectorImpl<Value *> &Left,
6478                                              SmallVectorImpl<Value *> &Right,
6479                                              const DataLayout &DL,
6480                                              ScalarEvolution &SE,
6481                                              const BoUpSLP &R) {
6482   if (VL.empty())
6483     return;
6484   VLOperands Ops(VL, DL, SE, R);
6485   // Reorder the operands in place.
6486   Ops.reorder();
6487   Left = Ops.getVL(0);
6488   Right = Ops.getVL(1);
6489 }
6490 
6491 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6492   // Get the basic block this bundle is in. All instructions in the bundle
6493   // should be in this block.
6494   auto *Front = E->getMainOp();
6495   auto *BB = Front->getParent();
6496   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6497     auto *I = cast<Instruction>(V);
6498     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6499   }));
6500 
6501   auto &&FindLastInst = [E, Front]() {
6502     Instruction *LastInst = Front;
6503     for (Value *V : E->Scalars) {
6504       auto *I = dyn_cast<Instruction>(V);
6505       if (!I)
6506         continue;
6507       if (LastInst->comesBefore(I))
6508         LastInst = I;
6509     }
6510     return LastInst;
6511   };
6512 
6513   auto &&FindFirstInst = [E, Front]() {
6514     Instruction *FirstInst = Front;
6515     for (Value *V : E->Scalars) {
6516       auto *I = dyn_cast<Instruction>(V);
6517       if (!I)
6518         continue;
6519       if (I->comesBefore(FirstInst))
6520         FirstInst = I;
6521     }
6522     return FirstInst;
6523   };
6524 
6525   // Set the insert point to the beginning of the basic block if the entry
6526   // should not be scheduled.
6527   if (E->State != TreeEntry::NeedToGather &&
6528       doesNotNeedToSchedule(E->Scalars)) {
6529     BasicBlock::iterator InsertPt;
6530     if (all_of(E->Scalars, isUsedOutsideBlock))
6531       InsertPt = FindLastInst()->getIterator();
6532     else
6533       InsertPt = FindFirstInst()->getIterator();
6534     Builder.SetInsertPoint(BB, InsertPt);
6535     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6536     return;
6537   }
6538 
6539   // The last instruction in the bundle in program order.
6540   Instruction *LastInst = nullptr;
6541 
6542   // Find the last instruction. The common case should be that BB has been
6543   // scheduled, and the last instruction is VL.back(). So we start with
6544   // VL.back() and iterate over schedule data until we reach the end of the
6545   // bundle. The end of the bundle is marked by null ScheduleData.
6546   if (BlocksSchedules.count(BB)) {
6547     Value *V = E->isOneOf(E->Scalars.back());
6548     if (doesNotNeedToBeScheduled(V))
6549       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6550     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6551     if (Bundle && Bundle->isPartOfBundle())
6552       for (; Bundle; Bundle = Bundle->NextInBundle)
6553         if (Bundle->OpValue == Bundle->Inst)
6554           LastInst = Bundle->Inst;
6555   }
6556 
6557   // LastInst can still be null at this point if there's either not an entry
6558   // for BB in BlocksSchedules or there's no ScheduleData available for
6559   // VL.back(). This can be the case if buildTree_rec aborts for various
6560   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6561   // size is reached, etc.). ScheduleData is initialized in the scheduling
6562   // "dry-run".
6563   //
6564   // If this happens, we can still find the last instruction by brute force. We
6565   // iterate forwards from Front (inclusive) until we either see all
6566   // instructions in the bundle or reach the end of the block. If Front is the
6567   // last instruction in program order, LastInst will be set to Front, and we
6568   // will visit all the remaining instructions in the block.
6569   //
6570   // One of the reasons we exit early from buildTree_rec is to place an upper
6571   // bound on compile-time. Thus, taking an additional compile-time hit here is
6572   // not ideal. However, this should be exceedingly rare since it requires that
6573   // we both exit early from buildTree_rec and that the bundle be out-of-order
6574   // (causing us to iterate all the way to the end of the block).
6575   if (!LastInst)
6576     LastInst = FindLastInst();
6577   assert(LastInst && "Failed to find last instruction in bundle");
6578 
6579   // Set the insertion point after the last instruction in the bundle. Set the
6580   // debug location to Front.
6581   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6582   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6583 }
6584 
6585 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6586   // List of instructions/lanes from current block and/or the blocks which are
6587   // part of the current loop. These instructions will be inserted at the end to
6588   // make it possible to optimize loops and hoist invariant instructions out of
6589   // the loops body with better chances for success.
6590   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6591   SmallSet<int, 4> PostponedIndices;
6592   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6593   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6594     SmallPtrSet<BasicBlock *, 4> Visited;
6595     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6596       InsertBB = InsertBB->getSinglePredecessor();
6597     return InsertBB && InsertBB == InstBB;
6598   };
6599   for (int I = 0, E = VL.size(); I < E; ++I) {
6600     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6601       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6602            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6603           PostponedIndices.insert(I).second)
6604         PostponedInsts.emplace_back(Inst, I);
6605   }
6606 
6607   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6608     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6609     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6610     if (!InsElt)
6611       return Vec;
6612     GatherShuffleSeq.insert(InsElt);
6613     CSEBlocks.insert(InsElt->getParent());
6614     // Add to our 'need-to-extract' list.
6615     if (TreeEntry *Entry = getTreeEntry(V)) {
6616       // Find which lane we need to extract.
6617       unsigned FoundLane = Entry->findLaneForValue(V);
6618       ExternalUses.emplace_back(V, InsElt, FoundLane);
6619     }
6620     return Vec;
6621   };
6622   Value *Val0 =
6623       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6624   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6625   Value *Vec = PoisonValue::get(VecTy);
6626   SmallVector<int> NonConsts;
6627   // Insert constant values at first.
6628   for (int I = 0, E = VL.size(); I < E; ++I) {
6629     if (PostponedIndices.contains(I))
6630       continue;
6631     if (!isConstant(VL[I])) {
6632       NonConsts.push_back(I);
6633       continue;
6634     }
6635     Vec = CreateInsertElement(Vec, VL[I], I);
6636   }
6637   // Insert non-constant values.
6638   for (int I : NonConsts)
6639     Vec = CreateInsertElement(Vec, VL[I], I);
6640   // Append instructions, which are/may be part of the loop, in the end to make
6641   // it possible to hoist non-loop-based instructions.
6642   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6643     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6644 
6645   return Vec;
6646 }
6647 
6648 namespace {
6649 /// Merges shuffle masks and emits final shuffle instruction, if required.
6650 class ShuffleInstructionBuilder {
6651   IRBuilderBase &Builder;
6652   const unsigned VF = 0;
6653   bool IsFinalized = false;
6654   SmallVector<int, 4> Mask;
6655   /// Holds all of the instructions that we gathered.
6656   SetVector<Instruction *> &GatherShuffleSeq;
6657   /// A list of blocks that we are going to CSE.
6658   SetVector<BasicBlock *> &CSEBlocks;
6659 
6660 public:
6661   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6662                             SetVector<Instruction *> &GatherShuffleSeq,
6663                             SetVector<BasicBlock *> &CSEBlocks)
6664       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6665         CSEBlocks(CSEBlocks) {}
6666 
6667   /// Adds a mask, inverting it before applying.
6668   void addInversedMask(ArrayRef<unsigned> SubMask) {
6669     if (SubMask.empty())
6670       return;
6671     SmallVector<int, 4> NewMask;
6672     inversePermutation(SubMask, NewMask);
6673     addMask(NewMask);
6674   }
6675 
6676   /// Functions adds masks, merging them into  single one.
6677   void addMask(ArrayRef<unsigned> SubMask) {
6678     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6679     addMask(NewMask);
6680   }
6681 
6682   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6683 
6684   Value *finalize(Value *V) {
6685     IsFinalized = true;
6686     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6687     if (VF == ValueVF && Mask.empty())
6688       return V;
6689     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6690     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6691     addMask(NormalizedMask);
6692 
6693     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6694       return V;
6695     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6696     if (auto *I = dyn_cast<Instruction>(Vec)) {
6697       GatherShuffleSeq.insert(I);
6698       CSEBlocks.insert(I->getParent());
6699     }
6700     return Vec;
6701   }
6702 
6703   ~ShuffleInstructionBuilder() {
6704     assert((IsFinalized || Mask.empty()) &&
6705            "Shuffle construction must be finalized.");
6706   }
6707 };
6708 } // namespace
6709 
6710 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6711   const unsigned VF = VL.size();
6712   InstructionsState S = getSameOpcode(VL);
6713   if (S.getOpcode()) {
6714     if (TreeEntry *E = getTreeEntry(S.OpValue))
6715       if (E->isSame(VL)) {
6716         Value *V = vectorizeTree(E);
6717         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6718           if (!E->ReuseShuffleIndices.empty()) {
6719             // Reshuffle to get only unique values.
6720             // If some of the scalars are duplicated in the vectorization tree
6721             // entry, we do not vectorize them but instead generate a mask for
6722             // the reuses. But if there are several users of the same entry,
6723             // they may have different vectorization factors. This is especially
6724             // important for PHI nodes. In this case, we need to adapt the
6725             // resulting instruction for the user vectorization factor and have
6726             // to reshuffle it again to take only unique elements of the vector.
6727             // Without this code the function incorrectly returns reduced vector
6728             // instruction with the same elements, not with the unique ones.
6729 
6730             // block:
6731             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6732             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6733             // ... (use %2)
6734             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6735             // br %block
6736             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6737             SmallSet<int, 4> UsedIdxs;
6738             int Pos = 0;
6739             int Sz = VL.size();
6740             for (int Idx : E->ReuseShuffleIndices) {
6741               if (Idx != Sz && Idx != UndefMaskElem &&
6742                   UsedIdxs.insert(Idx).second)
6743                 UniqueIdxs[Idx] = Pos;
6744               ++Pos;
6745             }
6746             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6747                                             "less than original vector size.");
6748             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6749             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6750           } else {
6751             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6752                    "Expected vectorization factor less "
6753                    "than original vector size.");
6754             SmallVector<int> UniformMask(VF, 0);
6755             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6756             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6757           }
6758           if (auto *I = dyn_cast<Instruction>(V)) {
6759             GatherShuffleSeq.insert(I);
6760             CSEBlocks.insert(I->getParent());
6761           }
6762         }
6763         return V;
6764       }
6765   }
6766 
6767   // Can't vectorize this, so simply build a new vector with each lane
6768   // corresponding to the requested value.
6769   return createBuildVector(VL);
6770 }
6771 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6772   unsigned VF = VL.size();
6773   // Exploit possible reuse of values across lanes.
6774   SmallVector<int> ReuseShuffleIndicies;
6775   SmallVector<Value *> UniqueValues;
6776   if (VL.size() > 2) {
6777     DenseMap<Value *, unsigned> UniquePositions;
6778     unsigned NumValues =
6779         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6780                                     return !isa<UndefValue>(V);
6781                                   }).base());
6782     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6783     int UniqueVals = 0;
6784     for (Value *V : VL.drop_back(VL.size() - VF)) {
6785       if (isa<UndefValue>(V)) {
6786         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6787         continue;
6788       }
6789       if (isConstant(V)) {
6790         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6791         UniqueValues.emplace_back(V);
6792         continue;
6793       }
6794       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6795       ReuseShuffleIndicies.emplace_back(Res.first->second);
6796       if (Res.second) {
6797         UniqueValues.emplace_back(V);
6798         ++UniqueVals;
6799       }
6800     }
6801     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6802       // Emit pure splat vector.
6803       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6804                                   UndefMaskElem);
6805     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6806       ReuseShuffleIndicies.clear();
6807       UniqueValues.clear();
6808       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6809     }
6810     UniqueValues.append(VF - UniqueValues.size(),
6811                         PoisonValue::get(VL[0]->getType()));
6812     VL = UniqueValues;
6813   }
6814 
6815   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6816                                            CSEBlocks);
6817   Value *Vec = gather(VL);
6818   if (!ReuseShuffleIndicies.empty()) {
6819     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6820     Vec = ShuffleBuilder.finalize(Vec);
6821   }
6822   return Vec;
6823 }
6824 
6825 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6826   IRBuilder<>::InsertPointGuard Guard(Builder);
6827 
6828   if (E->VectorizedValue) {
6829     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6830     return E->VectorizedValue;
6831   }
6832 
6833   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6834   unsigned VF = E->getVectorFactor();
6835   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6836                                            CSEBlocks);
6837   if (E->State == TreeEntry::NeedToGather) {
6838     if (E->getMainOp())
6839       setInsertPointAfterBundle(E);
6840     Value *Vec;
6841     SmallVector<int> Mask;
6842     SmallVector<const TreeEntry *> Entries;
6843     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6844         isGatherShuffledEntry(E, Mask, Entries);
6845     if (Shuffle.hasValue()) {
6846       assert((Entries.size() == 1 || Entries.size() == 2) &&
6847              "Expected shuffle of 1 or 2 entries.");
6848       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6849                                         Entries.back()->VectorizedValue, Mask);
6850       if (auto *I = dyn_cast<Instruction>(Vec)) {
6851         GatherShuffleSeq.insert(I);
6852         CSEBlocks.insert(I->getParent());
6853       }
6854     } else {
6855       Vec = gather(E->Scalars);
6856     }
6857     if (NeedToShuffleReuses) {
6858       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6859       Vec = ShuffleBuilder.finalize(Vec);
6860     }
6861     E->VectorizedValue = Vec;
6862     return Vec;
6863   }
6864 
6865   assert((E->State == TreeEntry::Vectorize ||
6866           E->State == TreeEntry::ScatterVectorize) &&
6867          "Unhandled state");
6868   unsigned ShuffleOrOp =
6869       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6870   Instruction *VL0 = E->getMainOp();
6871   Type *ScalarTy = VL0->getType();
6872   if (auto *Store = dyn_cast<StoreInst>(VL0))
6873     ScalarTy = Store->getValueOperand()->getType();
6874   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6875     ScalarTy = IE->getOperand(1)->getType();
6876   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6877   switch (ShuffleOrOp) {
6878     case Instruction::PHI: {
6879       assert(
6880           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6881           "PHI reordering is free.");
6882       auto *PH = cast<PHINode>(VL0);
6883       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6884       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6885       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6886       Value *V = NewPhi;
6887 
6888       // Adjust insertion point once all PHI's have been generated.
6889       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6890       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6891 
6892       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6893       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6894       V = ShuffleBuilder.finalize(V);
6895 
6896       E->VectorizedValue = V;
6897 
6898       // PHINodes may have multiple entries from the same block. We want to
6899       // visit every block once.
6900       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6901 
6902       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6903         ValueList Operands;
6904         BasicBlock *IBB = PH->getIncomingBlock(i);
6905 
6906         if (!VisitedBBs.insert(IBB).second) {
6907           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6908           continue;
6909         }
6910 
6911         Builder.SetInsertPoint(IBB->getTerminator());
6912         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6913         Value *Vec = vectorizeTree(E->getOperand(i));
6914         NewPhi->addIncoming(Vec, IBB);
6915       }
6916 
6917       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6918              "Invalid number of incoming values");
6919       return V;
6920     }
6921 
6922     case Instruction::ExtractElement: {
6923       Value *V = E->getSingleOperand(0);
6924       Builder.SetInsertPoint(VL0);
6925       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6926       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6927       V = ShuffleBuilder.finalize(V);
6928       E->VectorizedValue = V;
6929       return V;
6930     }
6931     case Instruction::ExtractValue: {
6932       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6933       Builder.SetInsertPoint(LI);
6934       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6935       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6936       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6937       Value *NewV = propagateMetadata(V, E->Scalars);
6938       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6939       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6940       NewV = ShuffleBuilder.finalize(NewV);
6941       E->VectorizedValue = NewV;
6942       return NewV;
6943     }
6944     case Instruction::InsertElement: {
6945       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6946       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6947       Value *V = vectorizeTree(E->getOperand(1));
6948 
6949       // Create InsertVector shuffle if necessary
6950       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6951         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6952       }));
6953       const unsigned NumElts =
6954           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6955       const unsigned NumScalars = E->Scalars.size();
6956 
6957       unsigned Offset = *getInsertIndex(VL0);
6958       assert(Offset < NumElts && "Failed to find vector index offset");
6959 
6960       // Create shuffle to resize vector
6961       SmallVector<int> Mask;
6962       if (!E->ReorderIndices.empty()) {
6963         inversePermutation(E->ReorderIndices, Mask);
6964         Mask.append(NumElts - NumScalars, UndefMaskElem);
6965       } else {
6966         Mask.assign(NumElts, UndefMaskElem);
6967         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6968       }
6969       // Create InsertVector shuffle if necessary
6970       bool IsIdentity = true;
6971       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6972       Mask.swap(PrevMask);
6973       for (unsigned I = 0; I < NumScalars; ++I) {
6974         Value *Scalar = E->Scalars[PrevMask[I]];
6975         unsigned InsertIdx = *getInsertIndex(Scalar);
6976         IsIdentity &= InsertIdx - Offset == I;
6977         Mask[InsertIdx - Offset] = I;
6978       }
6979       if (!IsIdentity || NumElts != NumScalars) {
6980         V = Builder.CreateShuffleVector(V, Mask);
6981         if (auto *I = dyn_cast<Instruction>(V)) {
6982           GatherShuffleSeq.insert(I);
6983           CSEBlocks.insert(I->getParent());
6984         }
6985       }
6986 
6987       if ((!IsIdentity || Offset != 0 ||
6988            !isUndefVector(FirstInsert->getOperand(0))) &&
6989           NumElts != NumScalars) {
6990         SmallVector<int> InsertMask(NumElts);
6991         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6992         for (unsigned I = 0; I < NumElts; I++) {
6993           if (Mask[I] != UndefMaskElem)
6994             InsertMask[Offset + I] = NumElts + I;
6995         }
6996 
6997         V = Builder.CreateShuffleVector(
6998             FirstInsert->getOperand(0), V, InsertMask,
6999             cast<Instruction>(E->Scalars.back())->getName());
7000         if (auto *I = dyn_cast<Instruction>(V)) {
7001           GatherShuffleSeq.insert(I);
7002           CSEBlocks.insert(I->getParent());
7003         }
7004       }
7005 
7006       ++NumVectorInstructions;
7007       E->VectorizedValue = V;
7008       return V;
7009     }
7010     case Instruction::ZExt:
7011     case Instruction::SExt:
7012     case Instruction::FPToUI:
7013     case Instruction::FPToSI:
7014     case Instruction::FPExt:
7015     case Instruction::PtrToInt:
7016     case Instruction::IntToPtr:
7017     case Instruction::SIToFP:
7018     case Instruction::UIToFP:
7019     case Instruction::Trunc:
7020     case Instruction::FPTrunc:
7021     case Instruction::BitCast: {
7022       setInsertPointAfterBundle(E);
7023 
7024       Value *InVec = vectorizeTree(E->getOperand(0));
7025 
7026       if (E->VectorizedValue) {
7027         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7028         return E->VectorizedValue;
7029       }
7030 
7031       auto *CI = cast<CastInst>(VL0);
7032       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7033       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7034       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7035       V = ShuffleBuilder.finalize(V);
7036 
7037       E->VectorizedValue = V;
7038       ++NumVectorInstructions;
7039       return V;
7040     }
7041     case Instruction::FCmp:
7042     case Instruction::ICmp: {
7043       setInsertPointAfterBundle(E);
7044 
7045       Value *L = vectorizeTree(E->getOperand(0));
7046       Value *R = vectorizeTree(E->getOperand(1));
7047 
7048       if (E->VectorizedValue) {
7049         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7050         return E->VectorizedValue;
7051       }
7052 
7053       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7054       Value *V = Builder.CreateCmp(P0, L, R);
7055       propagateIRFlags(V, E->Scalars, VL0);
7056       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7057       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7058       V = ShuffleBuilder.finalize(V);
7059 
7060       E->VectorizedValue = V;
7061       ++NumVectorInstructions;
7062       return V;
7063     }
7064     case Instruction::Select: {
7065       setInsertPointAfterBundle(E);
7066 
7067       Value *Cond = vectorizeTree(E->getOperand(0));
7068       Value *True = vectorizeTree(E->getOperand(1));
7069       Value *False = vectorizeTree(E->getOperand(2));
7070 
7071       if (E->VectorizedValue) {
7072         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7073         return E->VectorizedValue;
7074       }
7075 
7076       Value *V = Builder.CreateSelect(Cond, True, False);
7077       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7078       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7079       V = ShuffleBuilder.finalize(V);
7080 
7081       E->VectorizedValue = V;
7082       ++NumVectorInstructions;
7083       return V;
7084     }
7085     case Instruction::FNeg: {
7086       setInsertPointAfterBundle(E);
7087 
7088       Value *Op = vectorizeTree(E->getOperand(0));
7089 
7090       if (E->VectorizedValue) {
7091         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7092         return E->VectorizedValue;
7093       }
7094 
7095       Value *V = Builder.CreateUnOp(
7096           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7097       propagateIRFlags(V, E->Scalars, VL0);
7098       if (auto *I = dyn_cast<Instruction>(V))
7099         V = propagateMetadata(I, E->Scalars);
7100 
7101       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7102       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7103       V = ShuffleBuilder.finalize(V);
7104 
7105       E->VectorizedValue = V;
7106       ++NumVectorInstructions;
7107 
7108       return V;
7109     }
7110     case Instruction::Add:
7111     case Instruction::FAdd:
7112     case Instruction::Sub:
7113     case Instruction::FSub:
7114     case Instruction::Mul:
7115     case Instruction::FMul:
7116     case Instruction::UDiv:
7117     case Instruction::SDiv:
7118     case Instruction::FDiv:
7119     case Instruction::URem:
7120     case Instruction::SRem:
7121     case Instruction::FRem:
7122     case Instruction::Shl:
7123     case Instruction::LShr:
7124     case Instruction::AShr:
7125     case Instruction::And:
7126     case Instruction::Or:
7127     case Instruction::Xor: {
7128       setInsertPointAfterBundle(E);
7129 
7130       Value *LHS = vectorizeTree(E->getOperand(0));
7131       Value *RHS = vectorizeTree(E->getOperand(1));
7132 
7133       if (E->VectorizedValue) {
7134         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7135         return E->VectorizedValue;
7136       }
7137 
7138       Value *V = Builder.CreateBinOp(
7139           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7140           RHS);
7141       propagateIRFlags(V, E->Scalars, VL0);
7142       if (auto *I = dyn_cast<Instruction>(V))
7143         V = propagateMetadata(I, E->Scalars);
7144 
7145       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7146       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7147       V = ShuffleBuilder.finalize(V);
7148 
7149       E->VectorizedValue = V;
7150       ++NumVectorInstructions;
7151 
7152       return V;
7153     }
7154     case Instruction::Load: {
7155       // Loads are inserted at the head of the tree because we don't want to
7156       // sink them all the way down past store instructions.
7157       setInsertPointAfterBundle(E);
7158 
7159       LoadInst *LI = cast<LoadInst>(VL0);
7160       Instruction *NewLI;
7161       unsigned AS = LI->getPointerAddressSpace();
7162       Value *PO = LI->getPointerOperand();
7163       if (E->State == TreeEntry::Vectorize) {
7164         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7165         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7166 
7167         // The pointer operand uses an in-tree scalar so we add the new BitCast
7168         // or LoadInst to ExternalUses list to make sure that an extract will
7169         // be generated in the future.
7170         if (TreeEntry *Entry = getTreeEntry(PO)) {
7171           // Find which lane we need to extract.
7172           unsigned FoundLane = Entry->findLaneForValue(PO);
7173           ExternalUses.emplace_back(
7174               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7175         }
7176       } else {
7177         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7178         Value *VecPtr = vectorizeTree(E->getOperand(0));
7179         // Use the minimum alignment of the gathered loads.
7180         Align CommonAlignment = LI->getAlign();
7181         for (Value *V : E->Scalars)
7182           CommonAlignment =
7183               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7184         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7185       }
7186       Value *V = propagateMetadata(NewLI, E->Scalars);
7187 
7188       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7189       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7190       V = ShuffleBuilder.finalize(V);
7191       E->VectorizedValue = V;
7192       ++NumVectorInstructions;
7193       return V;
7194     }
7195     case Instruction::Store: {
7196       auto *SI = cast<StoreInst>(VL0);
7197       unsigned AS = SI->getPointerAddressSpace();
7198 
7199       setInsertPointAfterBundle(E);
7200 
7201       Value *VecValue = vectorizeTree(E->getOperand(0));
7202       ShuffleBuilder.addMask(E->ReorderIndices);
7203       VecValue = ShuffleBuilder.finalize(VecValue);
7204 
7205       Value *ScalarPtr = SI->getPointerOperand();
7206       Value *VecPtr = Builder.CreateBitCast(
7207           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7208       StoreInst *ST =
7209           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7210 
7211       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7212       // StoreInst to ExternalUses to make sure that an extract will be
7213       // generated in the future.
7214       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7215         // Find which lane we need to extract.
7216         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7217         ExternalUses.push_back(ExternalUser(
7218             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7219             FoundLane));
7220       }
7221 
7222       Value *V = propagateMetadata(ST, E->Scalars);
7223 
7224       E->VectorizedValue = V;
7225       ++NumVectorInstructions;
7226       return V;
7227     }
7228     case Instruction::GetElementPtr: {
7229       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7230       setInsertPointAfterBundle(E);
7231 
7232       Value *Op0 = vectorizeTree(E->getOperand(0));
7233 
7234       SmallVector<Value *> OpVecs;
7235       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7236         Value *OpVec = vectorizeTree(E->getOperand(J));
7237         OpVecs.push_back(OpVec);
7238       }
7239 
7240       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7241       if (Instruction *I = dyn_cast<Instruction>(V))
7242         V = propagateMetadata(I, E->Scalars);
7243 
7244       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7245       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7246       V = ShuffleBuilder.finalize(V);
7247 
7248       E->VectorizedValue = V;
7249       ++NumVectorInstructions;
7250 
7251       return V;
7252     }
7253     case Instruction::Call: {
7254       CallInst *CI = cast<CallInst>(VL0);
7255       setInsertPointAfterBundle(E);
7256 
7257       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7258       if (Function *FI = CI->getCalledFunction())
7259         IID = FI->getIntrinsicID();
7260 
7261       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7262 
7263       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7264       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7265                           VecCallCosts.first <= VecCallCosts.second;
7266 
7267       Value *ScalarArg = nullptr;
7268       std::vector<Value *> OpVecs;
7269       SmallVector<Type *, 2> TysForDecl =
7270           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7271       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7272         ValueList OpVL;
7273         // Some intrinsics have scalar arguments. This argument should not be
7274         // vectorized.
7275         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7276           CallInst *CEI = cast<CallInst>(VL0);
7277           ScalarArg = CEI->getArgOperand(j);
7278           OpVecs.push_back(CEI->getArgOperand(j));
7279           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7280             TysForDecl.push_back(ScalarArg->getType());
7281           continue;
7282         }
7283 
7284         Value *OpVec = vectorizeTree(E->getOperand(j));
7285         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7286         OpVecs.push_back(OpVec);
7287       }
7288 
7289       Function *CF;
7290       if (!UseIntrinsic) {
7291         VFShape Shape =
7292             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7293                                   VecTy->getNumElements())),
7294                          false /*HasGlobalPred*/);
7295         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7296       } else {
7297         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7298       }
7299 
7300       SmallVector<OperandBundleDef, 1> OpBundles;
7301       CI->getOperandBundlesAsDefs(OpBundles);
7302       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7303 
7304       // The scalar argument uses an in-tree scalar so we add the new vectorized
7305       // call to ExternalUses list to make sure that an extract will be
7306       // generated in the future.
7307       if (ScalarArg) {
7308         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7309           // Find which lane we need to extract.
7310           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7311           ExternalUses.push_back(
7312               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7313         }
7314       }
7315 
7316       propagateIRFlags(V, E->Scalars, VL0);
7317       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7318       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7319       V = ShuffleBuilder.finalize(V);
7320 
7321       E->VectorizedValue = V;
7322       ++NumVectorInstructions;
7323       return V;
7324     }
7325     case Instruction::ShuffleVector: {
7326       assert(E->isAltShuffle() &&
7327              ((Instruction::isBinaryOp(E->getOpcode()) &&
7328                Instruction::isBinaryOp(E->getAltOpcode())) ||
7329               (Instruction::isCast(E->getOpcode()) &&
7330                Instruction::isCast(E->getAltOpcode())) ||
7331               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7332              "Invalid Shuffle Vector Operand");
7333 
7334       Value *LHS = nullptr, *RHS = nullptr;
7335       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7336         setInsertPointAfterBundle(E);
7337         LHS = vectorizeTree(E->getOperand(0));
7338         RHS = vectorizeTree(E->getOperand(1));
7339       } else {
7340         setInsertPointAfterBundle(E);
7341         LHS = vectorizeTree(E->getOperand(0));
7342       }
7343 
7344       if (E->VectorizedValue) {
7345         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7346         return E->VectorizedValue;
7347       }
7348 
7349       Value *V0, *V1;
7350       if (Instruction::isBinaryOp(E->getOpcode())) {
7351         V0 = Builder.CreateBinOp(
7352             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7353         V1 = Builder.CreateBinOp(
7354             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7355       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7356         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7357         auto *AltCI = cast<CmpInst>(E->getAltOp());
7358         CmpInst::Predicate AltPred = AltCI->getPredicate();
7359         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7360       } else {
7361         V0 = Builder.CreateCast(
7362             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7363         V1 = Builder.CreateCast(
7364             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7365       }
7366       // Add V0 and V1 to later analysis to try to find and remove matching
7367       // instruction, if any.
7368       for (Value *V : {V0, V1}) {
7369         if (auto *I = dyn_cast<Instruction>(V)) {
7370           GatherShuffleSeq.insert(I);
7371           CSEBlocks.insert(I->getParent());
7372         }
7373       }
7374 
7375       // Create shuffle to take alternate operations from the vector.
7376       // Also, gather up main and alt scalar ops to propagate IR flags to
7377       // each vector operation.
7378       ValueList OpScalars, AltScalars;
7379       SmallVector<int> Mask;
7380       buildShuffleEntryMask(
7381           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7382           [E](Instruction *I) {
7383             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7384             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7385           },
7386           Mask, &OpScalars, &AltScalars);
7387 
7388       propagateIRFlags(V0, OpScalars);
7389       propagateIRFlags(V1, AltScalars);
7390 
7391       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7392       if (auto *I = dyn_cast<Instruction>(V)) {
7393         V = propagateMetadata(I, E->Scalars);
7394         GatherShuffleSeq.insert(I);
7395         CSEBlocks.insert(I->getParent());
7396       }
7397       V = ShuffleBuilder.finalize(V);
7398 
7399       E->VectorizedValue = V;
7400       ++NumVectorInstructions;
7401 
7402       return V;
7403     }
7404     default:
7405     llvm_unreachable("unknown inst");
7406   }
7407   return nullptr;
7408 }
7409 
7410 Value *BoUpSLP::vectorizeTree() {
7411   ExtraValueToDebugLocsMap ExternallyUsedValues;
7412   return vectorizeTree(ExternallyUsedValues);
7413 }
7414 
7415 Value *
7416 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7417   // All blocks must be scheduled before any instructions are inserted.
7418   for (auto &BSIter : BlocksSchedules) {
7419     scheduleBlock(BSIter.second.get());
7420   }
7421 
7422   Builder.SetInsertPoint(&F->getEntryBlock().front());
7423   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7424 
7425   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7426   // vectorized root. InstCombine will then rewrite the entire expression. We
7427   // sign extend the extracted values below.
7428   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7429   if (MinBWs.count(ScalarRoot)) {
7430     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7431       // If current instr is a phi and not the last phi, insert it after the
7432       // last phi node.
7433       if (isa<PHINode>(I))
7434         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7435       else
7436         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7437     }
7438     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7439     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7440     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7441     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7442     VectorizableTree[0]->VectorizedValue = Trunc;
7443   }
7444 
7445   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7446                     << " values .\n");
7447 
7448   // Extract all of the elements with the external uses.
7449   for (const auto &ExternalUse : ExternalUses) {
7450     Value *Scalar = ExternalUse.Scalar;
7451     llvm::User *User = ExternalUse.User;
7452 
7453     // Skip users that we already RAUW. This happens when one instruction
7454     // has multiple uses of the same value.
7455     if (User && !is_contained(Scalar->users(), User))
7456       continue;
7457     TreeEntry *E = getTreeEntry(Scalar);
7458     assert(E && "Invalid scalar");
7459     assert(E->State != TreeEntry::NeedToGather &&
7460            "Extracting from a gather list");
7461 
7462     Value *Vec = E->VectorizedValue;
7463     assert(Vec && "Can't find vectorizable value");
7464 
7465     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7466     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7467       if (Scalar->getType() != Vec->getType()) {
7468         Value *Ex;
7469         // "Reuse" the existing extract to improve final codegen.
7470         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7471           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7472                                             ES->getOperand(1));
7473         } else {
7474           Ex = Builder.CreateExtractElement(Vec, Lane);
7475         }
7476         // If necessary, sign-extend or zero-extend ScalarRoot
7477         // to the larger type.
7478         if (!MinBWs.count(ScalarRoot))
7479           return Ex;
7480         if (MinBWs[ScalarRoot].second)
7481           return Builder.CreateSExt(Ex, Scalar->getType());
7482         return Builder.CreateZExt(Ex, Scalar->getType());
7483       }
7484       assert(isa<FixedVectorType>(Scalar->getType()) &&
7485              isa<InsertElementInst>(Scalar) &&
7486              "In-tree scalar of vector type is not insertelement?");
7487       return Vec;
7488     };
7489     // If User == nullptr, the Scalar is used as extra arg. Generate
7490     // ExtractElement instruction and update the record for this scalar in
7491     // ExternallyUsedValues.
7492     if (!User) {
7493       assert(ExternallyUsedValues.count(Scalar) &&
7494              "Scalar with nullptr as an external user must be registered in "
7495              "ExternallyUsedValues map");
7496       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7497         Builder.SetInsertPoint(VecI->getParent(),
7498                                std::next(VecI->getIterator()));
7499       } else {
7500         Builder.SetInsertPoint(&F->getEntryBlock().front());
7501       }
7502       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7503       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7504       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7505       auto It = ExternallyUsedValues.find(Scalar);
7506       assert(It != ExternallyUsedValues.end() &&
7507              "Externally used scalar is not found in ExternallyUsedValues");
7508       NewInstLocs.append(It->second);
7509       ExternallyUsedValues.erase(Scalar);
7510       // Required to update internally referenced instructions.
7511       Scalar->replaceAllUsesWith(NewInst);
7512       continue;
7513     }
7514 
7515     // Generate extracts for out-of-tree users.
7516     // Find the insertion point for the extractelement lane.
7517     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7518       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7519         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7520           if (PH->getIncomingValue(i) == Scalar) {
7521             Instruction *IncomingTerminator =
7522                 PH->getIncomingBlock(i)->getTerminator();
7523             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7524               Builder.SetInsertPoint(VecI->getParent(),
7525                                      std::next(VecI->getIterator()));
7526             } else {
7527               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7528             }
7529             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7530             CSEBlocks.insert(PH->getIncomingBlock(i));
7531             PH->setOperand(i, NewInst);
7532           }
7533         }
7534       } else {
7535         Builder.SetInsertPoint(cast<Instruction>(User));
7536         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7537         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7538         User->replaceUsesOfWith(Scalar, NewInst);
7539       }
7540     } else {
7541       Builder.SetInsertPoint(&F->getEntryBlock().front());
7542       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7543       CSEBlocks.insert(&F->getEntryBlock());
7544       User->replaceUsesOfWith(Scalar, NewInst);
7545     }
7546 
7547     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7548   }
7549 
7550   // For each vectorized value:
7551   for (auto &TEPtr : VectorizableTree) {
7552     TreeEntry *Entry = TEPtr.get();
7553 
7554     // No need to handle users of gathered values.
7555     if (Entry->State == TreeEntry::NeedToGather)
7556       continue;
7557 
7558     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7559 
7560     // For each lane:
7561     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7562       Value *Scalar = Entry->Scalars[Lane];
7563 
7564 #ifndef NDEBUG
7565       Type *Ty = Scalar->getType();
7566       if (!Ty->isVoidTy()) {
7567         for (User *U : Scalar->users()) {
7568           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7569 
7570           // It is legal to delete users in the ignorelist.
7571           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7572                   (isa_and_nonnull<Instruction>(U) &&
7573                    isDeleted(cast<Instruction>(U)))) &&
7574                  "Deleting out-of-tree value");
7575         }
7576       }
7577 #endif
7578       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7579       eraseInstruction(cast<Instruction>(Scalar));
7580     }
7581   }
7582 
7583   Builder.ClearInsertionPoint();
7584   InstrElementSize.clear();
7585 
7586   return VectorizableTree[0]->VectorizedValue;
7587 }
7588 
7589 void BoUpSLP::optimizeGatherSequence() {
7590   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7591                     << " gather sequences instructions.\n");
7592   // LICM InsertElementInst sequences.
7593   for (Instruction *I : GatherShuffleSeq) {
7594     if (isDeleted(I))
7595       continue;
7596 
7597     // Check if this block is inside a loop.
7598     Loop *L = LI->getLoopFor(I->getParent());
7599     if (!L)
7600       continue;
7601 
7602     // Check if it has a preheader.
7603     BasicBlock *PreHeader = L->getLoopPreheader();
7604     if (!PreHeader)
7605       continue;
7606 
7607     // If the vector or the element that we insert into it are
7608     // instructions that are defined in this basic block then we can't
7609     // hoist this instruction.
7610     if (any_of(I->operands(), [L](Value *V) {
7611           auto *OpI = dyn_cast<Instruction>(V);
7612           return OpI && L->contains(OpI);
7613         }))
7614       continue;
7615 
7616     // We can hoist this instruction. Move it to the pre-header.
7617     I->moveBefore(PreHeader->getTerminator());
7618   }
7619 
7620   // Make a list of all reachable blocks in our CSE queue.
7621   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7622   CSEWorkList.reserve(CSEBlocks.size());
7623   for (BasicBlock *BB : CSEBlocks)
7624     if (DomTreeNode *N = DT->getNode(BB)) {
7625       assert(DT->isReachableFromEntry(N));
7626       CSEWorkList.push_back(N);
7627     }
7628 
7629   // Sort blocks by domination. This ensures we visit a block after all blocks
7630   // dominating it are visited.
7631   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7632     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7633            "Different nodes should have different DFS numbers");
7634     return A->getDFSNumIn() < B->getDFSNumIn();
7635   });
7636 
7637   // Less defined shuffles can be replaced by the more defined copies.
7638   // Between two shuffles one is less defined if it has the same vector operands
7639   // and its mask indeces are the same as in the first one or undefs. E.g.
7640   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7641   // poison, <0, 0, 0, 0>.
7642   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7643                                            SmallVectorImpl<int> &NewMask) {
7644     if (I1->getType() != I2->getType())
7645       return false;
7646     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7647     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7648     if (!SI1 || !SI2)
7649       return I1->isIdenticalTo(I2);
7650     if (SI1->isIdenticalTo(SI2))
7651       return true;
7652     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7653       if (SI1->getOperand(I) != SI2->getOperand(I))
7654         return false;
7655     // Check if the second instruction is more defined than the first one.
7656     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7657     ArrayRef<int> SM1 = SI1->getShuffleMask();
7658     // Count trailing undefs in the mask to check the final number of used
7659     // registers.
7660     unsigned LastUndefsCnt = 0;
7661     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7662       if (SM1[I] == UndefMaskElem)
7663         ++LastUndefsCnt;
7664       else
7665         LastUndefsCnt = 0;
7666       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7667           NewMask[I] != SM1[I])
7668         return false;
7669       if (NewMask[I] == UndefMaskElem)
7670         NewMask[I] = SM1[I];
7671     }
7672     // Check if the last undefs actually change the final number of used vector
7673     // registers.
7674     return SM1.size() - LastUndefsCnt > 1 &&
7675            TTI->getNumberOfParts(SI1->getType()) ==
7676                TTI->getNumberOfParts(
7677                    FixedVectorType::get(SI1->getType()->getElementType(),
7678                                         SM1.size() - LastUndefsCnt));
7679   };
7680   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7681   // instructions. TODO: We can further optimize this scan if we split the
7682   // instructions into different buckets based on the insert lane.
7683   SmallVector<Instruction *, 16> Visited;
7684   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7685     assert(*I &&
7686            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7687            "Worklist not sorted properly!");
7688     BasicBlock *BB = (*I)->getBlock();
7689     // For all instructions in blocks containing gather sequences:
7690     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7691       if (isDeleted(&In))
7692         continue;
7693       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7694           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7695         continue;
7696 
7697       // Check if we can replace this instruction with any of the
7698       // visited instructions.
7699       bool Replaced = false;
7700       for (Instruction *&V : Visited) {
7701         SmallVector<int> NewMask;
7702         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7703             DT->dominates(V->getParent(), In.getParent())) {
7704           In.replaceAllUsesWith(V);
7705           eraseInstruction(&In);
7706           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7707             if (!NewMask.empty())
7708               SI->setShuffleMask(NewMask);
7709           Replaced = true;
7710           break;
7711         }
7712         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7713             GatherShuffleSeq.contains(V) &&
7714             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7715             DT->dominates(In.getParent(), V->getParent())) {
7716           In.moveAfter(V);
7717           V->replaceAllUsesWith(&In);
7718           eraseInstruction(V);
7719           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7720             if (!NewMask.empty())
7721               SI->setShuffleMask(NewMask);
7722           V = &In;
7723           Replaced = true;
7724           break;
7725         }
7726       }
7727       if (!Replaced) {
7728         assert(!is_contained(Visited, &In));
7729         Visited.push_back(&In);
7730       }
7731     }
7732   }
7733   CSEBlocks.clear();
7734   GatherShuffleSeq.clear();
7735 }
7736 
7737 BoUpSLP::ScheduleData *
7738 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7739   ScheduleData *Bundle = nullptr;
7740   ScheduleData *PrevInBundle = nullptr;
7741   for (Value *V : VL) {
7742     if (doesNotNeedToBeScheduled(V))
7743       continue;
7744     ScheduleData *BundleMember = getScheduleData(V);
7745     assert(BundleMember &&
7746            "no ScheduleData for bundle member "
7747            "(maybe not in same basic block)");
7748     assert(BundleMember->isSchedulingEntity() &&
7749            "bundle member already part of other bundle");
7750     if (PrevInBundle) {
7751       PrevInBundle->NextInBundle = BundleMember;
7752     } else {
7753       Bundle = BundleMember;
7754     }
7755 
7756     // Group the instructions to a bundle.
7757     BundleMember->FirstInBundle = Bundle;
7758     PrevInBundle = BundleMember;
7759   }
7760   assert(Bundle && "Failed to find schedule bundle");
7761   return Bundle;
7762 }
7763 
7764 // Groups the instructions to a bundle (which is then a single scheduling entity)
7765 // and schedules instructions until the bundle gets ready.
7766 Optional<BoUpSLP::ScheduleData *>
7767 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7768                                             const InstructionsState &S) {
7769   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7770   // instructions.
7771   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7772       doesNotNeedToSchedule(VL))
7773     return nullptr;
7774 
7775   // Initialize the instruction bundle.
7776   Instruction *OldScheduleEnd = ScheduleEnd;
7777   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7778 
7779   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7780                                                          ScheduleData *Bundle) {
7781     // The scheduling region got new instructions at the lower end (or it is a
7782     // new region for the first bundle). This makes it necessary to
7783     // recalculate all dependencies.
7784     // It is seldom that this needs to be done a second time after adding the
7785     // initial bundle to the region.
7786     if (ScheduleEnd != OldScheduleEnd) {
7787       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7788         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7789       ReSchedule = true;
7790     }
7791     if (Bundle) {
7792       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7793                         << " in block " << BB->getName() << "\n");
7794       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7795     }
7796 
7797     if (ReSchedule) {
7798       resetSchedule();
7799       initialFillReadyList(ReadyInsts);
7800     }
7801 
7802     // Now try to schedule the new bundle or (if no bundle) just calculate
7803     // dependencies. As soon as the bundle is "ready" it means that there are no
7804     // cyclic dependencies and we can schedule it. Note that's important that we
7805     // don't "schedule" the bundle yet (see cancelScheduling).
7806     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7807            !ReadyInsts.empty()) {
7808       ScheduleData *Picked = ReadyInsts.pop_back_val();
7809       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7810              "must be ready to schedule");
7811       schedule(Picked, ReadyInsts);
7812     }
7813   };
7814 
7815   // Make sure that the scheduling region contains all
7816   // instructions of the bundle.
7817   for (Value *V : VL) {
7818     if (doesNotNeedToBeScheduled(V))
7819       continue;
7820     if (!extendSchedulingRegion(V, S)) {
7821       // If the scheduling region got new instructions at the lower end (or it
7822       // is a new region for the first bundle). This makes it necessary to
7823       // recalculate all dependencies.
7824       // Otherwise the compiler may crash trying to incorrectly calculate
7825       // dependencies and emit instruction in the wrong order at the actual
7826       // scheduling.
7827       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7828       return None;
7829     }
7830   }
7831 
7832   bool ReSchedule = false;
7833   for (Value *V : VL) {
7834     if (doesNotNeedToBeScheduled(V))
7835       continue;
7836     ScheduleData *BundleMember = getScheduleData(V);
7837     assert(BundleMember &&
7838            "no ScheduleData for bundle member (maybe not in same basic block)");
7839 
7840     // Make sure we don't leave the pieces of the bundle in the ready list when
7841     // whole bundle might not be ready.
7842     ReadyInsts.remove(BundleMember);
7843 
7844     if (!BundleMember->IsScheduled)
7845       continue;
7846     // A bundle member was scheduled as single instruction before and now
7847     // needs to be scheduled as part of the bundle. We just get rid of the
7848     // existing schedule.
7849     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7850                       << " was already scheduled\n");
7851     ReSchedule = true;
7852   }
7853 
7854   auto *Bundle = buildBundle(VL);
7855   TryScheduleBundleImpl(ReSchedule, Bundle);
7856   if (!Bundle->isReady()) {
7857     cancelScheduling(VL, S.OpValue);
7858     return None;
7859   }
7860   return Bundle;
7861 }
7862 
7863 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7864                                                 Value *OpValue) {
7865   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7866       doesNotNeedToSchedule(VL))
7867     return;
7868 
7869   if (doesNotNeedToBeScheduled(OpValue))
7870     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7871   ScheduleData *Bundle = getScheduleData(OpValue);
7872   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7873   assert(!Bundle->IsScheduled &&
7874          "Can't cancel bundle which is already scheduled");
7875   assert(Bundle->isSchedulingEntity() &&
7876          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7877          "tried to unbundle something which is not a bundle");
7878 
7879   // Remove the bundle from the ready list.
7880   if (Bundle->isReady())
7881     ReadyInsts.remove(Bundle);
7882 
7883   // Un-bundle: make single instructions out of the bundle.
7884   ScheduleData *BundleMember = Bundle;
7885   while (BundleMember) {
7886     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7887     BundleMember->FirstInBundle = BundleMember;
7888     ScheduleData *Next = BundleMember->NextInBundle;
7889     BundleMember->NextInBundle = nullptr;
7890     BundleMember->TE = nullptr;
7891     if (BundleMember->unscheduledDepsInBundle() == 0) {
7892       ReadyInsts.insert(BundleMember);
7893     }
7894     BundleMember = Next;
7895   }
7896 }
7897 
7898 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7899   // Allocate a new ScheduleData for the instruction.
7900   if (ChunkPos >= ChunkSize) {
7901     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7902     ChunkPos = 0;
7903   }
7904   return &(ScheduleDataChunks.back()[ChunkPos++]);
7905 }
7906 
7907 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7908                                                       const InstructionsState &S) {
7909   if (getScheduleData(V, isOneOf(S, V)))
7910     return true;
7911   Instruction *I = dyn_cast<Instruction>(V);
7912   assert(I && "bundle member must be an instruction");
7913   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7914          !doesNotNeedToBeScheduled(I) &&
7915          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7916          "be scheduled");
7917   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7918     ScheduleData *ISD = getScheduleData(I);
7919     if (!ISD)
7920       return false;
7921     assert(isInSchedulingRegion(ISD) &&
7922            "ScheduleData not in scheduling region");
7923     ScheduleData *SD = allocateScheduleDataChunks();
7924     SD->Inst = I;
7925     SD->init(SchedulingRegionID, S.OpValue);
7926     ExtraScheduleDataMap[I][S.OpValue] = SD;
7927     return true;
7928   };
7929   if (CheckScheduleForI(I))
7930     return true;
7931   if (!ScheduleStart) {
7932     // It's the first instruction in the new region.
7933     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7934     ScheduleStart = I;
7935     ScheduleEnd = I->getNextNode();
7936     if (isOneOf(S, I) != I)
7937       CheckScheduleForI(I);
7938     assert(ScheduleEnd && "tried to vectorize a terminator?");
7939     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7940     return true;
7941   }
7942   // Search up and down at the same time, because we don't know if the new
7943   // instruction is above or below the existing scheduling region.
7944   BasicBlock::reverse_iterator UpIter =
7945       ++ScheduleStart->getIterator().getReverse();
7946   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7947   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7948   BasicBlock::iterator LowerEnd = BB->end();
7949   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7950          &*DownIter != I) {
7951     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7952       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7953       return false;
7954     }
7955 
7956     ++UpIter;
7957     ++DownIter;
7958   }
7959   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7960     assert(I->getParent() == ScheduleStart->getParent() &&
7961            "Instruction is in wrong basic block.");
7962     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7963     ScheduleStart = I;
7964     if (isOneOf(S, I) != I)
7965       CheckScheduleForI(I);
7966     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7967                       << "\n");
7968     return true;
7969   }
7970   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7971          "Expected to reach top of the basic block or instruction down the "
7972          "lower end.");
7973   assert(I->getParent() == ScheduleEnd->getParent() &&
7974          "Instruction is in wrong basic block.");
7975   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7976                    nullptr);
7977   ScheduleEnd = I->getNextNode();
7978   if (isOneOf(S, I) != I)
7979     CheckScheduleForI(I);
7980   assert(ScheduleEnd && "tried to vectorize a terminator?");
7981   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7982   return true;
7983 }
7984 
7985 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7986                                                 Instruction *ToI,
7987                                                 ScheduleData *PrevLoadStore,
7988                                                 ScheduleData *NextLoadStore) {
7989   ScheduleData *CurrentLoadStore = PrevLoadStore;
7990   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7991     // No need to allocate data for non-schedulable instructions.
7992     if (doesNotNeedToBeScheduled(I))
7993       continue;
7994     ScheduleData *SD = ScheduleDataMap.lookup(I);
7995     if (!SD) {
7996       SD = allocateScheduleDataChunks();
7997       ScheduleDataMap[I] = SD;
7998       SD->Inst = I;
7999     }
8000     assert(!isInSchedulingRegion(SD) &&
8001            "new ScheduleData already in scheduling region");
8002     SD->init(SchedulingRegionID, I);
8003 
8004     if (I->mayReadOrWriteMemory() &&
8005         (!isa<IntrinsicInst>(I) ||
8006          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8007           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8008               Intrinsic::pseudoprobe))) {
8009       // Update the linked list of memory accessing instructions.
8010       if (CurrentLoadStore) {
8011         CurrentLoadStore->NextLoadStore = SD;
8012       } else {
8013         FirstLoadStoreInRegion = SD;
8014       }
8015       CurrentLoadStore = SD;
8016     }
8017   }
8018   if (NextLoadStore) {
8019     if (CurrentLoadStore)
8020       CurrentLoadStore->NextLoadStore = NextLoadStore;
8021   } else {
8022     LastLoadStoreInRegion = CurrentLoadStore;
8023   }
8024 }
8025 
8026 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8027                                                      bool InsertInReadyList,
8028                                                      BoUpSLP *SLP) {
8029   assert(SD->isSchedulingEntity());
8030 
8031   SmallVector<ScheduleData *, 10> WorkList;
8032   WorkList.push_back(SD);
8033 
8034   while (!WorkList.empty()) {
8035     ScheduleData *SD = WorkList.pop_back_val();
8036     for (ScheduleData *BundleMember = SD; BundleMember;
8037          BundleMember = BundleMember->NextInBundle) {
8038       assert(isInSchedulingRegion(BundleMember));
8039       if (BundleMember->hasValidDependencies())
8040         continue;
8041 
8042       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8043                  << "\n");
8044       BundleMember->Dependencies = 0;
8045       BundleMember->resetUnscheduledDeps();
8046 
8047       // Handle def-use chain dependencies.
8048       if (BundleMember->OpValue != BundleMember->Inst) {
8049         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8050           BundleMember->Dependencies++;
8051           ScheduleData *DestBundle = UseSD->FirstInBundle;
8052           if (!DestBundle->IsScheduled)
8053             BundleMember->incrementUnscheduledDeps(1);
8054           if (!DestBundle->hasValidDependencies())
8055             WorkList.push_back(DestBundle);
8056         }
8057       } else {
8058         for (User *U : BundleMember->Inst->users()) {
8059           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8060             BundleMember->Dependencies++;
8061             ScheduleData *DestBundle = UseSD->FirstInBundle;
8062             if (!DestBundle->IsScheduled)
8063               BundleMember->incrementUnscheduledDeps(1);
8064             if (!DestBundle->hasValidDependencies())
8065               WorkList.push_back(DestBundle);
8066           }
8067         }
8068       }
8069 
8070       // Any instruction which isn't safe to speculate at the begining of the
8071       // block is control dependend on any early exit or non-willreturn call
8072       // which proceeds it.
8073       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8074         for (Instruction *I = BundleMember->Inst->getNextNode();
8075              I != ScheduleEnd; I = I->getNextNode()) {
8076           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8077             continue;
8078 
8079           // Add the dependency
8080           auto *DepDest = getScheduleData(I);
8081           assert(DepDest && "must be in schedule window");
8082           DepDest->ControlDependencies.push_back(BundleMember);
8083           BundleMember->Dependencies++;
8084           ScheduleData *DestBundle = DepDest->FirstInBundle;
8085           if (!DestBundle->IsScheduled)
8086             BundleMember->incrementUnscheduledDeps(1);
8087           if (!DestBundle->hasValidDependencies())
8088             WorkList.push_back(DestBundle);
8089 
8090           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8091             // Everything past here must be control dependent on I.
8092             break;
8093         }
8094       }
8095 
8096       // If we have an inalloc alloca instruction, it needs to be scheduled
8097       // after any preceeding stacksave.
8098       if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>())) {
8099         for (Instruction *I = BundleMember->Inst->getNextNode();
8100              I != ScheduleEnd; I = I->getNextNode()) {
8101           if (match(I, m_Intrinsic<Intrinsic::stacksave>()))
8102             // Any allocas past here must be control dependent on I, and I
8103             // must be memory dependend on BundleMember->Inst.
8104             break;
8105 
8106           if (!isa<AllocaInst>(I))
8107             continue;
8108 
8109           // Add the dependency
8110           auto *DepDest = getScheduleData(I);
8111           assert(DepDest && "must be in schedule window");
8112           DepDest->ControlDependencies.push_back(BundleMember);
8113           BundleMember->Dependencies++;
8114           ScheduleData *DestBundle = DepDest->FirstInBundle;
8115           if (!DestBundle->IsScheduled)
8116             BundleMember->incrementUnscheduledDeps(1);
8117           if (!DestBundle->hasValidDependencies())
8118             WorkList.push_back(DestBundle);
8119         }
8120       }
8121 
8122 
8123       // Handle the memory dependencies (if any).
8124       ScheduleData *DepDest = BundleMember->NextLoadStore;
8125       if (!DepDest)
8126         continue;
8127       Instruction *SrcInst = BundleMember->Inst;
8128       assert(SrcInst->mayReadOrWriteMemory() &&
8129              "NextLoadStore list for non memory effecting bundle?");
8130       MemoryLocation SrcLoc = getLocation(SrcInst);
8131       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8132       unsigned numAliased = 0;
8133       unsigned DistToSrc = 1;
8134 
8135       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8136         assert(isInSchedulingRegion(DepDest));
8137 
8138         // We have two limits to reduce the complexity:
8139         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8140         //    SLP->isAliased (which is the expensive part in this loop).
8141         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8142         //    the whole loop (even if the loop is fast, it's quadratic).
8143         //    It's important for the loop break condition (see below) to
8144         //    check this limit even between two read-only instructions.
8145         if (DistToSrc >= MaxMemDepDistance ||
8146             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8147              (numAliased >= AliasedCheckLimit ||
8148               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8149 
8150           // We increment the counter only if the locations are aliased
8151           // (instead of counting all alias checks). This gives a better
8152           // balance between reduced runtime and accurate dependencies.
8153           numAliased++;
8154 
8155           DepDest->MemoryDependencies.push_back(BundleMember);
8156           BundleMember->Dependencies++;
8157           ScheduleData *DestBundle = DepDest->FirstInBundle;
8158           if (!DestBundle->IsScheduled) {
8159             BundleMember->incrementUnscheduledDeps(1);
8160           }
8161           if (!DestBundle->hasValidDependencies()) {
8162             WorkList.push_back(DestBundle);
8163           }
8164         }
8165 
8166         // Example, explaining the loop break condition: Let's assume our
8167         // starting instruction is i0 and MaxMemDepDistance = 3.
8168         //
8169         //                      +--------v--v--v
8170         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8171         //             +--------^--^--^
8172         //
8173         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8174         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8175         // Previously we already added dependencies from i3 to i6,i7,i8
8176         // (because of MaxMemDepDistance). As we added a dependency from
8177         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8178         // and we can abort this loop at i6.
8179         if (DistToSrc >= 2 * MaxMemDepDistance)
8180           break;
8181         DistToSrc++;
8182       }
8183     }
8184     if (InsertInReadyList && SD->isReady()) {
8185       ReadyInsts.insert(SD);
8186       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8187                         << "\n");
8188     }
8189   }
8190 }
8191 
8192 void BoUpSLP::BlockScheduling::resetSchedule() {
8193   assert(ScheduleStart &&
8194          "tried to reset schedule on block which has not been scheduled");
8195   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8196     doForAllOpcodes(I, [&](ScheduleData *SD) {
8197       assert(isInSchedulingRegion(SD) &&
8198              "ScheduleData not in scheduling region");
8199       SD->IsScheduled = false;
8200       SD->resetUnscheduledDeps();
8201     });
8202   }
8203   ReadyInsts.clear();
8204 }
8205 
8206 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8207   if (!BS->ScheduleStart)
8208     return;
8209 
8210   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8211 
8212   BS->resetSchedule();
8213 
8214   // For the real scheduling we use a more sophisticated ready-list: it is
8215   // sorted by the original instruction location. This lets the final schedule
8216   // be as  close as possible to the original instruction order.
8217   // WARNING: If changing this order causes a correctness issue, that means
8218   // there is some missing dependence edge in the schedule data graph.
8219   struct ScheduleDataCompare {
8220     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8221       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8222     }
8223   };
8224   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8225 
8226   // Ensure that all dependency data is updated and fill the ready-list with
8227   // initial instructions.
8228   int Idx = 0;
8229   int NumToSchedule = 0;
8230   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8231        I = I->getNextNode()) {
8232     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8233       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8234       (void)SDTE;
8235       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8236               SD->isPartOfBundle() ==
8237                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8238              "scheduler and vectorizer bundle mismatch");
8239       SD->FirstInBundle->SchedulingPriority = Idx++;
8240       if (SD->isSchedulingEntity()) {
8241         BS->calculateDependencies(SD, false, this);
8242         NumToSchedule++;
8243       }
8244     });
8245   }
8246   BS->initialFillReadyList(ReadyInsts);
8247 
8248   Instruction *LastScheduledInst = BS->ScheduleEnd;
8249 
8250   // Do the "real" scheduling.
8251   while (!ReadyInsts.empty()) {
8252     ScheduleData *picked = *ReadyInsts.begin();
8253     ReadyInsts.erase(ReadyInsts.begin());
8254 
8255     // Move the scheduled instruction(s) to their dedicated places, if not
8256     // there yet.
8257     for (ScheduleData *BundleMember = picked; BundleMember;
8258          BundleMember = BundleMember->NextInBundle) {
8259       Instruction *pickedInst = BundleMember->Inst;
8260       if (pickedInst->getNextNode() != LastScheduledInst)
8261         pickedInst->moveBefore(LastScheduledInst);
8262       LastScheduledInst = pickedInst;
8263     }
8264 
8265     BS->schedule(picked, ReadyInsts);
8266     NumToSchedule--;
8267   }
8268   assert(NumToSchedule == 0 && "could not schedule all instructions");
8269 
8270   // Check that we didn't break any of our invariants.
8271 #ifdef EXPENSIVE_CHECKS
8272   BS->verify();
8273 #endif
8274 
8275 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8276   // Check that all schedulable entities got scheduled
8277   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8278     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8279       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8280         assert(SD->IsScheduled && "must be scheduled at this point");
8281       }
8282     });
8283   }
8284 #endif
8285 
8286   // Avoid duplicate scheduling of the block.
8287   BS->ScheduleStart = nullptr;
8288 }
8289 
8290 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8291   // If V is a store, just return the width of the stored value (or value
8292   // truncated just before storing) without traversing the expression tree.
8293   // This is the common case.
8294   if (auto *Store = dyn_cast<StoreInst>(V)) {
8295     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8296       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8297     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8298   }
8299 
8300   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8301     return getVectorElementSize(IEI->getOperand(1));
8302 
8303   auto E = InstrElementSize.find(V);
8304   if (E != InstrElementSize.end())
8305     return E->second;
8306 
8307   // If V is not a store, we can traverse the expression tree to find loads
8308   // that feed it. The type of the loaded value may indicate a more suitable
8309   // width than V's type. We want to base the vector element size on the width
8310   // of memory operations where possible.
8311   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8312   SmallPtrSet<Instruction *, 16> Visited;
8313   if (auto *I = dyn_cast<Instruction>(V)) {
8314     Worklist.emplace_back(I, I->getParent());
8315     Visited.insert(I);
8316   }
8317 
8318   // Traverse the expression tree in bottom-up order looking for loads. If we
8319   // encounter an instruction we don't yet handle, we give up.
8320   auto Width = 0u;
8321   while (!Worklist.empty()) {
8322     Instruction *I;
8323     BasicBlock *Parent;
8324     std::tie(I, Parent) = Worklist.pop_back_val();
8325 
8326     // We should only be looking at scalar instructions here. If the current
8327     // instruction has a vector type, skip.
8328     auto *Ty = I->getType();
8329     if (isa<VectorType>(Ty))
8330       continue;
8331 
8332     // If the current instruction is a load, update MaxWidth to reflect the
8333     // width of the loaded value.
8334     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8335         isa<ExtractValueInst>(I))
8336       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8337 
8338     // Otherwise, we need to visit the operands of the instruction. We only
8339     // handle the interesting cases from buildTree here. If an operand is an
8340     // instruction we haven't yet visited and from the same basic block as the
8341     // user or the use is a PHI node, we add it to the worklist.
8342     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8343              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8344              isa<UnaryOperator>(I)) {
8345       for (Use &U : I->operands())
8346         if (auto *J = dyn_cast<Instruction>(U.get()))
8347           if (Visited.insert(J).second &&
8348               (isa<PHINode>(I) || J->getParent() == Parent))
8349             Worklist.emplace_back(J, J->getParent());
8350     } else {
8351       break;
8352     }
8353   }
8354 
8355   // If we didn't encounter a memory access in the expression tree, or if we
8356   // gave up for some reason, just return the width of V. Otherwise, return the
8357   // maximum width we found.
8358   if (!Width) {
8359     if (auto *CI = dyn_cast<CmpInst>(V))
8360       V = CI->getOperand(0);
8361     Width = DL->getTypeSizeInBits(V->getType());
8362   }
8363 
8364   for (Instruction *I : Visited)
8365     InstrElementSize[I] = Width;
8366 
8367   return Width;
8368 }
8369 
8370 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8371 // smaller type with a truncation. We collect the values that will be demoted
8372 // in ToDemote and additional roots that require investigating in Roots.
8373 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8374                                   SmallVectorImpl<Value *> &ToDemote,
8375                                   SmallVectorImpl<Value *> &Roots) {
8376   // We can always demote constants.
8377   if (isa<Constant>(V)) {
8378     ToDemote.push_back(V);
8379     return true;
8380   }
8381 
8382   // If the value is not an instruction in the expression with only one use, it
8383   // cannot be demoted.
8384   auto *I = dyn_cast<Instruction>(V);
8385   if (!I || !I->hasOneUse() || !Expr.count(I))
8386     return false;
8387 
8388   switch (I->getOpcode()) {
8389 
8390   // We can always demote truncations and extensions. Since truncations can
8391   // seed additional demotion, we save the truncated value.
8392   case Instruction::Trunc:
8393     Roots.push_back(I->getOperand(0));
8394     break;
8395   case Instruction::ZExt:
8396   case Instruction::SExt:
8397     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8398         isa<InsertElementInst>(I->getOperand(0)))
8399       return false;
8400     break;
8401 
8402   // We can demote certain binary operations if we can demote both of their
8403   // operands.
8404   case Instruction::Add:
8405   case Instruction::Sub:
8406   case Instruction::Mul:
8407   case Instruction::And:
8408   case Instruction::Or:
8409   case Instruction::Xor:
8410     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8411         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8412       return false;
8413     break;
8414 
8415   // We can demote selects if we can demote their true and false values.
8416   case Instruction::Select: {
8417     SelectInst *SI = cast<SelectInst>(I);
8418     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8419         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8420       return false;
8421     break;
8422   }
8423 
8424   // We can demote phis if we can demote all their incoming operands. Note that
8425   // we don't need to worry about cycles since we ensure single use above.
8426   case Instruction::PHI: {
8427     PHINode *PN = cast<PHINode>(I);
8428     for (Value *IncValue : PN->incoming_values())
8429       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8430         return false;
8431     break;
8432   }
8433 
8434   // Otherwise, conservatively give up.
8435   default:
8436     return false;
8437   }
8438 
8439   // Record the value that we can demote.
8440   ToDemote.push_back(V);
8441   return true;
8442 }
8443 
8444 void BoUpSLP::computeMinimumValueSizes() {
8445   // If there are no external uses, the expression tree must be rooted by a
8446   // store. We can't demote in-memory values, so there is nothing to do here.
8447   if (ExternalUses.empty())
8448     return;
8449 
8450   // We only attempt to truncate integer expressions.
8451   auto &TreeRoot = VectorizableTree[0]->Scalars;
8452   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8453   if (!TreeRootIT)
8454     return;
8455 
8456   // If the expression is not rooted by a store, these roots should have
8457   // external uses. We will rely on InstCombine to rewrite the expression in
8458   // the narrower type. However, InstCombine only rewrites single-use values.
8459   // This means that if a tree entry other than a root is used externally, it
8460   // must have multiple uses and InstCombine will not rewrite it. The code
8461   // below ensures that only the roots are used externally.
8462   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8463   for (auto &EU : ExternalUses)
8464     if (!Expr.erase(EU.Scalar))
8465       return;
8466   if (!Expr.empty())
8467     return;
8468 
8469   // Collect the scalar values of the vectorizable expression. We will use this
8470   // context to determine which values can be demoted. If we see a truncation,
8471   // we mark it as seeding another demotion.
8472   for (auto &EntryPtr : VectorizableTree)
8473     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8474 
8475   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8476   // have a single external user that is not in the vectorizable tree.
8477   for (auto *Root : TreeRoot)
8478     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8479       return;
8480 
8481   // Conservatively determine if we can actually truncate the roots of the
8482   // expression. Collect the values that can be demoted in ToDemote and
8483   // additional roots that require investigating in Roots.
8484   SmallVector<Value *, 32> ToDemote;
8485   SmallVector<Value *, 4> Roots;
8486   for (auto *Root : TreeRoot)
8487     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8488       return;
8489 
8490   // The maximum bit width required to represent all the values that can be
8491   // demoted without loss of precision. It would be safe to truncate the roots
8492   // of the expression to this width.
8493   auto MaxBitWidth = 8u;
8494 
8495   // We first check if all the bits of the roots are demanded. If they're not,
8496   // we can truncate the roots to this narrower type.
8497   for (auto *Root : TreeRoot) {
8498     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8499     MaxBitWidth = std::max<unsigned>(
8500         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8501   }
8502 
8503   // True if the roots can be zero-extended back to their original type, rather
8504   // than sign-extended. We know that if the leading bits are not demanded, we
8505   // can safely zero-extend. So we initialize IsKnownPositive to True.
8506   bool IsKnownPositive = true;
8507 
8508   // If all the bits of the roots are demanded, we can try a little harder to
8509   // compute a narrower type. This can happen, for example, if the roots are
8510   // getelementptr indices. InstCombine promotes these indices to the pointer
8511   // width. Thus, all their bits are technically demanded even though the
8512   // address computation might be vectorized in a smaller type.
8513   //
8514   // We start by looking at each entry that can be demoted. We compute the
8515   // maximum bit width required to store the scalar by using ValueTracking to
8516   // compute the number of high-order bits we can truncate.
8517   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8518       llvm::all_of(TreeRoot, [](Value *R) {
8519         assert(R->hasOneUse() && "Root should have only one use!");
8520         return isa<GetElementPtrInst>(R->user_back());
8521       })) {
8522     MaxBitWidth = 8u;
8523 
8524     // Determine if the sign bit of all the roots is known to be zero. If not,
8525     // IsKnownPositive is set to False.
8526     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8527       KnownBits Known = computeKnownBits(R, *DL);
8528       return Known.isNonNegative();
8529     });
8530 
8531     // Determine the maximum number of bits required to store the scalar
8532     // values.
8533     for (auto *Scalar : ToDemote) {
8534       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8535       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8536       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8537     }
8538 
8539     // If we can't prove that the sign bit is zero, we must add one to the
8540     // maximum bit width to account for the unknown sign bit. This preserves
8541     // the existing sign bit so we can safely sign-extend the root back to the
8542     // original type. Otherwise, if we know the sign bit is zero, we will
8543     // zero-extend the root instead.
8544     //
8545     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8546     //        one to the maximum bit width will yield a larger-than-necessary
8547     //        type. In general, we need to add an extra bit only if we can't
8548     //        prove that the upper bit of the original type is equal to the
8549     //        upper bit of the proposed smaller type. If these two bits are the
8550     //        same (either zero or one) we know that sign-extending from the
8551     //        smaller type will result in the same value. Here, since we can't
8552     //        yet prove this, we are just making the proposed smaller type
8553     //        larger to ensure correctness.
8554     if (!IsKnownPositive)
8555       ++MaxBitWidth;
8556   }
8557 
8558   // Round MaxBitWidth up to the next power-of-two.
8559   if (!isPowerOf2_64(MaxBitWidth))
8560     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8561 
8562   // If the maximum bit width we compute is less than the with of the roots'
8563   // type, we can proceed with the narrowing. Otherwise, do nothing.
8564   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8565     return;
8566 
8567   // If we can truncate the root, we must collect additional values that might
8568   // be demoted as a result. That is, those seeded by truncations we will
8569   // modify.
8570   while (!Roots.empty())
8571     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8572 
8573   // Finally, map the values we can demote to the maximum bit with we computed.
8574   for (auto *Scalar : ToDemote)
8575     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8576 }
8577 
8578 namespace {
8579 
8580 /// The SLPVectorizer Pass.
8581 struct SLPVectorizer : public FunctionPass {
8582   SLPVectorizerPass Impl;
8583 
8584   /// Pass identification, replacement for typeid
8585   static char ID;
8586 
8587   explicit SLPVectorizer() : FunctionPass(ID) {
8588     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8589   }
8590 
8591   bool doInitialization(Module &M) override { return false; }
8592 
8593   bool runOnFunction(Function &F) override {
8594     if (skipFunction(F))
8595       return false;
8596 
8597     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8598     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8599     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8600     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8601     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8602     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8603     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8604     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8605     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8606     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8607 
8608     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8609   }
8610 
8611   void getAnalysisUsage(AnalysisUsage &AU) const override {
8612     FunctionPass::getAnalysisUsage(AU);
8613     AU.addRequired<AssumptionCacheTracker>();
8614     AU.addRequired<ScalarEvolutionWrapperPass>();
8615     AU.addRequired<AAResultsWrapperPass>();
8616     AU.addRequired<TargetTransformInfoWrapperPass>();
8617     AU.addRequired<LoopInfoWrapperPass>();
8618     AU.addRequired<DominatorTreeWrapperPass>();
8619     AU.addRequired<DemandedBitsWrapperPass>();
8620     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8621     AU.addRequired<InjectTLIMappingsLegacy>();
8622     AU.addPreserved<LoopInfoWrapperPass>();
8623     AU.addPreserved<DominatorTreeWrapperPass>();
8624     AU.addPreserved<AAResultsWrapperPass>();
8625     AU.addPreserved<GlobalsAAWrapperPass>();
8626     AU.setPreservesCFG();
8627   }
8628 };
8629 
8630 } // end anonymous namespace
8631 
8632 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8633   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8634   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8635   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8636   auto *AA = &AM.getResult<AAManager>(F);
8637   auto *LI = &AM.getResult<LoopAnalysis>(F);
8638   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8639   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8640   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8641   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8642 
8643   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8644   if (!Changed)
8645     return PreservedAnalyses::all();
8646 
8647   PreservedAnalyses PA;
8648   PA.preserveSet<CFGAnalyses>();
8649   return PA;
8650 }
8651 
8652 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8653                                 TargetTransformInfo *TTI_,
8654                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8655                                 LoopInfo *LI_, DominatorTree *DT_,
8656                                 AssumptionCache *AC_, DemandedBits *DB_,
8657                                 OptimizationRemarkEmitter *ORE_) {
8658   if (!RunSLPVectorization)
8659     return false;
8660   SE = SE_;
8661   TTI = TTI_;
8662   TLI = TLI_;
8663   AA = AA_;
8664   LI = LI_;
8665   DT = DT_;
8666   AC = AC_;
8667   DB = DB_;
8668   DL = &F.getParent()->getDataLayout();
8669 
8670   Stores.clear();
8671   GEPs.clear();
8672   bool Changed = false;
8673 
8674   // If the target claims to have no vector registers don't attempt
8675   // vectorization.
8676   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8677     LLVM_DEBUG(
8678         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8679     return false;
8680   }
8681 
8682   // Don't vectorize when the attribute NoImplicitFloat is used.
8683   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8684     return false;
8685 
8686   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8687 
8688   // Use the bottom up slp vectorizer to construct chains that start with
8689   // store instructions.
8690   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8691 
8692   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8693   // delete instructions.
8694 
8695   // Update DFS numbers now so that we can use them for ordering.
8696   DT->updateDFSNumbers();
8697 
8698   // Scan the blocks in the function in post order.
8699   for (auto BB : post_order(&F.getEntryBlock())) {
8700     collectSeedInstructions(BB);
8701 
8702     // Vectorize trees that end at stores.
8703     if (!Stores.empty()) {
8704       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8705                         << " underlying objects.\n");
8706       Changed |= vectorizeStoreChains(R);
8707     }
8708 
8709     // Vectorize trees that end at reductions.
8710     Changed |= vectorizeChainsInBlock(BB, R);
8711 
8712     // Vectorize the index computations of getelementptr instructions. This
8713     // is primarily intended to catch gather-like idioms ending at
8714     // non-consecutive loads.
8715     if (!GEPs.empty()) {
8716       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8717                         << " underlying objects.\n");
8718       Changed |= vectorizeGEPIndices(BB, R);
8719     }
8720   }
8721 
8722   if (Changed) {
8723     R.optimizeGatherSequence();
8724     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8725   }
8726   return Changed;
8727 }
8728 
8729 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8730                                             unsigned Idx) {
8731   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8732                     << "\n");
8733   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8734   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8735   unsigned VF = Chain.size();
8736 
8737   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8738     return false;
8739 
8740   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8741                     << "\n");
8742 
8743   R.buildTree(Chain);
8744   if (R.isTreeTinyAndNotFullyVectorizable())
8745     return false;
8746   if (R.isLoadCombineCandidate())
8747     return false;
8748   R.reorderTopToBottom();
8749   R.reorderBottomToTop();
8750   R.buildExternalUses();
8751 
8752   R.computeMinimumValueSizes();
8753 
8754   InstructionCost Cost = R.getTreeCost();
8755 
8756   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8757   if (Cost < -SLPCostThreshold) {
8758     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8759 
8760     using namespace ore;
8761 
8762     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8763                                         cast<StoreInst>(Chain[0]))
8764                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8765                      << " and with tree size "
8766                      << NV("TreeSize", R.getTreeSize()));
8767 
8768     R.vectorizeTree();
8769     return true;
8770   }
8771 
8772   return false;
8773 }
8774 
8775 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8776                                         BoUpSLP &R) {
8777   // We may run into multiple chains that merge into a single chain. We mark the
8778   // stores that we vectorized so that we don't visit the same store twice.
8779   BoUpSLP::ValueSet VectorizedStores;
8780   bool Changed = false;
8781 
8782   int E = Stores.size();
8783   SmallBitVector Tails(E, false);
8784   int MaxIter = MaxStoreLookup.getValue();
8785   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8786       E, std::make_pair(E, INT_MAX));
8787   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8788   int IterCnt;
8789   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8790                                   &CheckedPairs,
8791                                   &ConsecutiveChain](int K, int Idx) {
8792     if (IterCnt >= MaxIter)
8793       return true;
8794     if (CheckedPairs[Idx].test(K))
8795       return ConsecutiveChain[K].second == 1 &&
8796              ConsecutiveChain[K].first == Idx;
8797     ++IterCnt;
8798     CheckedPairs[Idx].set(K);
8799     CheckedPairs[K].set(Idx);
8800     Optional<int> Diff = getPointersDiff(
8801         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8802         Stores[Idx]->getValueOperand()->getType(),
8803         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8804     if (!Diff || *Diff == 0)
8805       return false;
8806     int Val = *Diff;
8807     if (Val < 0) {
8808       if (ConsecutiveChain[Idx].second > -Val) {
8809         Tails.set(K);
8810         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8811       }
8812       return false;
8813     }
8814     if (ConsecutiveChain[K].second <= Val)
8815       return false;
8816 
8817     Tails.set(Idx);
8818     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8819     return Val == 1;
8820   };
8821   // Do a quadratic search on all of the given stores in reverse order and find
8822   // all of the pairs of stores that follow each other.
8823   for (int Idx = E - 1; Idx >= 0; --Idx) {
8824     // If a store has multiple consecutive store candidates, search according
8825     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8826     // This is because usually pairing with immediate succeeding or preceding
8827     // candidate create the best chance to find slp vectorization opportunity.
8828     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8829     IterCnt = 0;
8830     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8831       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8832           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8833         break;
8834   }
8835 
8836   // Tracks if we tried to vectorize stores starting from the given tail
8837   // already.
8838   SmallBitVector TriedTails(E, false);
8839   // For stores that start but don't end a link in the chain:
8840   for (int Cnt = E; Cnt > 0; --Cnt) {
8841     int I = Cnt - 1;
8842     if (ConsecutiveChain[I].first == E || Tails.test(I))
8843       continue;
8844     // We found a store instr that starts a chain. Now follow the chain and try
8845     // to vectorize it.
8846     BoUpSLP::ValueList Operands;
8847     // Collect the chain into a list.
8848     while (I != E && !VectorizedStores.count(Stores[I])) {
8849       Operands.push_back(Stores[I]);
8850       Tails.set(I);
8851       if (ConsecutiveChain[I].second != 1) {
8852         // Mark the new end in the chain and go back, if required. It might be
8853         // required if the original stores come in reversed order, for example.
8854         if (ConsecutiveChain[I].first != E &&
8855             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8856             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8857           TriedTails.set(I);
8858           Tails.reset(ConsecutiveChain[I].first);
8859           if (Cnt < ConsecutiveChain[I].first + 2)
8860             Cnt = ConsecutiveChain[I].first + 2;
8861         }
8862         break;
8863       }
8864       // Move to the next value in the chain.
8865       I = ConsecutiveChain[I].first;
8866     }
8867     assert(!Operands.empty() && "Expected non-empty list of stores.");
8868 
8869     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8870     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8871     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8872 
8873     unsigned MinVF = R.getMinVF(EltSize);
8874     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8875                               MaxElts);
8876 
8877     // FIXME: Is division-by-2 the correct step? Should we assert that the
8878     // register size is a power-of-2?
8879     unsigned StartIdx = 0;
8880     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8881       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8882         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8883         if (!VectorizedStores.count(Slice.front()) &&
8884             !VectorizedStores.count(Slice.back()) &&
8885             vectorizeStoreChain(Slice, R, Cnt)) {
8886           // Mark the vectorized stores so that we don't vectorize them again.
8887           VectorizedStores.insert(Slice.begin(), Slice.end());
8888           Changed = true;
8889           // If we vectorized initial block, no need to try to vectorize it
8890           // again.
8891           if (Cnt == StartIdx)
8892             StartIdx += Size;
8893           Cnt += Size;
8894           continue;
8895         }
8896         ++Cnt;
8897       }
8898       // Check if the whole array was vectorized already - exit.
8899       if (StartIdx >= Operands.size())
8900         break;
8901     }
8902   }
8903 
8904   return Changed;
8905 }
8906 
8907 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8908   // Initialize the collections. We will make a single pass over the block.
8909   Stores.clear();
8910   GEPs.clear();
8911 
8912   // Visit the store and getelementptr instructions in BB and organize them in
8913   // Stores and GEPs according to the underlying objects of their pointer
8914   // operands.
8915   for (Instruction &I : *BB) {
8916     // Ignore store instructions that are volatile or have a pointer operand
8917     // that doesn't point to a scalar type.
8918     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8919       if (!SI->isSimple())
8920         continue;
8921       if (!isValidElementType(SI->getValueOperand()->getType()))
8922         continue;
8923       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8924     }
8925 
8926     // Ignore getelementptr instructions that have more than one index, a
8927     // constant index, or a pointer operand that doesn't point to a scalar
8928     // type.
8929     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8930       auto Idx = GEP->idx_begin()->get();
8931       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8932         continue;
8933       if (!isValidElementType(Idx->getType()))
8934         continue;
8935       if (GEP->getType()->isVectorTy())
8936         continue;
8937       GEPs[GEP->getPointerOperand()].push_back(GEP);
8938     }
8939   }
8940 }
8941 
8942 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8943   if (!A || !B)
8944     return false;
8945   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8946     return false;
8947   Value *VL[] = {A, B};
8948   return tryToVectorizeList(VL, R);
8949 }
8950 
8951 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8952                                            bool LimitForRegisterSize) {
8953   if (VL.size() < 2)
8954     return false;
8955 
8956   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8957                     << VL.size() << ".\n");
8958 
8959   // Check that all of the parts are instructions of the same type,
8960   // we permit an alternate opcode via InstructionsState.
8961   InstructionsState S = getSameOpcode(VL);
8962   if (!S.getOpcode())
8963     return false;
8964 
8965   Instruction *I0 = cast<Instruction>(S.OpValue);
8966   // Make sure invalid types (including vector type) are rejected before
8967   // determining vectorization factor for scalar instructions.
8968   for (Value *V : VL) {
8969     Type *Ty = V->getType();
8970     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8971       // NOTE: the following will give user internal llvm type name, which may
8972       // not be useful.
8973       R.getORE()->emit([&]() {
8974         std::string type_str;
8975         llvm::raw_string_ostream rso(type_str);
8976         Ty->print(rso);
8977         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8978                << "Cannot SLP vectorize list: type "
8979                << rso.str() + " is unsupported by vectorizer";
8980       });
8981       return false;
8982     }
8983   }
8984 
8985   unsigned Sz = R.getVectorElementSize(I0);
8986   unsigned MinVF = R.getMinVF(Sz);
8987   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8988   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8989   if (MaxVF < 2) {
8990     R.getORE()->emit([&]() {
8991       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8992              << "Cannot SLP vectorize list: vectorization factor "
8993              << "less than 2 is not supported";
8994     });
8995     return false;
8996   }
8997 
8998   bool Changed = false;
8999   bool CandidateFound = false;
9000   InstructionCost MinCost = SLPCostThreshold.getValue();
9001   Type *ScalarTy = VL[0]->getType();
9002   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9003     ScalarTy = IE->getOperand(1)->getType();
9004 
9005   unsigned NextInst = 0, MaxInst = VL.size();
9006   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9007     // No actual vectorization should happen, if number of parts is the same as
9008     // provided vectorization factor (i.e. the scalar type is used for vector
9009     // code during codegen).
9010     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9011     if (TTI->getNumberOfParts(VecTy) == VF)
9012       continue;
9013     for (unsigned I = NextInst; I < MaxInst; ++I) {
9014       unsigned OpsWidth = 0;
9015 
9016       if (I + VF > MaxInst)
9017         OpsWidth = MaxInst - I;
9018       else
9019         OpsWidth = VF;
9020 
9021       if (!isPowerOf2_32(OpsWidth))
9022         continue;
9023 
9024       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9025           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9026         break;
9027 
9028       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9029       // Check that a previous iteration of this loop did not delete the Value.
9030       if (llvm::any_of(Ops, [&R](Value *V) {
9031             auto *I = dyn_cast<Instruction>(V);
9032             return I && R.isDeleted(I);
9033           }))
9034         continue;
9035 
9036       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9037                         << "\n");
9038 
9039       R.buildTree(Ops);
9040       if (R.isTreeTinyAndNotFullyVectorizable())
9041         continue;
9042       R.reorderTopToBottom();
9043       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9044       R.buildExternalUses();
9045 
9046       R.computeMinimumValueSizes();
9047       InstructionCost Cost = R.getTreeCost();
9048       CandidateFound = true;
9049       MinCost = std::min(MinCost, Cost);
9050 
9051       if (Cost < -SLPCostThreshold) {
9052         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9053         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9054                                                     cast<Instruction>(Ops[0]))
9055                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9056                                  << " and with tree size "
9057                                  << ore::NV("TreeSize", R.getTreeSize()));
9058 
9059         R.vectorizeTree();
9060         // Move to the next bundle.
9061         I += VF - 1;
9062         NextInst = I + 1;
9063         Changed = true;
9064       }
9065     }
9066   }
9067 
9068   if (!Changed && CandidateFound) {
9069     R.getORE()->emit([&]() {
9070       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9071              << "List vectorization was possible but not beneficial with cost "
9072              << ore::NV("Cost", MinCost) << " >= "
9073              << ore::NV("Treshold", -SLPCostThreshold);
9074     });
9075   } else if (!Changed) {
9076     R.getORE()->emit([&]() {
9077       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9078              << "Cannot SLP vectorize list: vectorization was impossible"
9079              << " with available vectorization factors";
9080     });
9081   }
9082   return Changed;
9083 }
9084 
9085 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9086   if (!I)
9087     return false;
9088 
9089   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9090     return false;
9091 
9092   Value *P = I->getParent();
9093 
9094   // Vectorize in current basic block only.
9095   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9096   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9097   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9098     return false;
9099 
9100   // Try to vectorize V.
9101   if (tryToVectorizePair(Op0, Op1, R))
9102     return true;
9103 
9104   auto *A = dyn_cast<BinaryOperator>(Op0);
9105   auto *B = dyn_cast<BinaryOperator>(Op1);
9106   // Try to skip B.
9107   if (B && B->hasOneUse()) {
9108     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9109     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9110     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9111       return true;
9112     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9113       return true;
9114   }
9115 
9116   // Try to skip A.
9117   if (A && A->hasOneUse()) {
9118     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9119     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9120     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9121       return true;
9122     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9123       return true;
9124   }
9125   return false;
9126 }
9127 
9128 namespace {
9129 
9130 /// Model horizontal reductions.
9131 ///
9132 /// A horizontal reduction is a tree of reduction instructions that has values
9133 /// that can be put into a vector as its leaves. For example:
9134 ///
9135 /// mul mul mul mul
9136 ///  \  /    \  /
9137 ///   +       +
9138 ///    \     /
9139 ///       +
9140 /// This tree has "mul" as its leaf values and "+" as its reduction
9141 /// instructions. A reduction can feed into a store or a binary operation
9142 /// feeding a phi.
9143 ///    ...
9144 ///    \  /
9145 ///     +
9146 ///     |
9147 ///  phi +=
9148 ///
9149 ///  Or:
9150 ///    ...
9151 ///    \  /
9152 ///     +
9153 ///     |
9154 ///   *p =
9155 ///
9156 class HorizontalReduction {
9157   using ReductionOpsType = SmallVector<Value *, 16>;
9158   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9159   ReductionOpsListType ReductionOps;
9160   SmallVector<Value *, 32> ReducedVals;
9161   // Use map vector to make stable output.
9162   MapVector<Instruction *, Value *> ExtraArgs;
9163   WeakTrackingVH ReductionRoot;
9164   /// The type of reduction operation.
9165   RecurKind RdxKind;
9166 
9167   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9168 
9169   static bool isCmpSelMinMax(Instruction *I) {
9170     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9171            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9172   }
9173 
9174   // And/or are potentially poison-safe logical patterns like:
9175   // select x, y, false
9176   // select x, true, y
9177   static bool isBoolLogicOp(Instruction *I) {
9178     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9179            match(I, m_LogicalOr(m_Value(), m_Value()));
9180   }
9181 
9182   /// Checks if instruction is associative and can be vectorized.
9183   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9184     if (Kind == RecurKind::None)
9185       return false;
9186 
9187     // Integer ops that map to select instructions or intrinsics are fine.
9188     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9189         isBoolLogicOp(I))
9190       return true;
9191 
9192     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9193       // FP min/max are associative except for NaN and -0.0. We do not
9194       // have to rule out -0.0 here because the intrinsic semantics do not
9195       // specify a fixed result for it.
9196       return I->getFastMathFlags().noNaNs();
9197     }
9198 
9199     return I->isAssociative();
9200   }
9201 
9202   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9203     // Poison-safe 'or' takes the form: select X, true, Y
9204     // To make that work with the normal operand processing, we skip the
9205     // true value operand.
9206     // TODO: Change the code and data structures to handle this without a hack.
9207     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9208       return I->getOperand(2);
9209     return I->getOperand(Index);
9210   }
9211 
9212   /// Checks if the ParentStackElem.first should be marked as a reduction
9213   /// operation with an extra argument or as extra argument itself.
9214   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9215                     Value *ExtraArg) {
9216     if (ExtraArgs.count(ParentStackElem.first)) {
9217       ExtraArgs[ParentStackElem.first] = nullptr;
9218       // We ran into something like:
9219       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9220       // The whole ParentStackElem.first should be considered as an extra value
9221       // in this case.
9222       // Do not perform analysis of remaining operands of ParentStackElem.first
9223       // instruction, this whole instruction is an extra argument.
9224       ParentStackElem.second = INVALID_OPERAND_INDEX;
9225     } else {
9226       // We ran into something like:
9227       // ParentStackElem.first += ... + ExtraArg + ...
9228       ExtraArgs[ParentStackElem.first] = ExtraArg;
9229     }
9230   }
9231 
9232   /// Creates reduction operation with the current opcode.
9233   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9234                          Value *RHS, const Twine &Name, bool UseSelect) {
9235     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9236     switch (Kind) {
9237     case RecurKind::Or:
9238       if (UseSelect &&
9239           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9240         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9241       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9242                                  Name);
9243     case RecurKind::And:
9244       if (UseSelect &&
9245           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9246         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9247       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9248                                  Name);
9249     case RecurKind::Add:
9250     case RecurKind::Mul:
9251     case RecurKind::Xor:
9252     case RecurKind::FAdd:
9253     case RecurKind::FMul:
9254       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9255                                  Name);
9256     case RecurKind::FMax:
9257       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9258     case RecurKind::FMin:
9259       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9260     case RecurKind::SMax:
9261       if (UseSelect) {
9262         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9263         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9264       }
9265       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9266     case RecurKind::SMin:
9267       if (UseSelect) {
9268         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9269         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9270       }
9271       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9272     case RecurKind::UMax:
9273       if (UseSelect) {
9274         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9275         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9276       }
9277       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9278     case RecurKind::UMin:
9279       if (UseSelect) {
9280         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9281         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9282       }
9283       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9284     default:
9285       llvm_unreachable("Unknown reduction operation.");
9286     }
9287   }
9288 
9289   /// Creates reduction operation with the current opcode with the IR flags
9290   /// from \p ReductionOps.
9291   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9292                          Value *RHS, const Twine &Name,
9293                          const ReductionOpsListType &ReductionOps) {
9294     bool UseSelect = ReductionOps.size() == 2 ||
9295                      // Logical or/and.
9296                      (ReductionOps.size() == 1 &&
9297                       isa<SelectInst>(ReductionOps.front().front()));
9298     assert((!UseSelect || ReductionOps.size() != 2 ||
9299             isa<SelectInst>(ReductionOps[1][0])) &&
9300            "Expected cmp + select pairs for reduction");
9301     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9302     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9303       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9304         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9305         propagateIRFlags(Op, ReductionOps[1]);
9306         return Op;
9307       }
9308     }
9309     propagateIRFlags(Op, ReductionOps[0]);
9310     return Op;
9311   }
9312 
9313   /// Creates reduction operation with the current opcode with the IR flags
9314   /// from \p I.
9315   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9316                          Value *RHS, const Twine &Name, Instruction *I) {
9317     auto *SelI = dyn_cast<SelectInst>(I);
9318     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9319     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9320       if (auto *Sel = dyn_cast<SelectInst>(Op))
9321         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9322     }
9323     propagateIRFlags(Op, I);
9324     return Op;
9325   }
9326 
9327   static RecurKind getRdxKind(Instruction *I) {
9328     assert(I && "Expected instruction for reduction matching");
9329     if (match(I, m_Add(m_Value(), m_Value())))
9330       return RecurKind::Add;
9331     if (match(I, m_Mul(m_Value(), m_Value())))
9332       return RecurKind::Mul;
9333     if (match(I, m_And(m_Value(), m_Value())) ||
9334         match(I, m_LogicalAnd(m_Value(), m_Value())))
9335       return RecurKind::And;
9336     if (match(I, m_Or(m_Value(), m_Value())) ||
9337         match(I, m_LogicalOr(m_Value(), m_Value())))
9338       return RecurKind::Or;
9339     if (match(I, m_Xor(m_Value(), m_Value())))
9340       return RecurKind::Xor;
9341     if (match(I, m_FAdd(m_Value(), m_Value())))
9342       return RecurKind::FAdd;
9343     if (match(I, m_FMul(m_Value(), m_Value())))
9344       return RecurKind::FMul;
9345 
9346     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9347       return RecurKind::FMax;
9348     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9349       return RecurKind::FMin;
9350 
9351     // This matches either cmp+select or intrinsics. SLP is expected to handle
9352     // either form.
9353     // TODO: If we are canonicalizing to intrinsics, we can remove several
9354     //       special-case paths that deal with selects.
9355     if (match(I, m_SMax(m_Value(), m_Value())))
9356       return RecurKind::SMax;
9357     if (match(I, m_SMin(m_Value(), m_Value())))
9358       return RecurKind::SMin;
9359     if (match(I, m_UMax(m_Value(), m_Value())))
9360       return RecurKind::UMax;
9361     if (match(I, m_UMin(m_Value(), m_Value())))
9362       return RecurKind::UMin;
9363 
9364     if (auto *Select = dyn_cast<SelectInst>(I)) {
9365       // Try harder: look for min/max pattern based on instructions producing
9366       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9367       // During the intermediate stages of SLP, it's very common to have
9368       // pattern like this (since optimizeGatherSequence is run only once
9369       // at the end):
9370       // %1 = extractelement <2 x i32> %a, i32 0
9371       // %2 = extractelement <2 x i32> %a, i32 1
9372       // %cond = icmp sgt i32 %1, %2
9373       // %3 = extractelement <2 x i32> %a, i32 0
9374       // %4 = extractelement <2 x i32> %a, i32 1
9375       // %select = select i1 %cond, i32 %3, i32 %4
9376       CmpInst::Predicate Pred;
9377       Instruction *L1;
9378       Instruction *L2;
9379 
9380       Value *LHS = Select->getTrueValue();
9381       Value *RHS = Select->getFalseValue();
9382       Value *Cond = Select->getCondition();
9383 
9384       // TODO: Support inverse predicates.
9385       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9386         if (!isa<ExtractElementInst>(RHS) ||
9387             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9388           return RecurKind::None;
9389       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9390         if (!isa<ExtractElementInst>(LHS) ||
9391             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9392           return RecurKind::None;
9393       } else {
9394         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9395           return RecurKind::None;
9396         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9397             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9398             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9399           return RecurKind::None;
9400       }
9401 
9402       switch (Pred) {
9403       default:
9404         return RecurKind::None;
9405       case CmpInst::ICMP_SGT:
9406       case CmpInst::ICMP_SGE:
9407         return RecurKind::SMax;
9408       case CmpInst::ICMP_SLT:
9409       case CmpInst::ICMP_SLE:
9410         return RecurKind::SMin;
9411       case CmpInst::ICMP_UGT:
9412       case CmpInst::ICMP_UGE:
9413         return RecurKind::UMax;
9414       case CmpInst::ICMP_ULT:
9415       case CmpInst::ICMP_ULE:
9416         return RecurKind::UMin;
9417       }
9418     }
9419     return RecurKind::None;
9420   }
9421 
9422   /// Get the index of the first operand.
9423   static unsigned getFirstOperandIndex(Instruction *I) {
9424     return isCmpSelMinMax(I) ? 1 : 0;
9425   }
9426 
9427   /// Total number of operands in the reduction operation.
9428   static unsigned getNumberOfOperands(Instruction *I) {
9429     return isCmpSelMinMax(I) ? 3 : 2;
9430   }
9431 
9432   /// Checks if the instruction is in basic block \p BB.
9433   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9434   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9435     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9436       auto *Sel = cast<SelectInst>(I);
9437       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9438       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9439     }
9440     return I->getParent() == BB;
9441   }
9442 
9443   /// Expected number of uses for reduction operations/reduced values.
9444   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9445     if (IsCmpSelMinMax) {
9446       // SelectInst must be used twice while the condition op must have single
9447       // use only.
9448       if (auto *Sel = dyn_cast<SelectInst>(I))
9449         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9450       return I->hasNUses(2);
9451     }
9452 
9453     // Arithmetic reduction operation must be used once only.
9454     return I->hasOneUse();
9455   }
9456 
9457   /// Initializes the list of reduction operations.
9458   void initReductionOps(Instruction *I) {
9459     if (isCmpSelMinMax(I))
9460       ReductionOps.assign(2, ReductionOpsType());
9461     else
9462       ReductionOps.assign(1, ReductionOpsType());
9463   }
9464 
9465   /// Add all reduction operations for the reduction instruction \p I.
9466   void addReductionOps(Instruction *I) {
9467     if (isCmpSelMinMax(I)) {
9468       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9469       ReductionOps[1].emplace_back(I);
9470     } else {
9471       ReductionOps[0].emplace_back(I);
9472     }
9473   }
9474 
9475   static Value *getLHS(RecurKind Kind, Instruction *I) {
9476     if (Kind == RecurKind::None)
9477       return nullptr;
9478     return I->getOperand(getFirstOperandIndex(I));
9479   }
9480   static Value *getRHS(RecurKind Kind, Instruction *I) {
9481     if (Kind == RecurKind::None)
9482       return nullptr;
9483     return I->getOperand(getFirstOperandIndex(I) + 1);
9484   }
9485 
9486 public:
9487   HorizontalReduction() = default;
9488 
9489   /// Try to find a reduction tree.
9490   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9491     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9492            "Phi needs to use the binary operator");
9493     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9494             isa<IntrinsicInst>(Inst)) &&
9495            "Expected binop, select, or intrinsic for reduction matching");
9496     RdxKind = getRdxKind(Inst);
9497 
9498     // We could have a initial reductions that is not an add.
9499     //  r *= v1 + v2 + v3 + v4
9500     // In such a case start looking for a tree rooted in the first '+'.
9501     if (Phi) {
9502       if (getLHS(RdxKind, Inst) == Phi) {
9503         Phi = nullptr;
9504         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9505         if (!Inst)
9506           return false;
9507         RdxKind = getRdxKind(Inst);
9508       } else if (getRHS(RdxKind, Inst) == Phi) {
9509         Phi = nullptr;
9510         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9511         if (!Inst)
9512           return false;
9513         RdxKind = getRdxKind(Inst);
9514       }
9515     }
9516 
9517     if (!isVectorizable(RdxKind, Inst))
9518       return false;
9519 
9520     // Analyze "regular" integer/FP types for reductions - no target-specific
9521     // types or pointers.
9522     Type *Ty = Inst->getType();
9523     if (!isValidElementType(Ty) || Ty->isPointerTy())
9524       return false;
9525 
9526     // Though the ultimate reduction may have multiple uses, its condition must
9527     // have only single use.
9528     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9529       if (!Sel->getCondition()->hasOneUse())
9530         return false;
9531 
9532     ReductionRoot = Inst;
9533 
9534     // The opcode for leaf values that we perform a reduction on.
9535     // For example: load(x) + load(y) + load(z) + fptoui(w)
9536     // The leaf opcode for 'w' does not match, so we don't include it as a
9537     // potential candidate for the reduction.
9538     unsigned LeafOpcode = 0;
9539 
9540     // Post-order traverse the reduction tree starting at Inst. We only handle
9541     // true trees containing binary operators or selects.
9542     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9543     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9544     initReductionOps(Inst);
9545     while (!Stack.empty()) {
9546       Instruction *TreeN = Stack.back().first;
9547       unsigned EdgeToVisit = Stack.back().second++;
9548       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9549       bool IsReducedValue = TreeRdxKind != RdxKind;
9550 
9551       // Postorder visit.
9552       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9553         if (IsReducedValue)
9554           ReducedVals.push_back(TreeN);
9555         else {
9556           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9557           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9558             // Check if TreeN is an extra argument of its parent operation.
9559             if (Stack.size() <= 1) {
9560               // TreeN can't be an extra argument as it is a root reduction
9561               // operation.
9562               return false;
9563             }
9564             // Yes, TreeN is an extra argument, do not add it to a list of
9565             // reduction operations.
9566             // Stack[Stack.size() - 2] always points to the parent operation.
9567             markExtraArg(Stack[Stack.size() - 2], TreeN);
9568             ExtraArgs.erase(TreeN);
9569           } else
9570             addReductionOps(TreeN);
9571         }
9572         // Retract.
9573         Stack.pop_back();
9574         continue;
9575       }
9576 
9577       // Visit operands.
9578       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9579       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9580       if (!EdgeInst) {
9581         // Edge value is not a reduction instruction or a leaf instruction.
9582         // (It may be a constant, function argument, or something else.)
9583         markExtraArg(Stack.back(), EdgeVal);
9584         continue;
9585       }
9586       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9587       // Continue analysis if the next operand is a reduction operation or
9588       // (possibly) a leaf value. If the leaf value opcode is not set,
9589       // the first met operation != reduction operation is considered as the
9590       // leaf opcode.
9591       // Only handle trees in the current basic block.
9592       // Each tree node needs to have minimal number of users except for the
9593       // ultimate reduction.
9594       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9595       if (EdgeInst != Phi && EdgeInst != Inst &&
9596           hasSameParent(EdgeInst, Inst->getParent()) &&
9597           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9598           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9599         if (IsRdxInst) {
9600           // We need to be able to reassociate the reduction operations.
9601           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9602             // I is an extra argument for TreeN (its parent operation).
9603             markExtraArg(Stack.back(), EdgeInst);
9604             continue;
9605           }
9606         } else if (!LeafOpcode) {
9607           LeafOpcode = EdgeInst->getOpcode();
9608         }
9609         Stack.push_back(
9610             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9611         continue;
9612       }
9613       // I is an extra argument for TreeN (its parent operation).
9614       markExtraArg(Stack.back(), EdgeInst);
9615     }
9616     return true;
9617   }
9618 
9619   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9620   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9621     // If there are a sufficient number of reduction values, reduce
9622     // to a nearby power-of-2. We can safely generate oversized
9623     // vectors and rely on the backend to split them to legal sizes.
9624     unsigned NumReducedVals = ReducedVals.size();
9625     if (NumReducedVals < 4)
9626       return nullptr;
9627 
9628     // Intersect the fast-math-flags from all reduction operations.
9629     FastMathFlags RdxFMF;
9630     RdxFMF.set();
9631     for (ReductionOpsType &RdxOp : ReductionOps) {
9632       for (Value *RdxVal : RdxOp) {
9633         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9634           RdxFMF &= FPMO->getFastMathFlags();
9635       }
9636     }
9637 
9638     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9639     Builder.setFastMathFlags(RdxFMF);
9640 
9641     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9642     // The same extra argument may be used several times, so log each attempt
9643     // to use it.
9644     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9645       assert(Pair.first && "DebugLoc must be set.");
9646       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9647     }
9648 
9649     // The compare instruction of a min/max is the insertion point for new
9650     // instructions and may be replaced with a new compare instruction.
9651     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9652       assert(isa<SelectInst>(RdxRootInst) &&
9653              "Expected min/max reduction to have select root instruction");
9654       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9655       assert(isa<Instruction>(ScalarCond) &&
9656              "Expected min/max reduction to have compare condition");
9657       return cast<Instruction>(ScalarCond);
9658     };
9659 
9660     // The reduction root is used as the insertion point for new instructions,
9661     // so set it as externally used to prevent it from being deleted.
9662     ExternallyUsedValues[ReductionRoot];
9663     SmallVector<Value *, 16> IgnoreList;
9664     for (ReductionOpsType &RdxOp : ReductionOps)
9665       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9666 
9667     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9668     if (NumReducedVals > ReduxWidth) {
9669       // In the loop below, we are building a tree based on a window of
9670       // 'ReduxWidth' values.
9671       // If the operands of those values have common traits (compare predicate,
9672       // constant operand, etc), then we want to group those together to
9673       // minimize the cost of the reduction.
9674 
9675       // TODO: This should be extended to count common operands for
9676       //       compares and binops.
9677 
9678       // Step 1: Count the number of times each compare predicate occurs.
9679       SmallDenseMap<unsigned, unsigned> PredCountMap;
9680       for (Value *RdxVal : ReducedVals) {
9681         CmpInst::Predicate Pred;
9682         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9683           ++PredCountMap[Pred];
9684       }
9685       // Step 2: Sort the values so the most common predicates come first.
9686       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9687         CmpInst::Predicate PredA, PredB;
9688         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9689             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9690           return PredCountMap[PredA] > PredCountMap[PredB];
9691         }
9692         return false;
9693       });
9694     }
9695 
9696     Value *VectorizedTree = nullptr;
9697     unsigned i = 0;
9698     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9699       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9700       V.buildTree(VL, IgnoreList);
9701       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9702         break;
9703       if (V.isLoadCombineReductionCandidate(RdxKind))
9704         break;
9705       V.reorderTopToBottom();
9706       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9707       V.buildExternalUses(ExternallyUsedValues);
9708 
9709       // For a poison-safe boolean logic reduction, do not replace select
9710       // instructions with logic ops. All reduced values will be frozen (see
9711       // below) to prevent leaking poison.
9712       if (isa<SelectInst>(ReductionRoot) &&
9713           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9714           NumReducedVals != ReduxWidth)
9715         break;
9716 
9717       V.computeMinimumValueSizes();
9718 
9719       // Estimate cost.
9720       InstructionCost TreeCost =
9721           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9722       InstructionCost ReductionCost =
9723           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9724       InstructionCost Cost = TreeCost + ReductionCost;
9725       if (!Cost.isValid()) {
9726         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9727         return nullptr;
9728       }
9729       if (Cost >= -SLPCostThreshold) {
9730         V.getORE()->emit([&]() {
9731           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9732                                           cast<Instruction>(VL[0]))
9733                  << "Vectorizing horizontal reduction is possible"
9734                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9735                  << " and threshold "
9736                  << ore::NV("Threshold", -SLPCostThreshold);
9737         });
9738         break;
9739       }
9740 
9741       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9742                         << Cost << ". (HorRdx)\n");
9743       V.getORE()->emit([&]() {
9744         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9745                                   cast<Instruction>(VL[0]))
9746                << "Vectorized horizontal reduction with cost "
9747                << ore::NV("Cost", Cost) << " and with tree size "
9748                << ore::NV("TreeSize", V.getTreeSize());
9749       });
9750 
9751       // Vectorize a tree.
9752       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9753       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9754 
9755       // Emit a reduction. If the root is a select (min/max idiom), the insert
9756       // point is the compare condition of that select.
9757       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9758       if (isCmpSelMinMax(RdxRootInst))
9759         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9760       else
9761         Builder.SetInsertPoint(RdxRootInst);
9762 
9763       // To prevent poison from leaking across what used to be sequential, safe,
9764       // scalar boolean logic operations, the reduction operand must be frozen.
9765       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9766         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9767 
9768       Value *ReducedSubTree =
9769           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9770 
9771       if (!VectorizedTree) {
9772         // Initialize the final value in the reduction.
9773         VectorizedTree = ReducedSubTree;
9774       } else {
9775         // Update the final value in the reduction.
9776         Builder.SetCurrentDebugLocation(Loc);
9777         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9778                                   ReducedSubTree, "op.rdx", ReductionOps);
9779       }
9780       i += ReduxWidth;
9781       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9782     }
9783 
9784     if (VectorizedTree) {
9785       // Finish the reduction.
9786       for (; i < NumReducedVals; ++i) {
9787         auto *I = cast<Instruction>(ReducedVals[i]);
9788         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9789         VectorizedTree =
9790             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9791       }
9792       for (auto &Pair : ExternallyUsedValues) {
9793         // Add each externally used value to the final reduction.
9794         for (auto *I : Pair.second) {
9795           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9796           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9797                                     Pair.first, "op.extra", I);
9798         }
9799       }
9800 
9801       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9802 
9803       // Mark all scalar reduction ops for deletion, they are replaced by the
9804       // vector reductions.
9805       V.eraseInstructions(IgnoreList);
9806     }
9807     return VectorizedTree;
9808   }
9809 
9810   unsigned numReductionValues() const { return ReducedVals.size(); }
9811 
9812 private:
9813   /// Calculate the cost of a reduction.
9814   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9815                                    Value *FirstReducedVal, unsigned ReduxWidth,
9816                                    FastMathFlags FMF) {
9817     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9818     Type *ScalarTy = FirstReducedVal->getType();
9819     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9820     InstructionCost VectorCost, ScalarCost;
9821     switch (RdxKind) {
9822     case RecurKind::Add:
9823     case RecurKind::Mul:
9824     case RecurKind::Or:
9825     case RecurKind::And:
9826     case RecurKind::Xor:
9827     case RecurKind::FAdd:
9828     case RecurKind::FMul: {
9829       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9830       VectorCost =
9831           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9832       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9833       break;
9834     }
9835     case RecurKind::FMax:
9836     case RecurKind::FMin: {
9837       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9838       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9839       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9840                                                /*IsUnsigned=*/false, CostKind);
9841       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9842       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9843                                            SclCondTy, RdxPred, CostKind) +
9844                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9845                                            SclCondTy, RdxPred, CostKind);
9846       break;
9847     }
9848     case RecurKind::SMax:
9849     case RecurKind::SMin:
9850     case RecurKind::UMax:
9851     case RecurKind::UMin: {
9852       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9853       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9854       bool IsUnsigned =
9855           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9856       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9857                                                CostKind);
9858       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9859       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9860                                            SclCondTy, RdxPred, CostKind) +
9861                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9862                                            SclCondTy, RdxPred, CostKind);
9863       break;
9864     }
9865     default:
9866       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9867     }
9868 
9869     // Scalar cost is repeated for N-1 elements.
9870     ScalarCost *= (ReduxWidth - 1);
9871     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9872                       << " for reduction that starts with " << *FirstReducedVal
9873                       << " (It is a splitting reduction)\n");
9874     return VectorCost - ScalarCost;
9875   }
9876 
9877   /// Emit a horizontal reduction of the vectorized value.
9878   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9879                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9880     assert(VectorizedValue && "Need to have a vectorized tree node");
9881     assert(isPowerOf2_32(ReduxWidth) &&
9882            "We only handle power-of-two reductions for now");
9883     assert(RdxKind != RecurKind::FMulAdd &&
9884            "A call to the llvm.fmuladd intrinsic is not handled yet");
9885 
9886     ++NumVectorInstructions;
9887     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9888   }
9889 };
9890 
9891 } // end anonymous namespace
9892 
9893 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9894   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9895     return cast<FixedVectorType>(IE->getType())->getNumElements();
9896 
9897   unsigned AggregateSize = 1;
9898   auto *IV = cast<InsertValueInst>(InsertInst);
9899   Type *CurrentType = IV->getType();
9900   do {
9901     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9902       for (auto *Elt : ST->elements())
9903         if (Elt != ST->getElementType(0)) // check homogeneity
9904           return None;
9905       AggregateSize *= ST->getNumElements();
9906       CurrentType = ST->getElementType(0);
9907     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9908       AggregateSize *= AT->getNumElements();
9909       CurrentType = AT->getElementType();
9910     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9911       AggregateSize *= VT->getNumElements();
9912       return AggregateSize;
9913     } else if (CurrentType->isSingleValueType()) {
9914       return AggregateSize;
9915     } else {
9916       return None;
9917     }
9918   } while (true);
9919 }
9920 
9921 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9922                                    TargetTransformInfo *TTI,
9923                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9924                                    SmallVectorImpl<Value *> &InsertElts,
9925                                    unsigned OperandOffset) {
9926   do {
9927     Value *InsertedOperand = LastInsertInst->getOperand(1);
9928     Optional<unsigned> OperandIndex =
9929         getInsertIndex(LastInsertInst, OperandOffset);
9930     if (!OperandIndex)
9931       return;
9932     if (isa<InsertElementInst>(InsertedOperand) ||
9933         isa<InsertValueInst>(InsertedOperand)) {
9934       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9935                              BuildVectorOpds, InsertElts, *OperandIndex);
9936 
9937     } else {
9938       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9939       InsertElts[*OperandIndex] = LastInsertInst;
9940     }
9941     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9942   } while (LastInsertInst != nullptr &&
9943            (isa<InsertValueInst>(LastInsertInst) ||
9944             isa<InsertElementInst>(LastInsertInst)) &&
9945            LastInsertInst->hasOneUse());
9946 }
9947 
9948 /// Recognize construction of vectors like
9949 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9950 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9951 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9952 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9953 ///  starting from the last insertelement or insertvalue instruction.
9954 ///
9955 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9956 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9957 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9958 ///
9959 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9960 ///
9961 /// \return true if it matches.
9962 static bool findBuildAggregate(Instruction *LastInsertInst,
9963                                TargetTransformInfo *TTI,
9964                                SmallVectorImpl<Value *> &BuildVectorOpds,
9965                                SmallVectorImpl<Value *> &InsertElts) {
9966 
9967   assert((isa<InsertElementInst>(LastInsertInst) ||
9968           isa<InsertValueInst>(LastInsertInst)) &&
9969          "Expected insertelement or insertvalue instruction!");
9970 
9971   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9972          "Expected empty result vectors!");
9973 
9974   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9975   if (!AggregateSize)
9976     return false;
9977   BuildVectorOpds.resize(*AggregateSize);
9978   InsertElts.resize(*AggregateSize);
9979 
9980   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9981   llvm::erase_value(BuildVectorOpds, nullptr);
9982   llvm::erase_value(InsertElts, nullptr);
9983   if (BuildVectorOpds.size() >= 2)
9984     return true;
9985 
9986   return false;
9987 }
9988 
9989 /// Try and get a reduction value from a phi node.
9990 ///
9991 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9992 /// if they come from either \p ParentBB or a containing loop latch.
9993 ///
9994 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9995 /// if not possible.
9996 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9997                                 BasicBlock *ParentBB, LoopInfo *LI) {
9998   // There are situations where the reduction value is not dominated by the
9999   // reduction phi. Vectorizing such cases has been reported to cause
10000   // miscompiles. See PR25787.
10001   auto DominatedReduxValue = [&](Value *R) {
10002     return isa<Instruction>(R) &&
10003            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10004   };
10005 
10006   Value *Rdx = nullptr;
10007 
10008   // Return the incoming value if it comes from the same BB as the phi node.
10009   if (P->getIncomingBlock(0) == ParentBB) {
10010     Rdx = P->getIncomingValue(0);
10011   } else if (P->getIncomingBlock(1) == ParentBB) {
10012     Rdx = P->getIncomingValue(1);
10013   }
10014 
10015   if (Rdx && DominatedReduxValue(Rdx))
10016     return Rdx;
10017 
10018   // Otherwise, check whether we have a loop latch to look at.
10019   Loop *BBL = LI->getLoopFor(ParentBB);
10020   if (!BBL)
10021     return nullptr;
10022   BasicBlock *BBLatch = BBL->getLoopLatch();
10023   if (!BBLatch)
10024     return nullptr;
10025 
10026   // There is a loop latch, return the incoming value if it comes from
10027   // that. This reduction pattern occasionally turns up.
10028   if (P->getIncomingBlock(0) == BBLatch) {
10029     Rdx = P->getIncomingValue(0);
10030   } else if (P->getIncomingBlock(1) == BBLatch) {
10031     Rdx = P->getIncomingValue(1);
10032   }
10033 
10034   if (Rdx && DominatedReduxValue(Rdx))
10035     return Rdx;
10036 
10037   return nullptr;
10038 }
10039 
10040 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10041   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10042     return true;
10043   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10044     return true;
10045   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10046     return true;
10047   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10048     return true;
10049   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10050     return true;
10051   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10052     return true;
10053   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10054     return true;
10055   return false;
10056 }
10057 
10058 /// Attempt to reduce a horizontal reduction.
10059 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10060 /// with reduction operators \a Root (or one of its operands) in a basic block
10061 /// \a BB, then check if it can be done. If horizontal reduction is not found
10062 /// and root instruction is a binary operation, vectorization of the operands is
10063 /// attempted.
10064 /// \returns true if a horizontal reduction was matched and reduced or operands
10065 /// of one of the binary instruction were vectorized.
10066 /// \returns false if a horizontal reduction was not matched (or not possible)
10067 /// or no vectorization of any binary operation feeding \a Root instruction was
10068 /// performed.
10069 static bool tryToVectorizeHorReductionOrInstOperands(
10070     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10071     TargetTransformInfo *TTI,
10072     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10073   if (!ShouldVectorizeHor)
10074     return false;
10075 
10076   if (!Root)
10077     return false;
10078 
10079   if (Root->getParent() != BB || isa<PHINode>(Root))
10080     return false;
10081   // Start analysis starting from Root instruction. If horizontal reduction is
10082   // found, try to vectorize it. If it is not a horizontal reduction or
10083   // vectorization is not possible or not effective, and currently analyzed
10084   // instruction is a binary operation, try to vectorize the operands, using
10085   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10086   // the same procedure considering each operand as a possible root of the
10087   // horizontal reduction.
10088   // Interrupt the process if the Root instruction itself was vectorized or all
10089   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10090   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10091   // CmpInsts so we can skip extra attempts in
10092   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10093   std::queue<std::pair<Instruction *, unsigned>> Stack;
10094   Stack.emplace(Root, 0);
10095   SmallPtrSet<Value *, 8> VisitedInstrs;
10096   SmallVector<WeakTrackingVH> PostponedInsts;
10097   bool Res = false;
10098   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10099                                      Value *&B1) -> Value * {
10100     bool IsBinop = matchRdxBop(Inst, B0, B1);
10101     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10102     if (IsBinop || IsSelect) {
10103       HorizontalReduction HorRdx;
10104       if (HorRdx.matchAssociativeReduction(P, Inst))
10105         return HorRdx.tryToReduce(R, TTI);
10106     }
10107     return nullptr;
10108   };
10109   while (!Stack.empty()) {
10110     Instruction *Inst;
10111     unsigned Level;
10112     std::tie(Inst, Level) = Stack.front();
10113     Stack.pop();
10114     // Do not try to analyze instruction that has already been vectorized.
10115     // This may happen when we vectorize instruction operands on a previous
10116     // iteration while stack was populated before that happened.
10117     if (R.isDeleted(Inst))
10118       continue;
10119     Value *B0 = nullptr, *B1 = nullptr;
10120     if (Value *V = TryToReduce(Inst, B0, B1)) {
10121       Res = true;
10122       // Set P to nullptr to avoid re-analysis of phi node in
10123       // matchAssociativeReduction function unless this is the root node.
10124       P = nullptr;
10125       if (auto *I = dyn_cast<Instruction>(V)) {
10126         // Try to find another reduction.
10127         Stack.emplace(I, Level);
10128         continue;
10129       }
10130     } else {
10131       bool IsBinop = B0 && B1;
10132       if (P && IsBinop) {
10133         Inst = dyn_cast<Instruction>(B0);
10134         if (Inst == P)
10135           Inst = dyn_cast<Instruction>(B1);
10136         if (!Inst) {
10137           // Set P to nullptr to avoid re-analysis of phi node in
10138           // matchAssociativeReduction function unless this is the root node.
10139           P = nullptr;
10140           continue;
10141         }
10142       }
10143       // Set P to nullptr to avoid re-analysis of phi node in
10144       // matchAssociativeReduction function unless this is the root node.
10145       P = nullptr;
10146       // Do not try to vectorize CmpInst operands, this is done separately.
10147       // Final attempt for binop args vectorization should happen after the loop
10148       // to try to find reductions.
10149       if (!isa<CmpInst>(Inst))
10150         PostponedInsts.push_back(Inst);
10151     }
10152 
10153     // Try to vectorize operands.
10154     // Continue analysis for the instruction from the same basic block only to
10155     // save compile time.
10156     if (++Level < RecursionMaxDepth)
10157       for (auto *Op : Inst->operand_values())
10158         if (VisitedInstrs.insert(Op).second)
10159           if (auto *I = dyn_cast<Instruction>(Op))
10160             // Do not try to vectorize CmpInst operands,  this is done
10161             // separately.
10162             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10163                 I->getParent() == BB)
10164               Stack.emplace(I, Level);
10165   }
10166   // Try to vectorized binops where reductions were not found.
10167   for (Value *V : PostponedInsts)
10168     if (auto *Inst = dyn_cast<Instruction>(V))
10169       if (!R.isDeleted(Inst))
10170         Res |= Vectorize(Inst, R);
10171   return Res;
10172 }
10173 
10174 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10175                                                  BasicBlock *BB, BoUpSLP &R,
10176                                                  TargetTransformInfo *TTI) {
10177   auto *I = dyn_cast_or_null<Instruction>(V);
10178   if (!I)
10179     return false;
10180 
10181   if (!isa<BinaryOperator>(I))
10182     P = nullptr;
10183   // Try to match and vectorize a horizontal reduction.
10184   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10185     return tryToVectorize(I, R);
10186   };
10187   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10188                                                   ExtraVectorization);
10189 }
10190 
10191 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10192                                                  BasicBlock *BB, BoUpSLP &R) {
10193   const DataLayout &DL = BB->getModule()->getDataLayout();
10194   if (!R.canMapToVector(IVI->getType(), DL))
10195     return false;
10196 
10197   SmallVector<Value *, 16> BuildVectorOpds;
10198   SmallVector<Value *, 16> BuildVectorInsts;
10199   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10200     return false;
10201 
10202   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10203   // Aggregate value is unlikely to be processed in vector register.
10204   return tryToVectorizeList(BuildVectorOpds, R);
10205 }
10206 
10207 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10208                                                    BasicBlock *BB, BoUpSLP &R) {
10209   SmallVector<Value *, 16> BuildVectorInsts;
10210   SmallVector<Value *, 16> BuildVectorOpds;
10211   SmallVector<int> Mask;
10212   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10213       (llvm::all_of(
10214            BuildVectorOpds,
10215            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10216        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10217     return false;
10218 
10219   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10220   return tryToVectorizeList(BuildVectorInsts, R);
10221 }
10222 
10223 template <typename T>
10224 static bool
10225 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10226                        function_ref<unsigned(T *)> Limit,
10227                        function_ref<bool(T *, T *)> Comparator,
10228                        function_ref<bool(T *, T *)> AreCompatible,
10229                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10230                        bool LimitForRegisterSize) {
10231   bool Changed = false;
10232   // Sort by type, parent, operands.
10233   stable_sort(Incoming, Comparator);
10234 
10235   // Try to vectorize elements base on their type.
10236   SmallVector<T *> Candidates;
10237   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10238     // Look for the next elements with the same type, parent and operand
10239     // kinds.
10240     auto *SameTypeIt = IncIt;
10241     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10242       ++SameTypeIt;
10243 
10244     // Try to vectorize them.
10245     unsigned NumElts = (SameTypeIt - IncIt);
10246     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10247                       << NumElts << ")\n");
10248     // The vectorization is a 3-state attempt:
10249     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10250     // size of maximal register at first.
10251     // 2. Try to vectorize remaining instructions with the same type, if
10252     // possible. This may result in the better vectorization results rather than
10253     // if we try just to vectorize instructions with the same/alternate opcodes.
10254     // 3. Final attempt to try to vectorize all instructions with the
10255     // same/alternate ops only, this may result in some extra final
10256     // vectorization.
10257     if (NumElts > 1 &&
10258         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10259       // Success start over because instructions might have been changed.
10260       Changed = true;
10261     } else if (NumElts < Limit(*IncIt) &&
10262                (Candidates.empty() ||
10263                 Candidates.front()->getType() == (*IncIt)->getType())) {
10264       Candidates.append(IncIt, std::next(IncIt, NumElts));
10265     }
10266     // Final attempt to vectorize instructions with the same types.
10267     if (Candidates.size() > 1 &&
10268         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10269       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10270         // Success start over because instructions might have been changed.
10271         Changed = true;
10272       } else if (LimitForRegisterSize) {
10273         // Try to vectorize using small vectors.
10274         for (auto *It = Candidates.begin(), *End = Candidates.end();
10275              It != End;) {
10276           auto *SameTypeIt = It;
10277           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10278             ++SameTypeIt;
10279           unsigned NumElts = (SameTypeIt - It);
10280           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10281                                             /*LimitForRegisterSize=*/false))
10282             Changed = true;
10283           It = SameTypeIt;
10284         }
10285       }
10286       Candidates.clear();
10287     }
10288 
10289     // Start over at the next instruction of a different type (or the end).
10290     IncIt = SameTypeIt;
10291   }
10292   return Changed;
10293 }
10294 
10295 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10296 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10297 /// operands. If IsCompatibility is false, function implements strict weak
10298 /// ordering relation between two cmp instructions, returning true if the first
10299 /// instruction is "less" than the second, i.e. its predicate is less than the
10300 /// predicate of the second or the operands IDs are less than the operands IDs
10301 /// of the second cmp instruction.
10302 template <bool IsCompatibility>
10303 static bool compareCmp(Value *V, Value *V2,
10304                        function_ref<bool(Instruction *)> IsDeleted) {
10305   auto *CI1 = cast<CmpInst>(V);
10306   auto *CI2 = cast<CmpInst>(V2);
10307   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10308     return false;
10309   if (CI1->getOperand(0)->getType()->getTypeID() <
10310       CI2->getOperand(0)->getType()->getTypeID())
10311     return !IsCompatibility;
10312   if (CI1->getOperand(0)->getType()->getTypeID() >
10313       CI2->getOperand(0)->getType()->getTypeID())
10314     return false;
10315   CmpInst::Predicate Pred1 = CI1->getPredicate();
10316   CmpInst::Predicate Pred2 = CI2->getPredicate();
10317   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10318   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10319   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10320   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10321   if (BasePred1 < BasePred2)
10322     return !IsCompatibility;
10323   if (BasePred1 > BasePred2)
10324     return false;
10325   // Compare operands.
10326   bool LEPreds = Pred1 <= Pred2;
10327   bool GEPreds = Pred1 >= Pred2;
10328   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10329     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10330     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10331     if (Op1->getValueID() < Op2->getValueID())
10332       return !IsCompatibility;
10333     if (Op1->getValueID() > Op2->getValueID())
10334       return false;
10335     if (auto *I1 = dyn_cast<Instruction>(Op1))
10336       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10337         if (I1->getParent() != I2->getParent())
10338           return false;
10339         InstructionsState S = getSameOpcode({I1, I2});
10340         if (S.getOpcode())
10341           continue;
10342         return false;
10343       }
10344   }
10345   return IsCompatibility;
10346 }
10347 
10348 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10349     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10350     bool AtTerminator) {
10351   bool OpsChanged = false;
10352   SmallVector<Instruction *, 4> PostponedCmps;
10353   for (auto *I : reverse(Instructions)) {
10354     if (R.isDeleted(I))
10355       continue;
10356     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10357       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10358     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10359       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10360     else if (isa<CmpInst>(I))
10361       PostponedCmps.push_back(I);
10362   }
10363   if (AtTerminator) {
10364     // Try to find reductions first.
10365     for (Instruction *I : PostponedCmps) {
10366       if (R.isDeleted(I))
10367         continue;
10368       for (Value *Op : I->operands())
10369         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10370     }
10371     // Try to vectorize operands as vector bundles.
10372     for (Instruction *I : PostponedCmps) {
10373       if (R.isDeleted(I))
10374         continue;
10375       OpsChanged |= tryToVectorize(I, R);
10376     }
10377     // Try to vectorize list of compares.
10378     // Sort by type, compare predicate, etc.
10379     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10380       return compareCmp<false>(V, V2,
10381                                [&R](Instruction *I) { return R.isDeleted(I); });
10382     };
10383 
10384     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10385       if (V1 == V2)
10386         return true;
10387       return compareCmp<true>(V1, V2,
10388                               [&R](Instruction *I) { return R.isDeleted(I); });
10389     };
10390     auto Limit = [&R](Value *V) {
10391       unsigned EltSize = R.getVectorElementSize(V);
10392       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10393     };
10394 
10395     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10396     OpsChanged |= tryToVectorizeSequence<Value>(
10397         Vals, Limit, CompareSorter, AreCompatibleCompares,
10398         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10399           // Exclude possible reductions from other blocks.
10400           bool ArePossiblyReducedInOtherBlock =
10401               any_of(Candidates, [](Value *V) {
10402                 return any_of(V->users(), [V](User *U) {
10403                   return isa<SelectInst>(U) &&
10404                          cast<SelectInst>(U)->getParent() !=
10405                              cast<Instruction>(V)->getParent();
10406                 });
10407               });
10408           if (ArePossiblyReducedInOtherBlock)
10409             return false;
10410           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10411         },
10412         /*LimitForRegisterSize=*/true);
10413     Instructions.clear();
10414   } else {
10415     // Insert in reverse order since the PostponedCmps vector was filled in
10416     // reverse order.
10417     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10418   }
10419   return OpsChanged;
10420 }
10421 
10422 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10423   bool Changed = false;
10424   SmallVector<Value *, 4> Incoming;
10425   SmallPtrSet<Value *, 16> VisitedInstrs;
10426   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10427   // node. Allows better to identify the chains that can be vectorized in the
10428   // better way.
10429   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10430   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10431     assert(isValidElementType(V1->getType()) &&
10432            isValidElementType(V2->getType()) &&
10433            "Expected vectorizable types only.");
10434     // It is fine to compare type IDs here, since we expect only vectorizable
10435     // types, like ints, floats and pointers, we don't care about other type.
10436     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10437       return true;
10438     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10439       return false;
10440     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10441     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10442     if (Opcodes1.size() < Opcodes2.size())
10443       return true;
10444     if (Opcodes1.size() > Opcodes2.size())
10445       return false;
10446     Optional<bool> ConstOrder;
10447     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10448       // Undefs are compatible with any other value.
10449       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10450         if (!ConstOrder)
10451           ConstOrder =
10452               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10453         continue;
10454       }
10455       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10456         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10457           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10458           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10459           if (!NodeI1)
10460             return NodeI2 != nullptr;
10461           if (!NodeI2)
10462             return false;
10463           assert((NodeI1 == NodeI2) ==
10464                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10465                  "Different nodes should have different DFS numbers");
10466           if (NodeI1 != NodeI2)
10467             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10468           InstructionsState S = getSameOpcode({I1, I2});
10469           if (S.getOpcode())
10470             continue;
10471           return I1->getOpcode() < I2->getOpcode();
10472         }
10473       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10474         if (!ConstOrder)
10475           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10476         continue;
10477       }
10478       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10479         return true;
10480       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10481         return false;
10482     }
10483     return ConstOrder && *ConstOrder;
10484   };
10485   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10486     if (V1 == V2)
10487       return true;
10488     if (V1->getType() != V2->getType())
10489       return false;
10490     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10491     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10492     if (Opcodes1.size() != Opcodes2.size())
10493       return false;
10494     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10495       // Undefs are compatible with any other value.
10496       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10497         continue;
10498       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10499         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10500           if (I1->getParent() != I2->getParent())
10501             return false;
10502           InstructionsState S = getSameOpcode({I1, I2});
10503           if (S.getOpcode())
10504             continue;
10505           return false;
10506         }
10507       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10508         continue;
10509       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10510         return false;
10511     }
10512     return true;
10513   };
10514   auto Limit = [&R](Value *V) {
10515     unsigned EltSize = R.getVectorElementSize(V);
10516     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10517   };
10518 
10519   bool HaveVectorizedPhiNodes = false;
10520   do {
10521     // Collect the incoming values from the PHIs.
10522     Incoming.clear();
10523     for (Instruction &I : *BB) {
10524       PHINode *P = dyn_cast<PHINode>(&I);
10525       if (!P)
10526         break;
10527 
10528       // No need to analyze deleted, vectorized and non-vectorizable
10529       // instructions.
10530       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10531           isValidElementType(P->getType()))
10532         Incoming.push_back(P);
10533     }
10534 
10535     // Find the corresponding non-phi nodes for better matching when trying to
10536     // build the tree.
10537     for (Value *V : Incoming) {
10538       SmallVectorImpl<Value *> &Opcodes =
10539           PHIToOpcodes.try_emplace(V).first->getSecond();
10540       if (!Opcodes.empty())
10541         continue;
10542       SmallVector<Value *, 4> Nodes(1, V);
10543       SmallPtrSet<Value *, 4> Visited;
10544       while (!Nodes.empty()) {
10545         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10546         if (!Visited.insert(PHI).second)
10547           continue;
10548         for (Value *V : PHI->incoming_values()) {
10549           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10550             Nodes.push_back(PHI1);
10551             continue;
10552           }
10553           Opcodes.emplace_back(V);
10554         }
10555       }
10556     }
10557 
10558     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10559         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10560         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10561           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10562         },
10563         /*LimitForRegisterSize=*/true);
10564     Changed |= HaveVectorizedPhiNodes;
10565     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10566   } while (HaveVectorizedPhiNodes);
10567 
10568   VisitedInstrs.clear();
10569 
10570   SmallVector<Instruction *, 8> PostProcessInstructions;
10571   SmallDenseSet<Instruction *, 4> KeyNodes;
10572   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10573     // Skip instructions with scalable type. The num of elements is unknown at
10574     // compile-time for scalable type.
10575     if (isa<ScalableVectorType>(it->getType()))
10576       continue;
10577 
10578     // Skip instructions marked for the deletion.
10579     if (R.isDeleted(&*it))
10580       continue;
10581     // We may go through BB multiple times so skip the one we have checked.
10582     if (!VisitedInstrs.insert(&*it).second) {
10583       if (it->use_empty() && KeyNodes.contains(&*it) &&
10584           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10585                                       it->isTerminator())) {
10586         // We would like to start over since some instructions are deleted
10587         // and the iterator may become invalid value.
10588         Changed = true;
10589         it = BB->begin();
10590         e = BB->end();
10591       }
10592       continue;
10593     }
10594 
10595     if (isa<DbgInfoIntrinsic>(it))
10596       continue;
10597 
10598     // Try to vectorize reductions that use PHINodes.
10599     if (PHINode *P = dyn_cast<PHINode>(it)) {
10600       // Check that the PHI is a reduction PHI.
10601       if (P->getNumIncomingValues() == 2) {
10602         // Try to match and vectorize a horizontal reduction.
10603         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10604                                      TTI)) {
10605           Changed = true;
10606           it = BB->begin();
10607           e = BB->end();
10608           continue;
10609         }
10610       }
10611       // Try to vectorize the incoming values of the PHI, to catch reductions
10612       // that feed into PHIs.
10613       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10614         // Skip if the incoming block is the current BB for now. Also, bypass
10615         // unreachable IR for efficiency and to avoid crashing.
10616         // TODO: Collect the skipped incoming values and try to vectorize them
10617         // after processing BB.
10618         if (BB == P->getIncomingBlock(I) ||
10619             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10620           continue;
10621 
10622         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10623                                             P->getIncomingBlock(I), R, TTI);
10624       }
10625       continue;
10626     }
10627 
10628     // Ran into an instruction without users, like terminator, or function call
10629     // with ignored return value, store. Ignore unused instructions (basing on
10630     // instruction type, except for CallInst and InvokeInst).
10631     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10632                             isa<InvokeInst>(it))) {
10633       KeyNodes.insert(&*it);
10634       bool OpsChanged = false;
10635       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10636         for (auto *V : it->operand_values()) {
10637           // Try to match and vectorize a horizontal reduction.
10638           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10639         }
10640       }
10641       // Start vectorization of post-process list of instructions from the
10642       // top-tree instructions to try to vectorize as many instructions as
10643       // possible.
10644       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10645                                                 it->isTerminator());
10646       if (OpsChanged) {
10647         // We would like to start over since some instructions are deleted
10648         // and the iterator may become invalid value.
10649         Changed = true;
10650         it = BB->begin();
10651         e = BB->end();
10652         continue;
10653       }
10654     }
10655 
10656     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10657         isa<InsertValueInst>(it))
10658       PostProcessInstructions.push_back(&*it);
10659   }
10660 
10661   return Changed;
10662 }
10663 
10664 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10665   auto Changed = false;
10666   for (auto &Entry : GEPs) {
10667     // If the getelementptr list has fewer than two elements, there's nothing
10668     // to do.
10669     if (Entry.second.size() < 2)
10670       continue;
10671 
10672     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10673                       << Entry.second.size() << ".\n");
10674 
10675     // Process the GEP list in chunks suitable for the target's supported
10676     // vector size. If a vector register can't hold 1 element, we are done. We
10677     // are trying to vectorize the index computations, so the maximum number of
10678     // elements is based on the size of the index expression, rather than the
10679     // size of the GEP itself (the target's pointer size).
10680     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10681     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10682     if (MaxVecRegSize < EltSize)
10683       continue;
10684 
10685     unsigned MaxElts = MaxVecRegSize / EltSize;
10686     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10687       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10688       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10689 
10690       // Initialize a set a candidate getelementptrs. Note that we use a
10691       // SetVector here to preserve program order. If the index computations
10692       // are vectorizable and begin with loads, we want to minimize the chance
10693       // of having to reorder them later.
10694       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10695 
10696       // Some of the candidates may have already been vectorized after we
10697       // initially collected them. If so, they are marked as deleted, so remove
10698       // them from the set of candidates.
10699       Candidates.remove_if(
10700           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10701 
10702       // Remove from the set of candidates all pairs of getelementptrs with
10703       // constant differences. Such getelementptrs are likely not good
10704       // candidates for vectorization in a bottom-up phase since one can be
10705       // computed from the other. We also ensure all candidate getelementptr
10706       // indices are unique.
10707       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10708         auto *GEPI = GEPList[I];
10709         if (!Candidates.count(GEPI))
10710           continue;
10711         auto *SCEVI = SE->getSCEV(GEPList[I]);
10712         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10713           auto *GEPJ = GEPList[J];
10714           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10715           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10716             Candidates.remove(GEPI);
10717             Candidates.remove(GEPJ);
10718           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10719             Candidates.remove(GEPJ);
10720           }
10721         }
10722       }
10723 
10724       // We break out of the above computation as soon as we know there are
10725       // fewer than two candidates remaining.
10726       if (Candidates.size() < 2)
10727         continue;
10728 
10729       // Add the single, non-constant index of each candidate to the bundle. We
10730       // ensured the indices met these constraints when we originally collected
10731       // the getelementptrs.
10732       SmallVector<Value *, 16> Bundle(Candidates.size());
10733       auto BundleIndex = 0u;
10734       for (auto *V : Candidates) {
10735         auto *GEP = cast<GetElementPtrInst>(V);
10736         auto *GEPIdx = GEP->idx_begin()->get();
10737         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10738         Bundle[BundleIndex++] = GEPIdx;
10739       }
10740 
10741       // Try and vectorize the indices. We are currently only interested in
10742       // gather-like cases of the form:
10743       //
10744       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10745       //
10746       // where the loads of "a", the loads of "b", and the subtractions can be
10747       // performed in parallel. It's likely that detecting this pattern in a
10748       // bottom-up phase will be simpler and less costly than building a
10749       // full-blown top-down phase beginning at the consecutive loads.
10750       Changed |= tryToVectorizeList(Bundle, R);
10751     }
10752   }
10753   return Changed;
10754 }
10755 
10756 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10757   bool Changed = false;
10758   // Sort by type, base pointers and values operand. Value operands must be
10759   // compatible (have the same opcode, same parent), otherwise it is
10760   // definitely not profitable to try to vectorize them.
10761   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10762     if (V->getPointerOperandType()->getTypeID() <
10763         V2->getPointerOperandType()->getTypeID())
10764       return true;
10765     if (V->getPointerOperandType()->getTypeID() >
10766         V2->getPointerOperandType()->getTypeID())
10767       return false;
10768     // UndefValues are compatible with all other values.
10769     if (isa<UndefValue>(V->getValueOperand()) ||
10770         isa<UndefValue>(V2->getValueOperand()))
10771       return false;
10772     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10773       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10774         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10775             DT->getNode(I1->getParent());
10776         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10777             DT->getNode(I2->getParent());
10778         assert(NodeI1 && "Should only process reachable instructions");
10779         assert(NodeI1 && "Should only process reachable instructions");
10780         assert((NodeI1 == NodeI2) ==
10781                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10782                "Different nodes should have different DFS numbers");
10783         if (NodeI1 != NodeI2)
10784           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10785         InstructionsState S = getSameOpcode({I1, I2});
10786         if (S.getOpcode())
10787           return false;
10788         return I1->getOpcode() < I2->getOpcode();
10789       }
10790     if (isa<Constant>(V->getValueOperand()) &&
10791         isa<Constant>(V2->getValueOperand()))
10792       return false;
10793     return V->getValueOperand()->getValueID() <
10794            V2->getValueOperand()->getValueID();
10795   };
10796 
10797   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10798     if (V1 == V2)
10799       return true;
10800     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10801       return false;
10802     // Undefs are compatible with any other value.
10803     if (isa<UndefValue>(V1->getValueOperand()) ||
10804         isa<UndefValue>(V2->getValueOperand()))
10805       return true;
10806     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10807       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10808         if (I1->getParent() != I2->getParent())
10809           return false;
10810         InstructionsState S = getSameOpcode({I1, I2});
10811         return S.getOpcode() > 0;
10812       }
10813     if (isa<Constant>(V1->getValueOperand()) &&
10814         isa<Constant>(V2->getValueOperand()))
10815       return true;
10816     return V1->getValueOperand()->getValueID() ==
10817            V2->getValueOperand()->getValueID();
10818   };
10819   auto Limit = [&R, this](StoreInst *SI) {
10820     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10821     return R.getMinVF(EltSize);
10822   };
10823 
10824   // Attempt to sort and vectorize each of the store-groups.
10825   for (auto &Pair : Stores) {
10826     if (Pair.second.size() < 2)
10827       continue;
10828 
10829     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10830                       << Pair.second.size() << ".\n");
10831 
10832     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10833       continue;
10834 
10835     Changed |= tryToVectorizeSequence<StoreInst>(
10836         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10837         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10838           return vectorizeStores(Candidates, R);
10839         },
10840         /*LimitForRegisterSize=*/false);
10841   }
10842   return Changed;
10843 }
10844 
10845 char SLPVectorizer::ID = 0;
10846 
10847 static const char lv_name[] = "SLP Vectorizer";
10848 
10849 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10850 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10851 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10852 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10853 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10854 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10855 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10856 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10857 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10858 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10859 
10860 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10861