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 !I->mayReadOrWriteMemory() && all_of(I->operands(), [I](Value *V) {
782     auto *IO = dyn_cast<Instruction>(V);
783     if (!IO)
784       return true;
785     return isa<PHINode>(IO) || IO->getParent() != I->getParent();
786   });
787 }
788 
789 /// Checks if the provided value does not require scheduling. It does not
790 /// require scheduling if this is not an instruction or it is an instruction
791 /// that does not read/write memory and all users are phi nodes or instructions
792 /// from the different blocks.
793 static bool isUsedOutsideBlock(Value *V) {
794   auto *I = dyn_cast<Instruction>(V);
795   if (!I)
796     return true;
797   // Limits the number of uses to save compile time.
798   constexpr int UsesLimit = 8;
799   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
800          all_of(I->users(), [I](User *U) {
801            auto *IU = dyn_cast<Instruction>(U);
802            if (!IU)
803              return true;
804            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
805          });
806 }
807 
808 /// Checks if the specified value does not require scheduling. It does not
809 /// require scheduling if all operands and all users do not need to be scheduled
810 /// in the current basic block.
811 static bool doesNotNeedToBeScheduled(Value *V) {
812   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
813 }
814 
815 /// Checks if the specified array of instructions does not require scheduling.
816 /// It is so if all either instructions have operands that do not require
817 /// scheduling or their users do not require scheduling since they are phis or
818 /// in other basic blocks.
819 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
820   return !VL.empty() &&
821          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
822 }
823 
824 namespace slpvectorizer {
825 
826 /// Bottom Up SLP Vectorizer.
827 class BoUpSLP {
828   struct TreeEntry;
829   struct ScheduleData;
830 
831 public:
832   using ValueList = SmallVector<Value *, 8>;
833   using InstrList = SmallVector<Instruction *, 16>;
834   using ValueSet = SmallPtrSet<Value *, 16>;
835   using StoreList = SmallVector<StoreInst *, 8>;
836   using ExtraValueToDebugLocsMap =
837       MapVector<Value *, SmallVector<Instruction *, 2>>;
838   using OrdersType = SmallVector<unsigned, 4>;
839 
840   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
841           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
842           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
843           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
844       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
845         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
846     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
847     // Use the vector register size specified by the target unless overridden
848     // by a command-line option.
849     // TODO: It would be better to limit the vectorization factor based on
850     //       data type rather than just register size. For example, x86 AVX has
851     //       256-bit registers, but it does not support integer operations
852     //       at that width (that requires AVX2).
853     if (MaxVectorRegSizeOption.getNumOccurrences())
854       MaxVecRegSize = MaxVectorRegSizeOption;
855     else
856       MaxVecRegSize =
857           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
858               .getFixedSize();
859 
860     if (MinVectorRegSizeOption.getNumOccurrences())
861       MinVecRegSize = MinVectorRegSizeOption;
862     else
863       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
864   }
865 
866   /// Vectorize the tree that starts with the elements in \p VL.
867   /// Returns the vectorized root.
868   Value *vectorizeTree();
869 
870   /// Vectorize the tree but with the list of externally used values \p
871   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
872   /// generated extractvalue instructions.
873   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
874 
875   /// \returns the cost incurred by unwanted spills and fills, caused by
876   /// holding live values over call sites.
877   InstructionCost getSpillCost() const;
878 
879   /// \returns the vectorization cost of the subtree that starts at \p VL.
880   /// A negative number means that this is profitable.
881   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
882 
883   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
884   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
885   void buildTree(ArrayRef<Value *> Roots,
886                  ArrayRef<Value *> UserIgnoreLst = None);
887 
888   /// Builds external uses of the vectorized scalars, i.e. the list of
889   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
890   /// ExternallyUsedValues contains additional list of external uses to handle
891   /// vectorization of reductions.
892   void
893   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
894 
895   /// Clear the internal data structures that are created by 'buildTree'.
896   void deleteTree() {
897     VectorizableTree.clear();
898     ScalarToTreeEntry.clear();
899     MustGather.clear();
900     ExternalUses.clear();
901     for (auto &Iter : BlocksSchedules) {
902       BlockScheduling *BS = Iter.second.get();
903       BS->clear();
904     }
905     MinBWs.clear();
906     InstrElementSize.clear();
907   }
908 
909   unsigned getTreeSize() const { return VectorizableTree.size(); }
910 
911   /// Perform LICM and CSE on the newly generated gather sequences.
912   void optimizeGatherSequence();
913 
914   /// Checks if the specified gather tree entry \p TE can be represented as a
915   /// shuffled vector entry + (possibly) permutation with other gathers. It
916   /// implements the checks only for possibly ordered scalars (Loads,
917   /// ExtractElement, ExtractValue), which can be part of the graph.
918   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
919 
920   /// Gets reordering data for the given tree entry. If the entry is vectorized
921   /// - just return ReorderIndices, otherwise check if the scalars can be
922   /// reordered and return the most optimal order.
923   /// \param TopToBottom If true, include the order of vectorized stores and
924   /// insertelement nodes, otherwise skip them.
925   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
926 
927   /// Reorders the current graph to the most profitable order starting from the
928   /// root node to the leaf nodes. The best order is chosen only from the nodes
929   /// of the same size (vectorization factor). Smaller nodes are considered
930   /// parts of subgraph with smaller VF and they are reordered independently. We
931   /// can make it because we still need to extend smaller nodes to the wider VF
932   /// and we can merge reordering shuffles with the widening shuffles.
933   void reorderTopToBottom();
934 
935   /// Reorders the current graph to the most profitable order starting from
936   /// leaves to the root. It allows to rotate small subgraphs and reduce the
937   /// number of reshuffles if the leaf nodes use the same order. In this case we
938   /// can merge the orders and just shuffle user node instead of shuffling its
939   /// operands. Plus, even the leaf nodes have different orders, it allows to
940   /// sink reordering in the graph closer to the root node and merge it later
941   /// during analysis.
942   void reorderBottomToTop(bool IgnoreReorder = false);
943 
944   /// \return The vector element size in bits to use when vectorizing the
945   /// expression tree ending at \p V. If V is a store, the size is the width of
946   /// the stored value. Otherwise, the size is the width of the largest loaded
947   /// value reaching V. This method is used by the vectorizer to calculate
948   /// vectorization factors.
949   unsigned getVectorElementSize(Value *V);
950 
951   /// Compute the minimum type sizes required to represent the entries in a
952   /// vectorizable tree.
953   void computeMinimumValueSizes();
954 
955   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
956   unsigned getMaxVecRegSize() const {
957     return MaxVecRegSize;
958   }
959 
960   // \returns minimum vector register size as set by cl::opt.
961   unsigned getMinVecRegSize() const {
962     return MinVecRegSize;
963   }
964 
965   unsigned getMinVF(unsigned Sz) const {
966     return std::max(2U, getMinVecRegSize() / Sz);
967   }
968 
969   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
970     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
971       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
972     return MaxVF ? MaxVF : UINT_MAX;
973   }
974 
975   /// Check if homogeneous aggregate is isomorphic to some VectorType.
976   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
977   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
978   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
979   ///
980   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
981   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
982 
983   /// \returns True if the VectorizableTree is both tiny and not fully
984   /// vectorizable. We do not vectorize such trees.
985   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
986 
987   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
988   /// can be load combined in the backend. Load combining may not be allowed in
989   /// the IR optimizer, so we do not want to alter the pattern. For example,
990   /// partially transforming a scalar bswap() pattern into vector code is
991   /// effectively impossible for the backend to undo.
992   /// TODO: If load combining is allowed in the IR optimizer, this analysis
993   ///       may not be necessary.
994   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
995 
996   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
997   /// can be load combined in the backend. Load combining may not be allowed in
998   /// the IR optimizer, so we do not want to alter the pattern. For example,
999   /// partially transforming a scalar bswap() pattern into vector code is
1000   /// effectively impossible for the backend to undo.
1001   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1002   ///       may not be necessary.
1003   bool isLoadCombineCandidate() const;
1004 
1005   OptimizationRemarkEmitter *getORE() { return ORE; }
1006 
1007   /// This structure holds any data we need about the edges being traversed
1008   /// during buildTree_rec(). We keep track of:
1009   /// (i) the user TreeEntry index, and
1010   /// (ii) the index of the edge.
1011   struct EdgeInfo {
1012     EdgeInfo() = default;
1013     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1014         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1015     /// The user TreeEntry.
1016     TreeEntry *UserTE = nullptr;
1017     /// The operand index of the use.
1018     unsigned EdgeIdx = UINT_MAX;
1019 #ifndef NDEBUG
1020     friend inline raw_ostream &operator<<(raw_ostream &OS,
1021                                           const BoUpSLP::EdgeInfo &EI) {
1022       EI.dump(OS);
1023       return OS;
1024     }
1025     /// Debug print.
1026     void dump(raw_ostream &OS) const {
1027       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1028          << " EdgeIdx:" << EdgeIdx << "}";
1029     }
1030     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1031 #endif
1032   };
1033 
1034   /// A helper data structure to hold the operands of a vector of instructions.
1035   /// This supports a fixed vector length for all operand vectors.
1036   class VLOperands {
1037     /// For each operand we need (i) the value, and (ii) the opcode that it
1038     /// would be attached to if the expression was in a left-linearized form.
1039     /// This is required to avoid illegal operand reordering.
1040     /// For example:
1041     /// \verbatim
1042     ///                         0 Op1
1043     ///                         |/
1044     /// Op1 Op2   Linearized    + Op2
1045     ///   \ /     ---------->   |/
1046     ///    -                    -
1047     ///
1048     /// Op1 - Op2            (0 + Op1) - Op2
1049     /// \endverbatim
1050     ///
1051     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1052     ///
1053     /// Another way to think of this is to track all the operations across the
1054     /// path from the operand all the way to the root of the tree and to
1055     /// calculate the operation that corresponds to this path. For example, the
1056     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1057     /// corresponding operation is a '-' (which matches the one in the
1058     /// linearized tree, as shown above).
1059     ///
1060     /// For lack of a better term, we refer to this operation as Accumulated
1061     /// Path Operation (APO).
1062     struct OperandData {
1063       OperandData() = default;
1064       OperandData(Value *V, bool APO, bool IsUsed)
1065           : V(V), APO(APO), IsUsed(IsUsed) {}
1066       /// The operand value.
1067       Value *V = nullptr;
1068       /// TreeEntries only allow a single opcode, or an alternate sequence of
1069       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1070       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1071       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1072       /// (e.g., Add/Mul)
1073       bool APO = false;
1074       /// Helper data for the reordering function.
1075       bool IsUsed = false;
1076     };
1077 
1078     /// During operand reordering, we are trying to select the operand at lane
1079     /// that matches best with the operand at the neighboring lane. Our
1080     /// selection is based on the type of value we are looking for. For example,
1081     /// if the neighboring lane has a load, we need to look for a load that is
1082     /// accessing a consecutive address. These strategies are summarized in the
1083     /// 'ReorderingMode' enumerator.
1084     enum class ReorderingMode {
1085       Load,     ///< Matching loads to consecutive memory addresses
1086       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1087       Constant, ///< Matching constants
1088       Splat,    ///< Matching the same instruction multiple times (broadcast)
1089       Failed,   ///< We failed to create a vectorizable group
1090     };
1091 
1092     using OperandDataVec = SmallVector<OperandData, 2>;
1093 
1094     /// A vector of operand vectors.
1095     SmallVector<OperandDataVec, 4> OpsVec;
1096 
1097     const DataLayout &DL;
1098     ScalarEvolution &SE;
1099     const BoUpSLP &R;
1100 
1101     /// \returns the operand data at \p OpIdx and \p Lane.
1102     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1103       return OpsVec[OpIdx][Lane];
1104     }
1105 
1106     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1107     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1108       return OpsVec[OpIdx][Lane];
1109     }
1110 
1111     /// Clears the used flag for all entries.
1112     void clearUsed() {
1113       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1114            OpIdx != NumOperands; ++OpIdx)
1115         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1116              ++Lane)
1117           OpsVec[OpIdx][Lane].IsUsed = false;
1118     }
1119 
1120     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1121     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1122       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1123     }
1124 
1125     // The hard-coded scores listed here are not very important, though it shall
1126     // be higher for better matches to improve the resulting cost. When
1127     // computing the scores of matching one sub-tree with another, we are
1128     // basically counting the number of values that are matching. So even if all
1129     // scores are set to 1, we would still get a decent matching result.
1130     // However, sometimes we have to break ties. For example we may have to
1131     // choose between matching loads vs matching opcodes. This is what these
1132     // scores are helping us with: they provide the order of preference. Also,
1133     // this is important if the scalar is externally used or used in another
1134     // tree entry node in the different lane.
1135 
1136     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1137     static const int ScoreConsecutiveLoads = 4;
1138     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1139     static const int ScoreReversedLoads = 3;
1140     /// ExtractElementInst from same vector and consecutive indexes.
1141     static const int ScoreConsecutiveExtracts = 4;
1142     /// ExtractElementInst from same vector and reversed indices.
1143     static const int ScoreReversedExtracts = 3;
1144     /// Constants.
1145     static const int ScoreConstants = 2;
1146     /// Instructions with the same opcode.
1147     static const int ScoreSameOpcode = 2;
1148     /// Instructions with alt opcodes (e.g, add + sub).
1149     static const int ScoreAltOpcodes = 1;
1150     /// Identical instructions (a.k.a. splat or broadcast).
1151     static const int ScoreSplat = 1;
1152     /// Matching with an undef is preferable to failing.
1153     static const int ScoreUndef = 1;
1154     /// Score for failing to find a decent match.
1155     static const int ScoreFail = 0;
1156     /// Score if all users are vectorized.
1157     static const int ScoreAllUserVectorized = 1;
1158 
1159     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1160     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1161     /// MainAltOps.
1162     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1163                                ScalarEvolution &SE, int NumLanes,
1164                                ArrayRef<Value *> MainAltOps) {
1165       if (V1 == V2)
1166         return VLOperands::ScoreSplat;
1167 
1168       auto *LI1 = dyn_cast<LoadInst>(V1);
1169       auto *LI2 = dyn_cast<LoadInst>(V2);
1170       if (LI1 && LI2) {
1171         if (LI1->getParent() != LI2->getParent())
1172           return VLOperands::ScoreFail;
1173 
1174         Optional<int> Dist = getPointersDiff(
1175             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1176             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1177         if (!Dist || *Dist == 0)
1178           return VLOperands::ScoreFail;
1179         // The distance is too large - still may be profitable to use masked
1180         // loads/gathers.
1181         if (std::abs(*Dist) > NumLanes / 2)
1182           return VLOperands::ScoreAltOpcodes;
1183         // This still will detect consecutive loads, but we might have "holes"
1184         // in some cases. It is ok for non-power-2 vectorization and may produce
1185         // better results. It should not affect current vectorization.
1186         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1187                            : VLOperands::ScoreReversedLoads;
1188       }
1189 
1190       auto *C1 = dyn_cast<Constant>(V1);
1191       auto *C2 = dyn_cast<Constant>(V2);
1192       if (C1 && C2)
1193         return VLOperands::ScoreConstants;
1194 
1195       // Extracts from consecutive indexes of the same vector better score as
1196       // the extracts could be optimized away.
1197       Value *EV1;
1198       ConstantInt *Ex1Idx;
1199       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1200         // Undefs are always profitable for extractelements.
1201         if (isa<UndefValue>(V2))
1202           return VLOperands::ScoreConsecutiveExtracts;
1203         Value *EV2 = nullptr;
1204         ConstantInt *Ex2Idx = nullptr;
1205         if (match(V2,
1206                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1207                                                          m_Undef())))) {
1208           // Undefs are always profitable for extractelements.
1209           if (!Ex2Idx)
1210             return VLOperands::ScoreConsecutiveExtracts;
1211           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1212             return VLOperands::ScoreConsecutiveExtracts;
1213           if (EV2 == EV1) {
1214             int Idx1 = Ex1Idx->getZExtValue();
1215             int Idx2 = Ex2Idx->getZExtValue();
1216             int Dist = Idx2 - Idx1;
1217             // The distance is too large - still may be profitable to use
1218             // shuffles.
1219             if (std::abs(Dist) == 0)
1220               return VLOperands::ScoreSplat;
1221             if (std::abs(Dist) > NumLanes / 2)
1222               return VLOperands::ScoreSameOpcode;
1223             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1224                               : VLOperands::ScoreReversedExtracts;
1225           }
1226           return VLOperands::ScoreAltOpcodes;
1227         }
1228         return VLOperands::ScoreFail;
1229       }
1230 
1231       auto *I1 = dyn_cast<Instruction>(V1);
1232       auto *I2 = dyn_cast<Instruction>(V2);
1233       if (I1 && I2) {
1234         if (I1->getParent() != I2->getParent())
1235           return VLOperands::ScoreFail;
1236         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1237         Ops.push_back(I1);
1238         Ops.push_back(I2);
1239         InstructionsState S = getSameOpcode(Ops);
1240         // Note: Only consider instructions with <= 2 operands to avoid
1241         // complexity explosion.
1242         if (S.getOpcode() &&
1243             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1244              !S.isAltShuffle()) &&
1245             all_of(Ops, [&S](Value *V) {
1246               return cast<Instruction>(V)->getNumOperands() ==
1247                      S.MainOp->getNumOperands();
1248             }))
1249           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1250                                   : VLOperands::ScoreSameOpcode;
1251       }
1252 
1253       if (isa<UndefValue>(V2))
1254         return VLOperands::ScoreUndef;
1255 
1256       return VLOperands::ScoreFail;
1257     }
1258 
1259     /// \param Lane lane of the operands under analysis.
1260     /// \param OpIdx operand index in \p Lane lane we're looking the best
1261     /// candidate for.
1262     /// \param Idx operand index of the current candidate value.
1263     /// \returns The additional score due to possible broadcasting of the
1264     /// elements in the lane. It is more profitable to have power-of-2 unique
1265     /// elements in the lane, it will be vectorized with higher probability
1266     /// after removing duplicates. Currently the SLP vectorizer supports only
1267     /// vectorization of the power-of-2 number of unique scalars.
1268     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1269       Value *IdxLaneV = getData(Idx, Lane).V;
1270       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1271         return 0;
1272       SmallPtrSet<Value *, 4> Uniques;
1273       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1274         if (Ln == Lane)
1275           continue;
1276         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1277         if (!isa<Instruction>(OpIdxLnV))
1278           return 0;
1279         Uniques.insert(OpIdxLnV);
1280       }
1281       int UniquesCount = Uniques.size();
1282       int UniquesCntWithIdxLaneV =
1283           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1284       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1285       int UniquesCntWithOpIdxLaneV =
1286           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1287       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1288         return 0;
1289       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1290               UniquesCntWithOpIdxLaneV) -
1291              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1292     }
1293 
1294     /// \param Lane lane of the operands under analysis.
1295     /// \param OpIdx operand index in \p Lane lane we're looking the best
1296     /// candidate for.
1297     /// \param Idx operand index of the current candidate value.
1298     /// \returns The additional score for the scalar which users are all
1299     /// vectorized.
1300     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1301       Value *IdxLaneV = getData(Idx, Lane).V;
1302       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1303       // Do not care about number of uses for vector-like instructions
1304       // (extractelement/extractvalue with constant indices), they are extracts
1305       // themselves and already externally used. Vectorization of such
1306       // instructions does not add extra extractelement instruction, just may
1307       // remove it.
1308       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1309           isVectorLikeInstWithConstOps(OpIdxLaneV))
1310         return VLOperands::ScoreAllUserVectorized;
1311       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1312       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1313         return 0;
1314       return R.areAllUsersVectorized(IdxLaneI, None)
1315                  ? VLOperands::ScoreAllUserVectorized
1316                  : 0;
1317     }
1318 
1319     /// Go through the operands of \p LHS and \p RHS recursively until \p
1320     /// MaxLevel, and return the cummulative score. For example:
1321     /// \verbatim
1322     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1323     ///     \ /         \ /         \ /        \ /
1324     ///      +           +           +          +
1325     ///     G1          G2          G3         G4
1326     /// \endverbatim
1327     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1328     /// each level recursively, accumulating the score. It starts from matching
1329     /// the additions at level 0, then moves on to the loads (level 1). The
1330     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1331     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1332     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1333     /// Please note that the order of the operands does not matter, as we
1334     /// evaluate the score of all profitable combinations of operands. In
1335     /// other words the score of G1 and G4 is the same as G1 and G2. This
1336     /// heuristic is based on ideas described in:
1337     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1338     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1339     ///   Luís F. W. Góes
1340     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1341                            ArrayRef<Value *> MainAltOps) {
1342 
1343       // Get the shallow score of V1 and V2.
1344       int ShallowScoreAtThisLevel =
1345           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1346 
1347       // If reached MaxLevel,
1348       //  or if V1 and V2 are not instructions,
1349       //  or if they are SPLAT,
1350       //  or if they are not consecutive,
1351       //  or if profitable to vectorize loads or extractelements, early return
1352       //  the current cost.
1353       auto *I1 = dyn_cast<Instruction>(LHS);
1354       auto *I2 = dyn_cast<Instruction>(RHS);
1355       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1356           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1357           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1358             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1359             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1360            ShallowScoreAtThisLevel))
1361         return ShallowScoreAtThisLevel;
1362       assert(I1 && I2 && "Should have early exited.");
1363 
1364       // Contains the I2 operand indexes that got matched with I1 operands.
1365       SmallSet<unsigned, 4> Op2Used;
1366 
1367       // Recursion towards the operands of I1 and I2. We are trying all possible
1368       // operand pairs, and keeping track of the best score.
1369       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1370            OpIdx1 != NumOperands1; ++OpIdx1) {
1371         // Try to pair op1I with the best operand of I2.
1372         int MaxTmpScore = 0;
1373         unsigned MaxOpIdx2 = 0;
1374         bool FoundBest = false;
1375         // If I2 is commutative try all combinations.
1376         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1377         unsigned ToIdx = isCommutative(I2)
1378                              ? I2->getNumOperands()
1379                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1380         assert(FromIdx <= ToIdx && "Bad index");
1381         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1382           // Skip operands already paired with OpIdx1.
1383           if (Op2Used.count(OpIdx2))
1384             continue;
1385           // Recursively calculate the cost at each level
1386           int TmpScore =
1387               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1388                                  CurrLevel + 1, MaxLevel, None);
1389           // Look for the best score.
1390           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1391             MaxTmpScore = TmpScore;
1392             MaxOpIdx2 = OpIdx2;
1393             FoundBest = true;
1394           }
1395         }
1396         if (FoundBest) {
1397           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1398           Op2Used.insert(MaxOpIdx2);
1399           ShallowScoreAtThisLevel += MaxTmpScore;
1400         }
1401       }
1402       return ShallowScoreAtThisLevel;
1403     }
1404 
1405     /// Score scaling factor for fully compatible instructions but with
1406     /// different number of external uses. Allows better selection of the
1407     /// instructions with less external uses.
1408     static const int ScoreScaleFactor = 10;
1409 
1410     /// \Returns the look-ahead score, which tells us how much the sub-trees
1411     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1412     /// score. This helps break ties in an informed way when we cannot decide on
1413     /// the order of the operands by just considering the immediate
1414     /// predecessors.
1415     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1416                           int Lane, unsigned OpIdx, unsigned Idx,
1417                           bool &IsUsed) {
1418       int Score =
1419           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1420       if (Score) {
1421         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1422         if (Score <= -SplatScore) {
1423           // Set the minimum score for splat-like sequence to avoid setting
1424           // failed state.
1425           Score = 1;
1426         } else {
1427           Score += SplatScore;
1428           // Scale score to see the difference between different operands
1429           // and similar operands but all vectorized/not all vectorized
1430           // uses. It does not affect actual selection of the best
1431           // compatible operand in general, just allows to select the
1432           // operand with all vectorized uses.
1433           Score *= ScoreScaleFactor;
1434           Score += getExternalUseScore(Lane, OpIdx, Idx);
1435           IsUsed = true;
1436         }
1437       }
1438       return Score;
1439     }
1440 
1441     /// Best defined scores per lanes between the passes. Used to choose the
1442     /// best operand (with the highest score) between the passes.
1443     /// The key - {Operand Index, Lane}.
1444     /// The value - the best score between the passes for the lane and the
1445     /// operand.
1446     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1447         BestScoresPerLanes;
1448 
1449     // Search all operands in Ops[*][Lane] for the one that matches best
1450     // Ops[OpIdx][LastLane] and return its opreand index.
1451     // If no good match can be found, return None.
1452     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1453                                       ArrayRef<ReorderingMode> ReorderingModes,
1454                                       ArrayRef<Value *> MainAltOps) {
1455       unsigned NumOperands = getNumOperands();
1456 
1457       // The operand of the previous lane at OpIdx.
1458       Value *OpLastLane = getData(OpIdx, LastLane).V;
1459 
1460       // Our strategy mode for OpIdx.
1461       ReorderingMode RMode = ReorderingModes[OpIdx];
1462       if (RMode == ReorderingMode::Failed)
1463         return None;
1464 
1465       // The linearized opcode of the operand at OpIdx, Lane.
1466       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1467 
1468       // The best operand index and its score.
1469       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1470       // are using the score to differentiate between the two.
1471       struct BestOpData {
1472         Optional<unsigned> Idx = None;
1473         unsigned Score = 0;
1474       } BestOp;
1475       BestOp.Score =
1476           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1477               .first->second;
1478 
1479       // Track if the operand must be marked as used. If the operand is set to
1480       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1481       // want to reestimate the operands again on the following iterations).
1482       bool IsUsed =
1483           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1484       // Iterate through all unused operands and look for the best.
1485       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1486         // Get the operand at Idx and Lane.
1487         OperandData &OpData = getData(Idx, Lane);
1488         Value *Op = OpData.V;
1489         bool OpAPO = OpData.APO;
1490 
1491         // Skip already selected operands.
1492         if (OpData.IsUsed)
1493           continue;
1494 
1495         // Skip if we are trying to move the operand to a position with a
1496         // different opcode in the linearized tree form. This would break the
1497         // semantics.
1498         if (OpAPO != OpIdxAPO)
1499           continue;
1500 
1501         // Look for an operand that matches the current mode.
1502         switch (RMode) {
1503         case ReorderingMode::Load:
1504         case ReorderingMode::Constant:
1505         case ReorderingMode::Opcode: {
1506           bool LeftToRight = Lane > LastLane;
1507           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1508           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1509           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1510                                         OpIdx, Idx, IsUsed);
1511           if (Score > static_cast<int>(BestOp.Score)) {
1512             BestOp.Idx = Idx;
1513             BestOp.Score = Score;
1514             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1515           }
1516           break;
1517         }
1518         case ReorderingMode::Splat:
1519           if (Op == OpLastLane)
1520             BestOp.Idx = Idx;
1521           break;
1522         case ReorderingMode::Failed:
1523           llvm_unreachable("Not expected Failed reordering mode.");
1524         }
1525       }
1526 
1527       if (BestOp.Idx) {
1528         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1529         return BestOp.Idx;
1530       }
1531       // If we could not find a good match return None.
1532       return None;
1533     }
1534 
1535     /// Helper for reorderOperandVecs.
1536     /// \returns the lane that we should start reordering from. This is the one
1537     /// which has the least number of operands that can freely move about or
1538     /// less profitable because it already has the most optimal set of operands.
1539     unsigned getBestLaneToStartReordering() const {
1540       unsigned Min = UINT_MAX;
1541       unsigned SameOpNumber = 0;
1542       // std::pair<unsigned, unsigned> is used to implement a simple voting
1543       // algorithm and choose the lane with the least number of operands that
1544       // can freely move about or less profitable because it already has the
1545       // most optimal set of operands. The first unsigned is a counter for
1546       // voting, the second unsigned is the counter of lanes with instructions
1547       // with same/alternate opcodes and same parent basic block.
1548       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1549       // Try to be closer to the original results, if we have multiple lanes
1550       // with same cost. If 2 lanes have the same cost, use the one with the
1551       // lowest index.
1552       for (int I = getNumLanes(); I > 0; --I) {
1553         unsigned Lane = I - 1;
1554         OperandsOrderData NumFreeOpsHash =
1555             getMaxNumOperandsThatCanBeReordered(Lane);
1556         // Compare the number of operands that can move and choose the one with
1557         // the least number.
1558         if (NumFreeOpsHash.NumOfAPOs < Min) {
1559           Min = NumFreeOpsHash.NumOfAPOs;
1560           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1561           HashMap.clear();
1562           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1563         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1564                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1565           // Select the most optimal lane in terms of number of operands that
1566           // should be moved around.
1567           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1568           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1569         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1570                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1571           auto It = HashMap.find(NumFreeOpsHash.Hash);
1572           if (It == HashMap.end())
1573             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1574           else
1575             ++It->second.first;
1576         }
1577       }
1578       // Select the lane with the minimum counter.
1579       unsigned BestLane = 0;
1580       unsigned CntMin = UINT_MAX;
1581       for (const auto &Data : reverse(HashMap)) {
1582         if (Data.second.first < CntMin) {
1583           CntMin = Data.second.first;
1584           BestLane = Data.second.second;
1585         }
1586       }
1587       return BestLane;
1588     }
1589 
1590     /// Data structure that helps to reorder operands.
1591     struct OperandsOrderData {
1592       /// The best number of operands with the same APOs, which can be
1593       /// reordered.
1594       unsigned NumOfAPOs = UINT_MAX;
1595       /// Number of operands with the same/alternate instruction opcode and
1596       /// parent.
1597       unsigned NumOpsWithSameOpcodeParent = 0;
1598       /// Hash for the actual operands ordering.
1599       /// Used to count operands, actually their position id and opcode
1600       /// value. It is used in the voting mechanism to find the lane with the
1601       /// least number of operands that can freely move about or less profitable
1602       /// because it already has the most optimal set of operands. Can be
1603       /// replaced with SmallVector<unsigned> instead but hash code is faster
1604       /// and requires less memory.
1605       unsigned Hash = 0;
1606     };
1607     /// \returns the maximum number of operands that are allowed to be reordered
1608     /// for \p Lane and the number of compatible instructions(with the same
1609     /// parent/opcode). This is used as a heuristic for selecting the first lane
1610     /// to start operand reordering.
1611     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1612       unsigned CntTrue = 0;
1613       unsigned NumOperands = getNumOperands();
1614       // Operands with the same APO can be reordered. We therefore need to count
1615       // how many of them we have for each APO, like this: Cnt[APO] = x.
1616       // Since we only have two APOs, namely true and false, we can avoid using
1617       // a map. Instead we can simply count the number of operands that
1618       // correspond to one of them (in this case the 'true' APO), and calculate
1619       // the other by subtracting it from the total number of operands.
1620       // Operands with the same instruction opcode and parent are more
1621       // profitable since we don't need to move them in many cases, with a high
1622       // probability such lane already can be vectorized effectively.
1623       bool AllUndefs = true;
1624       unsigned NumOpsWithSameOpcodeParent = 0;
1625       Instruction *OpcodeI = nullptr;
1626       BasicBlock *Parent = nullptr;
1627       unsigned Hash = 0;
1628       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1629         const OperandData &OpData = getData(OpIdx, Lane);
1630         if (OpData.APO)
1631           ++CntTrue;
1632         // Use Boyer-Moore majority voting for finding the majority opcode and
1633         // the number of times it occurs.
1634         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1635           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1636               I->getParent() != Parent) {
1637             if (NumOpsWithSameOpcodeParent == 0) {
1638               NumOpsWithSameOpcodeParent = 1;
1639               OpcodeI = I;
1640               Parent = I->getParent();
1641             } else {
1642               --NumOpsWithSameOpcodeParent;
1643             }
1644           } else {
1645             ++NumOpsWithSameOpcodeParent;
1646           }
1647         }
1648         Hash = hash_combine(
1649             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1650         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1651       }
1652       if (AllUndefs)
1653         return {};
1654       OperandsOrderData Data;
1655       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1656       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1657       Data.Hash = Hash;
1658       return Data;
1659     }
1660 
1661     /// Go through the instructions in VL and append their operands.
1662     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1663       assert(!VL.empty() && "Bad VL");
1664       assert((empty() || VL.size() == getNumLanes()) &&
1665              "Expected same number of lanes");
1666       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1667       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1668       OpsVec.resize(NumOperands);
1669       unsigned NumLanes = VL.size();
1670       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1671         OpsVec[OpIdx].resize(NumLanes);
1672         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1673           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1674           // Our tree has just 3 nodes: the root and two operands.
1675           // It is therefore trivial to get the APO. We only need to check the
1676           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1677           // RHS operand. The LHS operand of both add and sub is never attached
1678           // to an inversese operation in the linearized form, therefore its APO
1679           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1680 
1681           // Since operand reordering is performed on groups of commutative
1682           // operations or alternating sequences (e.g., +, -), we can safely
1683           // tell the inverse operations by checking commutativity.
1684           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1685           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1686           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1687                                  APO, false};
1688         }
1689       }
1690     }
1691 
1692     /// \returns the number of operands.
1693     unsigned getNumOperands() const { return OpsVec.size(); }
1694 
1695     /// \returns the number of lanes.
1696     unsigned getNumLanes() const { return OpsVec[0].size(); }
1697 
1698     /// \returns the operand value at \p OpIdx and \p Lane.
1699     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1700       return getData(OpIdx, Lane).V;
1701     }
1702 
1703     /// \returns true if the data structure is empty.
1704     bool empty() const { return OpsVec.empty(); }
1705 
1706     /// Clears the data.
1707     void clear() { OpsVec.clear(); }
1708 
1709     /// \Returns true if there are enough operands identical to \p Op to fill
1710     /// the whole vector.
1711     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1712     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1713       bool OpAPO = getData(OpIdx, Lane).APO;
1714       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1715         if (Ln == Lane)
1716           continue;
1717         // This is set to true if we found a candidate for broadcast at Lane.
1718         bool FoundCandidate = false;
1719         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1720           OperandData &Data = getData(OpI, Ln);
1721           if (Data.APO != OpAPO || Data.IsUsed)
1722             continue;
1723           if (Data.V == Op) {
1724             FoundCandidate = true;
1725             Data.IsUsed = true;
1726             break;
1727           }
1728         }
1729         if (!FoundCandidate)
1730           return false;
1731       }
1732       return true;
1733     }
1734 
1735   public:
1736     /// Initialize with all the operands of the instruction vector \p RootVL.
1737     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1738                ScalarEvolution &SE, const BoUpSLP &R)
1739         : DL(DL), SE(SE), R(R) {
1740       // Append all the operands of RootVL.
1741       appendOperandsOfVL(RootVL);
1742     }
1743 
1744     /// \Returns a value vector with the operands across all lanes for the
1745     /// opearnd at \p OpIdx.
1746     ValueList getVL(unsigned OpIdx) const {
1747       ValueList OpVL(OpsVec[OpIdx].size());
1748       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1749              "Expected same num of lanes across all operands");
1750       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1751         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1752       return OpVL;
1753     }
1754 
1755     // Performs operand reordering for 2 or more operands.
1756     // The original operands are in OrigOps[OpIdx][Lane].
1757     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1758     void reorder() {
1759       unsigned NumOperands = getNumOperands();
1760       unsigned NumLanes = getNumLanes();
1761       // Each operand has its own mode. We are using this mode to help us select
1762       // the instructions for each lane, so that they match best with the ones
1763       // we have selected so far.
1764       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1765 
1766       // This is a greedy single-pass algorithm. We are going over each lane
1767       // once and deciding on the best order right away with no back-tracking.
1768       // However, in order to increase its effectiveness, we start with the lane
1769       // that has operands that can move the least. For example, given the
1770       // following lanes:
1771       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1772       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1773       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1774       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1775       // we will start at Lane 1, since the operands of the subtraction cannot
1776       // be reordered. Then we will visit the rest of the lanes in a circular
1777       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1778 
1779       // Find the first lane that we will start our search from.
1780       unsigned FirstLane = getBestLaneToStartReordering();
1781 
1782       // Initialize the modes.
1783       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1784         Value *OpLane0 = getValue(OpIdx, FirstLane);
1785         // Keep track if we have instructions with all the same opcode on one
1786         // side.
1787         if (isa<LoadInst>(OpLane0))
1788           ReorderingModes[OpIdx] = ReorderingMode::Load;
1789         else if (isa<Instruction>(OpLane0)) {
1790           // Check if OpLane0 should be broadcast.
1791           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1792             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1793           else
1794             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1795         }
1796         else if (isa<Constant>(OpLane0))
1797           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1798         else if (isa<Argument>(OpLane0))
1799           // Our best hope is a Splat. It may save some cost in some cases.
1800           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1801         else
1802           // NOTE: This should be unreachable.
1803           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1804       }
1805 
1806       // Check that we don't have same operands. No need to reorder if operands
1807       // are just perfect diamond or shuffled diamond match. Do not do it only
1808       // for possible broadcasts or non-power of 2 number of scalars (just for
1809       // now).
1810       auto &&SkipReordering = [this]() {
1811         SmallPtrSet<Value *, 4> UniqueValues;
1812         ArrayRef<OperandData> Op0 = OpsVec.front();
1813         for (const OperandData &Data : Op0)
1814           UniqueValues.insert(Data.V);
1815         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1816           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1817                 return !UniqueValues.contains(Data.V);
1818               }))
1819             return false;
1820         }
1821         // TODO: Check if we can remove a check for non-power-2 number of
1822         // scalars after full support of non-power-2 vectorization.
1823         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1824       };
1825 
1826       // If the initial strategy fails for any of the operand indexes, then we
1827       // perform reordering again in a second pass. This helps avoid assigning
1828       // high priority to the failed strategy, and should improve reordering for
1829       // the non-failed operand indexes.
1830       for (int Pass = 0; Pass != 2; ++Pass) {
1831         // Check if no need to reorder operands since they're are perfect or
1832         // shuffled diamond match.
1833         // Need to to do it to avoid extra external use cost counting for
1834         // shuffled matches, which may cause regressions.
1835         if (SkipReordering())
1836           break;
1837         // Skip the second pass if the first pass did not fail.
1838         bool StrategyFailed = false;
1839         // Mark all operand data as free to use.
1840         clearUsed();
1841         // We keep the original operand order for the FirstLane, so reorder the
1842         // rest of the lanes. We are visiting the nodes in a circular fashion,
1843         // using FirstLane as the center point and increasing the radius
1844         // distance.
1845         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1846         for (unsigned I = 0; I < NumOperands; ++I)
1847           MainAltOps[I].push_back(getData(I, FirstLane).V);
1848 
1849         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1850           // Visit the lane on the right and then the lane on the left.
1851           for (int Direction : {+1, -1}) {
1852             int Lane = FirstLane + Direction * Distance;
1853             if (Lane < 0 || Lane >= (int)NumLanes)
1854               continue;
1855             int LastLane = Lane - Direction;
1856             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1857                    "Out of bounds");
1858             // Look for a good match for each operand.
1859             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1860               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1861               Optional<unsigned> BestIdx = getBestOperand(
1862                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1863               // By not selecting a value, we allow the operands that follow to
1864               // select a better matching value. We will get a non-null value in
1865               // the next run of getBestOperand().
1866               if (BestIdx) {
1867                 // Swap the current operand with the one returned by
1868                 // getBestOperand().
1869                 swap(OpIdx, BestIdx.getValue(), Lane);
1870               } else {
1871                 // We failed to find a best operand, set mode to 'Failed'.
1872                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1873                 // Enable the second pass.
1874                 StrategyFailed = true;
1875               }
1876               // Try to get the alternate opcode and follow it during analysis.
1877               if (MainAltOps[OpIdx].size() != 2) {
1878                 OperandData &AltOp = getData(OpIdx, Lane);
1879                 InstructionsState OpS =
1880                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1881                 if (OpS.getOpcode() && OpS.isAltShuffle())
1882                   MainAltOps[OpIdx].push_back(AltOp.V);
1883               }
1884             }
1885           }
1886         }
1887         // Skip second pass if the strategy did not fail.
1888         if (!StrategyFailed)
1889           break;
1890       }
1891     }
1892 
1893 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1894     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1895       switch (RMode) {
1896       case ReorderingMode::Load:
1897         return "Load";
1898       case ReorderingMode::Opcode:
1899         return "Opcode";
1900       case ReorderingMode::Constant:
1901         return "Constant";
1902       case ReorderingMode::Splat:
1903         return "Splat";
1904       case ReorderingMode::Failed:
1905         return "Failed";
1906       }
1907       llvm_unreachable("Unimplemented Reordering Type");
1908     }
1909 
1910     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1911                                                    raw_ostream &OS) {
1912       return OS << getModeStr(RMode);
1913     }
1914 
1915     /// Debug print.
1916     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1917       printMode(RMode, dbgs());
1918     }
1919 
1920     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1921       return printMode(RMode, OS);
1922     }
1923 
1924     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1925       const unsigned Indent = 2;
1926       unsigned Cnt = 0;
1927       for (const OperandDataVec &OpDataVec : OpsVec) {
1928         OS << "Operand " << Cnt++ << "\n";
1929         for (const OperandData &OpData : OpDataVec) {
1930           OS.indent(Indent) << "{";
1931           if (Value *V = OpData.V)
1932             OS << *V;
1933           else
1934             OS << "null";
1935           OS << ", APO:" << OpData.APO << "}\n";
1936         }
1937         OS << "\n";
1938       }
1939       return OS;
1940     }
1941 
1942     /// Debug print.
1943     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1944 #endif
1945   };
1946 
1947   /// Checks if the instruction is marked for deletion.
1948   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1949 
1950   /// Marks values operands for later deletion by replacing them with Undefs.
1951   void eraseInstructions(ArrayRef<Value *> AV);
1952 
1953   ~BoUpSLP();
1954 
1955 private:
1956   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1957   /// reordering (i.e. the operands can be reordered because they have only one
1958   /// user and reordarable).
1959   /// \param NonVectorized List of all gather nodes that require reordering
1960   /// (e.g., gather of extractlements or partially vectorizable loads).
1961   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1962   /// reordering, subset of \p NonVectorized.
1963   bool
1964   canReorderOperands(TreeEntry *UserTE,
1965                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1966                      ArrayRef<TreeEntry *> ReorderableGathers,
1967                      SmallVectorImpl<TreeEntry *> &GatherOps);
1968 
1969   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1970   /// if any. If it is not vectorized (gather node), returns nullptr.
1971   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1972     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1973     TreeEntry *TE = nullptr;
1974     const auto *It = find_if(VL, [this, &TE](Value *V) {
1975       TE = getTreeEntry(V);
1976       return TE;
1977     });
1978     if (It != VL.end() && TE->isSame(VL))
1979       return TE;
1980     return nullptr;
1981   }
1982 
1983   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1984   /// if any. If it is not vectorized (gather node), returns nullptr.
1985   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1986                                         unsigned OpIdx) const {
1987     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1988         const_cast<TreeEntry *>(UserTE), OpIdx);
1989   }
1990 
1991   /// Checks if all users of \p I are the part of the vectorization tree.
1992   bool areAllUsersVectorized(Instruction *I,
1993                              ArrayRef<Value *> VectorizedVals) const;
1994 
1995   /// \returns the cost of the vectorizable entry.
1996   InstructionCost getEntryCost(const TreeEntry *E,
1997                                ArrayRef<Value *> VectorizedVals);
1998 
1999   /// This is the recursive part of buildTree.
2000   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2001                      const EdgeInfo &EI);
2002 
2003   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2004   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2005   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2006   /// returns false, setting \p CurrentOrder to either an empty vector or a
2007   /// non-identity permutation that allows to reuse extract instructions.
2008   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2009                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2010 
2011   /// Vectorize a single entry in the tree.
2012   Value *vectorizeTree(TreeEntry *E);
2013 
2014   /// Vectorize a single entry in the tree, starting in \p VL.
2015   Value *vectorizeTree(ArrayRef<Value *> VL);
2016 
2017   /// Create a new vector from a list of scalar values.  Produces a sequence
2018   /// which exploits values reused across lanes, and arranges the inserts
2019   /// for ease of later optimization.
2020   Value *createBuildVector(ArrayRef<Value *> VL);
2021 
2022   /// \returns the scalarization cost for this type. Scalarization in this
2023   /// context means the creation of vectors from a group of scalars. If \p
2024   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2025   /// vector elements.
2026   InstructionCost getGatherCost(FixedVectorType *Ty,
2027                                 const APInt &ShuffledIndices,
2028                                 bool NeedToShuffle) const;
2029 
2030   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2031   /// tree entries.
2032   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2033   /// previous tree entries. \p Mask is filled with the shuffle mask.
2034   Optional<TargetTransformInfo::ShuffleKind>
2035   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2036                         SmallVectorImpl<const TreeEntry *> &Entries);
2037 
2038   /// \returns the scalarization cost for this list of values. Assuming that
2039   /// this subtree gets vectorized, we may need to extract the values from the
2040   /// roots. This method calculates the cost of extracting the values.
2041   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2042 
2043   /// Set the Builder insert point to one after the last instruction in
2044   /// the bundle
2045   void setInsertPointAfterBundle(const TreeEntry *E);
2046 
2047   /// \returns a vector from a collection of scalars in \p VL.
2048   Value *gather(ArrayRef<Value *> VL);
2049 
2050   /// \returns whether the VectorizableTree is fully vectorizable and will
2051   /// be beneficial even the tree height is tiny.
2052   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2053 
2054   /// Reorder commutative or alt operands to get better probability of
2055   /// generating vectorized code.
2056   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2057                                              SmallVectorImpl<Value *> &Left,
2058                                              SmallVectorImpl<Value *> &Right,
2059                                              const DataLayout &DL,
2060                                              ScalarEvolution &SE,
2061                                              const BoUpSLP &R);
2062   struct TreeEntry {
2063     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2064     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2065 
2066     /// \returns true if the scalars in VL are equal to this entry.
2067     bool isSame(ArrayRef<Value *> VL) const {
2068       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2069         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2070           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2071         return VL.size() == Mask.size() &&
2072                std::equal(VL.begin(), VL.end(), Mask.begin(),
2073                           [Scalars](Value *V, int Idx) {
2074                             return (isa<UndefValue>(V) &&
2075                                     Idx == UndefMaskElem) ||
2076                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2077                           });
2078       };
2079       if (!ReorderIndices.empty()) {
2080         // TODO: implement matching if the nodes are just reordered, still can
2081         // treat the vector as the same if the list of scalars matches VL
2082         // directly, without reordering.
2083         SmallVector<int> Mask;
2084         inversePermutation(ReorderIndices, Mask);
2085         if (VL.size() == Scalars.size())
2086           return IsSame(Scalars, Mask);
2087         if (VL.size() == ReuseShuffleIndices.size()) {
2088           ::addMask(Mask, ReuseShuffleIndices);
2089           return IsSame(Scalars, Mask);
2090         }
2091         return false;
2092       }
2093       return IsSame(Scalars, ReuseShuffleIndices);
2094     }
2095 
2096     /// \returns true if current entry has same operands as \p TE.
2097     bool hasEqualOperands(const TreeEntry &TE) const {
2098       if (TE.getNumOperands() != getNumOperands())
2099         return false;
2100       SmallBitVector Used(getNumOperands());
2101       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2102         unsigned PrevCount = Used.count();
2103         for (unsigned K = 0; K < E; ++K) {
2104           if (Used.test(K))
2105             continue;
2106           if (getOperand(K) == TE.getOperand(I)) {
2107             Used.set(K);
2108             break;
2109           }
2110         }
2111         // Check if we actually found the matching operand.
2112         if (PrevCount == Used.count())
2113           return false;
2114       }
2115       return true;
2116     }
2117 
2118     /// \return Final vectorization factor for the node. Defined by the total
2119     /// number of vectorized scalars, including those, used several times in the
2120     /// entry and counted in the \a ReuseShuffleIndices, if any.
2121     unsigned getVectorFactor() const {
2122       if (!ReuseShuffleIndices.empty())
2123         return ReuseShuffleIndices.size();
2124       return Scalars.size();
2125     };
2126 
2127     /// A vector of scalars.
2128     ValueList Scalars;
2129 
2130     /// The Scalars are vectorized into this value. It is initialized to Null.
2131     Value *VectorizedValue = nullptr;
2132 
2133     /// Do we need to gather this sequence or vectorize it
2134     /// (either with vector instruction or with scatter/gather
2135     /// intrinsics for store/load)?
2136     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2137     EntryState State;
2138 
2139     /// Does this sequence require some shuffling?
2140     SmallVector<int, 4> ReuseShuffleIndices;
2141 
2142     /// Does this entry require reordering?
2143     SmallVector<unsigned, 4> ReorderIndices;
2144 
2145     /// Points back to the VectorizableTree.
2146     ///
2147     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2148     /// to be a pointer and needs to be able to initialize the child iterator.
2149     /// Thus we need a reference back to the container to translate the indices
2150     /// to entries.
2151     VecTreeTy &Container;
2152 
2153     /// The TreeEntry index containing the user of this entry.  We can actually
2154     /// have multiple users so the data structure is not truly a tree.
2155     SmallVector<EdgeInfo, 1> UserTreeIndices;
2156 
2157     /// The index of this treeEntry in VectorizableTree.
2158     int Idx = -1;
2159 
2160   private:
2161     /// The operands of each instruction in each lane Operands[op_index][lane].
2162     /// Note: This helps avoid the replication of the code that performs the
2163     /// reordering of operands during buildTree_rec() and vectorizeTree().
2164     SmallVector<ValueList, 2> Operands;
2165 
2166     /// The main/alternate instruction.
2167     Instruction *MainOp = nullptr;
2168     Instruction *AltOp = nullptr;
2169 
2170   public:
2171     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2172     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2173       if (Operands.size() < OpIdx + 1)
2174         Operands.resize(OpIdx + 1);
2175       assert(Operands[OpIdx].empty() && "Already resized?");
2176       assert(OpVL.size() <= Scalars.size() &&
2177              "Number of operands is greater than the number of scalars.");
2178       Operands[OpIdx].resize(OpVL.size());
2179       copy(OpVL, Operands[OpIdx].begin());
2180     }
2181 
2182     /// Set the operands of this bundle in their original order.
2183     void setOperandsInOrder() {
2184       assert(Operands.empty() && "Already initialized?");
2185       auto *I0 = cast<Instruction>(Scalars[0]);
2186       Operands.resize(I0->getNumOperands());
2187       unsigned NumLanes = Scalars.size();
2188       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2189            OpIdx != NumOperands; ++OpIdx) {
2190         Operands[OpIdx].resize(NumLanes);
2191         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2192           auto *I = cast<Instruction>(Scalars[Lane]);
2193           assert(I->getNumOperands() == NumOperands &&
2194                  "Expected same number of operands");
2195           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2196         }
2197       }
2198     }
2199 
2200     /// Reorders operands of the node to the given mask \p Mask.
2201     void reorderOperands(ArrayRef<int> Mask) {
2202       for (ValueList &Operand : Operands)
2203         reorderScalars(Operand, Mask);
2204     }
2205 
2206     /// \returns the \p OpIdx operand of this TreeEntry.
2207     ValueList &getOperand(unsigned OpIdx) {
2208       assert(OpIdx < Operands.size() && "Off bounds");
2209       return Operands[OpIdx];
2210     }
2211 
2212     /// \returns the \p OpIdx operand of this TreeEntry.
2213     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2214       assert(OpIdx < Operands.size() && "Off bounds");
2215       return Operands[OpIdx];
2216     }
2217 
2218     /// \returns the number of operands.
2219     unsigned getNumOperands() const { return Operands.size(); }
2220 
2221     /// \return the single \p OpIdx operand.
2222     Value *getSingleOperand(unsigned OpIdx) const {
2223       assert(OpIdx < Operands.size() && "Off bounds");
2224       assert(!Operands[OpIdx].empty() && "No operand available");
2225       return Operands[OpIdx][0];
2226     }
2227 
2228     /// Some of the instructions in the list have alternate opcodes.
2229     bool isAltShuffle() const { return MainOp != AltOp; }
2230 
2231     bool isOpcodeOrAlt(Instruction *I) const {
2232       unsigned CheckedOpcode = I->getOpcode();
2233       return (getOpcode() == CheckedOpcode ||
2234               getAltOpcode() == CheckedOpcode);
2235     }
2236 
2237     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2238     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2239     /// \p OpValue.
2240     Value *isOneOf(Value *Op) const {
2241       auto *I = dyn_cast<Instruction>(Op);
2242       if (I && isOpcodeOrAlt(I))
2243         return Op;
2244       return MainOp;
2245     }
2246 
2247     void setOperations(const InstructionsState &S) {
2248       MainOp = S.MainOp;
2249       AltOp = S.AltOp;
2250     }
2251 
2252     Instruction *getMainOp() const {
2253       return MainOp;
2254     }
2255 
2256     Instruction *getAltOp() const {
2257       return AltOp;
2258     }
2259 
2260     /// The main/alternate opcodes for the list of instructions.
2261     unsigned getOpcode() const {
2262       return MainOp ? MainOp->getOpcode() : 0;
2263     }
2264 
2265     unsigned getAltOpcode() const {
2266       return AltOp ? AltOp->getOpcode() : 0;
2267     }
2268 
2269     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2270     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2271     int findLaneForValue(Value *V) const {
2272       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2273       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2274       if (!ReorderIndices.empty())
2275         FoundLane = ReorderIndices[FoundLane];
2276       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2277       if (!ReuseShuffleIndices.empty()) {
2278         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2279                                   find(ReuseShuffleIndices, FoundLane));
2280       }
2281       return FoundLane;
2282     }
2283 
2284 #ifndef NDEBUG
2285     /// Debug printer.
2286     LLVM_DUMP_METHOD void dump() const {
2287       dbgs() << Idx << ".\n";
2288       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2289         dbgs() << "Operand " << OpI << ":\n";
2290         for (const Value *V : Operands[OpI])
2291           dbgs().indent(2) << *V << "\n";
2292       }
2293       dbgs() << "Scalars: \n";
2294       for (Value *V : Scalars)
2295         dbgs().indent(2) << *V << "\n";
2296       dbgs() << "State: ";
2297       switch (State) {
2298       case Vectorize:
2299         dbgs() << "Vectorize\n";
2300         break;
2301       case ScatterVectorize:
2302         dbgs() << "ScatterVectorize\n";
2303         break;
2304       case NeedToGather:
2305         dbgs() << "NeedToGather\n";
2306         break;
2307       }
2308       dbgs() << "MainOp: ";
2309       if (MainOp)
2310         dbgs() << *MainOp << "\n";
2311       else
2312         dbgs() << "NULL\n";
2313       dbgs() << "AltOp: ";
2314       if (AltOp)
2315         dbgs() << *AltOp << "\n";
2316       else
2317         dbgs() << "NULL\n";
2318       dbgs() << "VectorizedValue: ";
2319       if (VectorizedValue)
2320         dbgs() << *VectorizedValue << "\n";
2321       else
2322         dbgs() << "NULL\n";
2323       dbgs() << "ReuseShuffleIndices: ";
2324       if (ReuseShuffleIndices.empty())
2325         dbgs() << "Empty";
2326       else
2327         for (int ReuseIdx : ReuseShuffleIndices)
2328           dbgs() << ReuseIdx << ", ";
2329       dbgs() << "\n";
2330       dbgs() << "ReorderIndices: ";
2331       for (unsigned ReorderIdx : ReorderIndices)
2332         dbgs() << ReorderIdx << ", ";
2333       dbgs() << "\n";
2334       dbgs() << "UserTreeIndices: ";
2335       for (const auto &EInfo : UserTreeIndices)
2336         dbgs() << EInfo << ", ";
2337       dbgs() << "\n";
2338     }
2339 #endif
2340   };
2341 
2342 #ifndef NDEBUG
2343   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2344                      InstructionCost VecCost,
2345                      InstructionCost ScalarCost) const {
2346     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2347     dbgs() << "SLP: Costs:\n";
2348     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2349     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2350     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2351     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2352                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2353   }
2354 #endif
2355 
2356   /// Create a new VectorizableTree entry.
2357   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2358                           const InstructionsState &S,
2359                           const EdgeInfo &UserTreeIdx,
2360                           ArrayRef<int> ReuseShuffleIndices = None,
2361                           ArrayRef<unsigned> ReorderIndices = None) {
2362     TreeEntry::EntryState EntryState =
2363         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2364     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2365                         ReuseShuffleIndices, ReorderIndices);
2366   }
2367 
2368   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2369                           TreeEntry::EntryState EntryState,
2370                           Optional<ScheduleData *> Bundle,
2371                           const InstructionsState &S,
2372                           const EdgeInfo &UserTreeIdx,
2373                           ArrayRef<int> ReuseShuffleIndices = None,
2374                           ArrayRef<unsigned> ReorderIndices = None) {
2375     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2376             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2377            "Need to vectorize gather entry?");
2378     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2379     TreeEntry *Last = VectorizableTree.back().get();
2380     Last->Idx = VectorizableTree.size() - 1;
2381     Last->State = EntryState;
2382     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2383                                      ReuseShuffleIndices.end());
2384     if (ReorderIndices.empty()) {
2385       Last->Scalars.assign(VL.begin(), VL.end());
2386       Last->setOperations(S);
2387     } else {
2388       // Reorder scalars and build final mask.
2389       Last->Scalars.assign(VL.size(), nullptr);
2390       transform(ReorderIndices, Last->Scalars.begin(),
2391                 [VL](unsigned Idx) -> Value * {
2392                   if (Idx >= VL.size())
2393                     return UndefValue::get(VL.front()->getType());
2394                   return VL[Idx];
2395                 });
2396       InstructionsState S = getSameOpcode(Last->Scalars);
2397       Last->setOperations(S);
2398       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2399     }
2400     if (Last->State != TreeEntry::NeedToGather) {
2401       for (Value *V : VL) {
2402         assert(!getTreeEntry(V) && "Scalar already in tree!");
2403         ScalarToTreeEntry[V] = Last;
2404       }
2405       // Update the scheduler bundle to point to this TreeEntry.
2406       ScheduleData *BundleMember = Bundle.getValue();
2407       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2408               isVectorLikeInstWithConstOps(S.MainOp) ||
2409               doesNotNeedToSchedule(VL)) &&
2410              "Bundle and VL out of sync");
2411       if (BundleMember) {
2412         for (Value *V : VL) {
2413           if (doesNotNeedToBeScheduled(V))
2414             continue;
2415           assert(BundleMember && "Unexpected end of bundle.");
2416           BundleMember->TE = Last;
2417           BundleMember = BundleMember->NextInBundle;
2418         }
2419       }
2420       assert(!BundleMember && "Bundle and VL out of sync");
2421     } else {
2422       MustGather.insert(VL.begin(), VL.end());
2423     }
2424 
2425     if (UserTreeIdx.UserTE)
2426       Last->UserTreeIndices.push_back(UserTreeIdx);
2427 
2428     return Last;
2429   }
2430 
2431   /// -- Vectorization State --
2432   /// Holds all of the tree entries.
2433   TreeEntry::VecTreeTy VectorizableTree;
2434 
2435 #ifndef NDEBUG
2436   /// Debug printer.
2437   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2438     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2439       VectorizableTree[Id]->dump();
2440       dbgs() << "\n";
2441     }
2442   }
2443 #endif
2444 
2445   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2446 
2447   const TreeEntry *getTreeEntry(Value *V) const {
2448     return ScalarToTreeEntry.lookup(V);
2449   }
2450 
2451   /// Maps a specific scalar to its tree entry.
2452   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2453 
2454   /// Maps a value to the proposed vectorizable size.
2455   SmallDenseMap<Value *, unsigned> InstrElementSize;
2456 
2457   /// A list of scalars that we found that we need to keep as scalars.
2458   ValueSet MustGather;
2459 
2460   /// This POD struct describes one external user in the vectorized tree.
2461   struct ExternalUser {
2462     ExternalUser(Value *S, llvm::User *U, int L)
2463         : Scalar(S), User(U), Lane(L) {}
2464 
2465     // Which scalar in our function.
2466     Value *Scalar;
2467 
2468     // Which user that uses the scalar.
2469     llvm::User *User;
2470 
2471     // Which lane does the scalar belong to.
2472     int Lane;
2473   };
2474   using UserList = SmallVector<ExternalUser, 16>;
2475 
2476   /// Checks if two instructions may access the same memory.
2477   ///
2478   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2479   /// is invariant in the calling loop.
2480   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2481                  Instruction *Inst2) {
2482     // First check if the result is already in the cache.
2483     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2484     Optional<bool> &result = AliasCache[key];
2485     if (result.hasValue()) {
2486       return result.getValue();
2487     }
2488     bool aliased = true;
2489     if (Loc1.Ptr && isSimple(Inst1))
2490       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2491     // Store the result in the cache.
2492     result = aliased;
2493     return aliased;
2494   }
2495 
2496   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2497 
2498   /// Cache for alias results.
2499   /// TODO: consider moving this to the AliasAnalysis itself.
2500   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2501 
2502   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2503   // globally through SLP because we don't perform any action which
2504   // invalidates capture results.
2505   BatchAAResults BatchAA;
2506 
2507   /// Removes an instruction from its block and eventually deletes it.
2508   /// It's like Instruction::eraseFromParent() except that the actual deletion
2509   /// is delayed until BoUpSLP is destructed.
2510   /// This is required to ensure that there are no incorrect collisions in the
2511   /// AliasCache, which can happen if a new instruction is allocated at the
2512   /// same address as a previously deleted instruction.
2513   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2514     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2515     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2516   }
2517 
2518   /// Temporary store for deleted instructions. Instructions will be deleted
2519   /// eventually when the BoUpSLP is destructed.
2520   DenseMap<Instruction *, bool> DeletedInstructions;
2521 
2522   /// A list of values that need to extracted out of the tree.
2523   /// This list holds pairs of (Internal Scalar : External User). External User
2524   /// can be nullptr, it means that this Internal Scalar will be used later,
2525   /// after vectorization.
2526   UserList ExternalUses;
2527 
2528   /// Values used only by @llvm.assume calls.
2529   SmallPtrSet<const Value *, 32> EphValues;
2530 
2531   /// Holds all of the instructions that we gathered.
2532   SetVector<Instruction *> GatherShuffleSeq;
2533 
2534   /// A list of blocks that we are going to CSE.
2535   SetVector<BasicBlock *> CSEBlocks;
2536 
2537   /// Contains all scheduling relevant data for an instruction.
2538   /// A ScheduleData either represents a single instruction or a member of an
2539   /// instruction bundle (= a group of instructions which is combined into a
2540   /// vector instruction).
2541   struct ScheduleData {
2542     // The initial value for the dependency counters. It means that the
2543     // dependencies are not calculated yet.
2544     enum { InvalidDeps = -1 };
2545 
2546     ScheduleData() = default;
2547 
2548     void init(int BlockSchedulingRegionID, Value *OpVal) {
2549       FirstInBundle = this;
2550       NextInBundle = nullptr;
2551       NextLoadStore = nullptr;
2552       IsScheduled = false;
2553       SchedulingRegionID = BlockSchedulingRegionID;
2554       clearDependencies();
2555       OpValue = OpVal;
2556       TE = nullptr;
2557     }
2558 
2559     /// Verify basic self consistency properties
2560     void verify() {
2561       if (hasValidDependencies()) {
2562         assert(UnscheduledDeps <= Dependencies && "invariant");
2563       } else {
2564         assert(UnscheduledDeps == Dependencies && "invariant");
2565       }
2566 
2567       if (IsScheduled) {
2568         assert(isSchedulingEntity() &&
2569                 "unexpected scheduled state");
2570         for (const ScheduleData *BundleMember = this; BundleMember;
2571              BundleMember = BundleMember->NextInBundle) {
2572           assert(BundleMember->hasValidDependencies() &&
2573                  BundleMember->UnscheduledDeps == 0 &&
2574                  "unexpected scheduled state");
2575           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2576                  "only bundle is marked scheduled");
2577         }
2578       }
2579 
2580       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2581              "all bundle members must be in same basic block");
2582     }
2583 
2584     /// Returns true if the dependency information has been calculated.
2585     /// Note that depenendency validity can vary between instructions within
2586     /// a single bundle.
2587     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2588 
2589     /// Returns true for single instructions and for bundle representatives
2590     /// (= the head of a bundle).
2591     bool isSchedulingEntity() const { return FirstInBundle == this; }
2592 
2593     /// Returns true if it represents an instruction bundle and not only a
2594     /// single instruction.
2595     bool isPartOfBundle() const {
2596       return NextInBundle != nullptr || FirstInBundle != this || TE;
2597     }
2598 
2599     /// Returns true if it is ready for scheduling, i.e. it has no more
2600     /// unscheduled depending instructions/bundles.
2601     bool isReady() const {
2602       assert(isSchedulingEntity() &&
2603              "can't consider non-scheduling entity for ready list");
2604       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2605     }
2606 
2607     /// Modifies the number of unscheduled dependencies for this instruction,
2608     /// and returns the number of remaining dependencies for the containing
2609     /// bundle.
2610     int incrementUnscheduledDeps(int Incr) {
2611       assert(hasValidDependencies() &&
2612              "increment of unscheduled deps would be meaningless");
2613       UnscheduledDeps += Incr;
2614       return FirstInBundle->unscheduledDepsInBundle();
2615     }
2616 
2617     /// Sets the number of unscheduled dependencies to the number of
2618     /// dependencies.
2619     void resetUnscheduledDeps() {
2620       UnscheduledDeps = Dependencies;
2621     }
2622 
2623     /// Clears all dependency information.
2624     void clearDependencies() {
2625       Dependencies = InvalidDeps;
2626       resetUnscheduledDeps();
2627       MemoryDependencies.clear();
2628     }
2629 
2630     int unscheduledDepsInBundle() const {
2631       assert(isSchedulingEntity() && "only meaningful on the bundle");
2632       int Sum = 0;
2633       for (const ScheduleData *BundleMember = this; BundleMember;
2634            BundleMember = BundleMember->NextInBundle) {
2635         if (BundleMember->UnscheduledDeps == InvalidDeps)
2636           return InvalidDeps;
2637         Sum += BundleMember->UnscheduledDeps;
2638       }
2639       return Sum;
2640     }
2641 
2642     void dump(raw_ostream &os) const {
2643       if (!isSchedulingEntity()) {
2644         os << "/ " << *Inst;
2645       } else if (NextInBundle) {
2646         os << '[' << *Inst;
2647         ScheduleData *SD = NextInBundle;
2648         while (SD) {
2649           os << ';' << *SD->Inst;
2650           SD = SD->NextInBundle;
2651         }
2652         os << ']';
2653       } else {
2654         os << *Inst;
2655       }
2656     }
2657 
2658     Instruction *Inst = nullptr;
2659 
2660     /// Opcode of the current instruction in the schedule data.
2661     Value *OpValue = nullptr;
2662 
2663     /// The TreeEntry that this instruction corresponds to.
2664     TreeEntry *TE = nullptr;
2665 
2666     /// Points to the head in an instruction bundle (and always to this for
2667     /// single instructions).
2668     ScheduleData *FirstInBundle = nullptr;
2669 
2670     /// Single linked list of all instructions in a bundle. Null if it is a
2671     /// single instruction.
2672     ScheduleData *NextInBundle = nullptr;
2673 
2674     /// Single linked list of all memory instructions (e.g. load, store, call)
2675     /// in the block - until the end of the scheduling region.
2676     ScheduleData *NextLoadStore = nullptr;
2677 
2678     /// The dependent memory instructions.
2679     /// This list is derived on demand in calculateDependencies().
2680     SmallVector<ScheduleData *, 4> MemoryDependencies;
2681 
2682     /// This ScheduleData is in the current scheduling region if this matches
2683     /// the current SchedulingRegionID of BlockScheduling.
2684     int SchedulingRegionID = 0;
2685 
2686     /// Used for getting a "good" final ordering of instructions.
2687     int SchedulingPriority = 0;
2688 
2689     /// The number of dependencies. Constitutes of the number of users of the
2690     /// instruction plus the number of dependent memory instructions (if any).
2691     /// This value is calculated on demand.
2692     /// If InvalidDeps, the number of dependencies is not calculated yet.
2693     int Dependencies = InvalidDeps;
2694 
2695     /// The number of dependencies minus the number of dependencies of scheduled
2696     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2697     /// for scheduling.
2698     /// Note that this is negative as long as Dependencies is not calculated.
2699     int UnscheduledDeps = InvalidDeps;
2700 
2701     /// True if this instruction is scheduled (or considered as scheduled in the
2702     /// dry-run).
2703     bool IsScheduled = false;
2704   };
2705 
2706 #ifndef NDEBUG
2707   friend inline raw_ostream &operator<<(raw_ostream &os,
2708                                         const BoUpSLP::ScheduleData &SD) {
2709     SD.dump(os);
2710     return os;
2711   }
2712 #endif
2713 
2714   friend struct GraphTraits<BoUpSLP *>;
2715   friend struct DOTGraphTraits<BoUpSLP *>;
2716 
2717   /// Contains all scheduling data for a basic block.
2718   /// It does not schedules instructions, which are not memory read/write
2719   /// instructions and their operands are either constants, or arguments, or
2720   /// phis, or instructions from others blocks, or their users are phis or from
2721   /// the other blocks. The resulting vector instructions can be placed at the
2722   /// beginning of the basic block without scheduling (if operands does not need
2723   /// to be scheduled) or at the end of the block (if users are outside of the
2724   /// block). It allows to save some compile time and memory used by the
2725   /// compiler.
2726   /// ScheduleData is assigned for each instruction in between the boundaries of
2727   /// the tree entry, even for those, which are not part of the graph. It is
2728   /// required to correctly follow the dependencies between the instructions and
2729   /// their correct scheduling. The ScheduleData is not allocated for the
2730   /// instructions, which do not require scheduling, like phis, nodes with
2731   /// extractelements/insertelements only or nodes with instructions, with
2732   /// uses/operands outside of the block.
2733   struct BlockScheduling {
2734     BlockScheduling(BasicBlock *BB)
2735         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2736 
2737     void clear() {
2738       ReadyInsts.clear();
2739       ScheduleStart = nullptr;
2740       ScheduleEnd = nullptr;
2741       FirstLoadStoreInRegion = nullptr;
2742       LastLoadStoreInRegion = nullptr;
2743 
2744       // Reduce the maximum schedule region size by the size of the
2745       // previous scheduling run.
2746       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2747       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2748         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2749       ScheduleRegionSize = 0;
2750 
2751       // Make a new scheduling region, i.e. all existing ScheduleData is not
2752       // in the new region yet.
2753       ++SchedulingRegionID;
2754     }
2755 
2756     ScheduleData *getScheduleData(Instruction *I) {
2757       if (BB != I->getParent())
2758         // Avoid lookup if can't possibly be in map.
2759         return nullptr;
2760       ScheduleData *SD = ScheduleDataMap.lookup(I);
2761       if (SD && isInSchedulingRegion(SD))
2762         return SD;
2763       return nullptr;
2764     }
2765 
2766     ScheduleData *getScheduleData(Value *V) {
2767       if (auto *I = dyn_cast<Instruction>(V))
2768         return getScheduleData(I);
2769       return nullptr;
2770     }
2771 
2772     ScheduleData *getScheduleData(Value *V, Value *Key) {
2773       if (V == Key)
2774         return getScheduleData(V);
2775       auto I = ExtraScheduleDataMap.find(V);
2776       if (I != ExtraScheduleDataMap.end()) {
2777         ScheduleData *SD = I->second.lookup(Key);
2778         if (SD && isInSchedulingRegion(SD))
2779           return SD;
2780       }
2781       return nullptr;
2782     }
2783 
2784     bool isInSchedulingRegion(ScheduleData *SD) const {
2785       return SD->SchedulingRegionID == SchedulingRegionID;
2786     }
2787 
2788     /// Marks an instruction as scheduled and puts all dependent ready
2789     /// instructions into the ready-list.
2790     template <typename ReadyListType>
2791     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2792       SD->IsScheduled = true;
2793       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2794 
2795       for (ScheduleData *BundleMember = SD; BundleMember;
2796            BundleMember = BundleMember->NextInBundle) {
2797         if (BundleMember->Inst != BundleMember->OpValue)
2798           continue;
2799 
2800         // Handle the def-use chain dependencies.
2801 
2802         // Decrement the unscheduled counter and insert to ready list if ready.
2803         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2804           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2805             if (OpDef && OpDef->hasValidDependencies() &&
2806                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2807               // There are no more unscheduled dependencies after
2808               // decrementing, so we can put the dependent instruction
2809               // into the ready list.
2810               ScheduleData *DepBundle = OpDef->FirstInBundle;
2811               assert(!DepBundle->IsScheduled &&
2812                      "already scheduled bundle gets ready");
2813               ReadyList.insert(DepBundle);
2814               LLVM_DEBUG(dbgs()
2815                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2816             }
2817           });
2818         };
2819 
2820         // If BundleMember is a vector bundle, its operands may have been
2821         // reordered during buildTree(). We therefore need to get its operands
2822         // through the TreeEntry.
2823         if (TreeEntry *TE = BundleMember->TE) {
2824           // Need to search for the lane since the tree entry can be reordered.
2825           int Lane = std::distance(TE->Scalars.begin(),
2826                                    find(TE->Scalars, BundleMember->Inst));
2827           assert(Lane >= 0 && "Lane not set");
2828 
2829           // Since vectorization tree is being built recursively this assertion
2830           // ensures that the tree entry has all operands set before reaching
2831           // this code. Couple of exceptions known at the moment are extracts
2832           // where their second (immediate) operand is not added. Since
2833           // immediates do not affect scheduler behavior this is considered
2834           // okay.
2835           auto *In = BundleMember->Inst;
2836           assert(In &&
2837                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2838                   In->getNumOperands() == TE->getNumOperands()) &&
2839                  "Missed TreeEntry operands?");
2840           (void)In; // fake use to avoid build failure when assertions disabled
2841 
2842           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2843                OpIdx != NumOperands; ++OpIdx)
2844             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2845               DecrUnsched(I);
2846         } else {
2847           // If BundleMember is a stand-alone instruction, no operand reordering
2848           // has taken place, so we directly access its operands.
2849           for (Use &U : BundleMember->Inst->operands())
2850             if (auto *I = dyn_cast<Instruction>(U.get()))
2851               DecrUnsched(I);
2852         }
2853         // Handle the memory dependencies.
2854         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2855           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2856             // There are no more unscheduled dependencies after decrementing,
2857             // so we can put the dependent instruction into the ready list.
2858             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2859             assert(!DepBundle->IsScheduled &&
2860                    "already scheduled bundle gets ready");
2861             ReadyList.insert(DepBundle);
2862             LLVM_DEBUG(dbgs()
2863                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2864           }
2865         }
2866       }
2867     }
2868 
2869     /// Verify basic self consistency properties of the data structure.
2870     void verify() {
2871       if (!ScheduleStart)
2872         return;
2873 
2874       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2875              ScheduleStart->comesBefore(ScheduleEnd) &&
2876              "Not a valid scheduling region?");
2877 
2878       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2879         auto *SD = getScheduleData(I);
2880         if (!SD)
2881           continue;
2882         assert(isInSchedulingRegion(SD) &&
2883                "primary schedule data not in window?");
2884         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2885                "entire bundle in window!");
2886         (void)SD;
2887         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2888       }
2889 
2890       for (auto *SD : ReadyInsts) {
2891         assert(SD->isSchedulingEntity() && SD->isReady() &&
2892                "item in ready list not ready?");
2893         (void)SD;
2894       }
2895     }
2896 
2897     void doForAllOpcodes(Value *V,
2898                          function_ref<void(ScheduleData *SD)> Action) {
2899       if (ScheduleData *SD = getScheduleData(V))
2900         Action(SD);
2901       auto I = ExtraScheduleDataMap.find(V);
2902       if (I != ExtraScheduleDataMap.end())
2903         for (auto &P : I->second)
2904           if (isInSchedulingRegion(P.second))
2905             Action(P.second);
2906     }
2907 
2908     /// Put all instructions into the ReadyList which are ready for scheduling.
2909     template <typename ReadyListType>
2910     void initialFillReadyList(ReadyListType &ReadyList) {
2911       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2912         doForAllOpcodes(I, [&](ScheduleData *SD) {
2913           if (SD->isSchedulingEntity() && SD->isReady()) {
2914             ReadyList.insert(SD);
2915             LLVM_DEBUG(dbgs()
2916                        << "SLP:    initially in ready list: " << *SD << "\n");
2917           }
2918         });
2919       }
2920     }
2921 
2922     /// Build a bundle from the ScheduleData nodes corresponding to the
2923     /// scalar instruction for each lane.
2924     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2925 
2926     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2927     /// cyclic dependencies. This is only a dry-run, no instructions are
2928     /// actually moved at this stage.
2929     /// \returns the scheduling bundle. The returned Optional value is non-None
2930     /// if \p VL is allowed to be scheduled.
2931     Optional<ScheduleData *>
2932     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2933                       const InstructionsState &S);
2934 
2935     /// Un-bundles a group of instructions.
2936     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2937 
2938     /// Allocates schedule data chunk.
2939     ScheduleData *allocateScheduleDataChunks();
2940 
2941     /// Extends the scheduling region so that V is inside the region.
2942     /// \returns true if the region size is within the limit.
2943     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2944 
2945     /// Initialize the ScheduleData structures for new instructions in the
2946     /// scheduling region.
2947     void initScheduleData(Instruction *FromI, Instruction *ToI,
2948                           ScheduleData *PrevLoadStore,
2949                           ScheduleData *NextLoadStore);
2950 
2951     /// Updates the dependency information of a bundle and of all instructions/
2952     /// bundles which depend on the original bundle.  Note that only
2953     /// def-use and memory dependencies are explicitly modeled.  We do not
2954     /// track control dependencies (e.g. a potentially faulting load following
2955     /// a potentially infinte looping readnone call), and as such the resulting
2956     /// graph is a subgraph of the full dependency graph.
2957     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2958                                BoUpSLP *SLP);
2959 
2960     /// Sets all instruction in the scheduling region to un-scheduled.
2961     void resetSchedule();
2962 
2963     BasicBlock *BB;
2964 
2965     /// Simple memory allocation for ScheduleData.
2966     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2967 
2968     /// The size of a ScheduleData array in ScheduleDataChunks.
2969     int ChunkSize;
2970 
2971     /// The allocator position in the current chunk, which is the last entry
2972     /// of ScheduleDataChunks.
2973     int ChunkPos;
2974 
2975     /// Attaches ScheduleData to Instruction.
2976     /// Note that the mapping survives during all vectorization iterations, i.e.
2977     /// ScheduleData structures are recycled.
2978     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2979 
2980     /// Attaches ScheduleData to Instruction with the leading key.
2981     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2982         ExtraScheduleDataMap;
2983 
2984     /// The ready-list for scheduling (only used for the dry-run).
2985     SetVector<ScheduleData *> ReadyInsts;
2986 
2987     /// The first instruction of the scheduling region.
2988     Instruction *ScheduleStart = nullptr;
2989 
2990     /// The first instruction _after_ the scheduling region.
2991     Instruction *ScheduleEnd = nullptr;
2992 
2993     /// The first memory accessing instruction in the scheduling region
2994     /// (can be null).
2995     ScheduleData *FirstLoadStoreInRegion = nullptr;
2996 
2997     /// The last memory accessing instruction in the scheduling region
2998     /// (can be null).
2999     ScheduleData *LastLoadStoreInRegion = nullptr;
3000 
3001     /// The current size of the scheduling region.
3002     int ScheduleRegionSize = 0;
3003 
3004     /// The maximum size allowed for the scheduling region.
3005     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3006 
3007     /// The ID of the scheduling region. For a new vectorization iteration this
3008     /// is incremented which "removes" all ScheduleData from the region.
3009     /// Make sure that the initial SchedulingRegionID is greater than the
3010     /// initial SchedulingRegionID in ScheduleData (which is 0).
3011     int SchedulingRegionID = 1;
3012   };
3013 
3014   /// Attaches the BlockScheduling structures to basic blocks.
3015   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3016 
3017   /// Performs the "real" scheduling. Done before vectorization is actually
3018   /// performed in a basic block.
3019   void scheduleBlock(BlockScheduling *BS);
3020 
3021   /// List of users to ignore during scheduling and that don't need extracting.
3022   ArrayRef<Value *> UserIgnoreList;
3023 
3024   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3025   /// sorted SmallVectors of unsigned.
3026   struct OrdersTypeDenseMapInfo {
3027     static OrdersType getEmptyKey() {
3028       OrdersType V;
3029       V.push_back(~1U);
3030       return V;
3031     }
3032 
3033     static OrdersType getTombstoneKey() {
3034       OrdersType V;
3035       V.push_back(~2U);
3036       return V;
3037     }
3038 
3039     static unsigned getHashValue(const OrdersType &V) {
3040       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3041     }
3042 
3043     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3044       return LHS == RHS;
3045     }
3046   };
3047 
3048   // Analysis and block reference.
3049   Function *F;
3050   ScalarEvolution *SE;
3051   TargetTransformInfo *TTI;
3052   TargetLibraryInfo *TLI;
3053   LoopInfo *LI;
3054   DominatorTree *DT;
3055   AssumptionCache *AC;
3056   DemandedBits *DB;
3057   const DataLayout *DL;
3058   OptimizationRemarkEmitter *ORE;
3059 
3060   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3061   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3062 
3063   /// Instruction builder to construct the vectorized tree.
3064   IRBuilder<> Builder;
3065 
3066   /// A map of scalar integer values to the smallest bit width with which they
3067   /// can legally be represented. The values map to (width, signed) pairs,
3068   /// where "width" indicates the minimum bit width and "signed" is True if the
3069   /// value must be signed-extended, rather than zero-extended, back to its
3070   /// original width.
3071   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3072 };
3073 
3074 } // end namespace slpvectorizer
3075 
3076 template <> struct GraphTraits<BoUpSLP *> {
3077   using TreeEntry = BoUpSLP::TreeEntry;
3078 
3079   /// NodeRef has to be a pointer per the GraphWriter.
3080   using NodeRef = TreeEntry *;
3081 
3082   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3083 
3084   /// Add the VectorizableTree to the index iterator to be able to return
3085   /// TreeEntry pointers.
3086   struct ChildIteratorType
3087       : public iterator_adaptor_base<
3088             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3089     ContainerTy &VectorizableTree;
3090 
3091     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3092                       ContainerTy &VT)
3093         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3094 
3095     NodeRef operator*() { return I->UserTE; }
3096   };
3097 
3098   static NodeRef getEntryNode(BoUpSLP &R) {
3099     return R.VectorizableTree[0].get();
3100   }
3101 
3102   static ChildIteratorType child_begin(NodeRef N) {
3103     return {N->UserTreeIndices.begin(), N->Container};
3104   }
3105 
3106   static ChildIteratorType child_end(NodeRef N) {
3107     return {N->UserTreeIndices.end(), N->Container};
3108   }
3109 
3110   /// For the node iterator we just need to turn the TreeEntry iterator into a
3111   /// TreeEntry* iterator so that it dereferences to NodeRef.
3112   class nodes_iterator {
3113     using ItTy = ContainerTy::iterator;
3114     ItTy It;
3115 
3116   public:
3117     nodes_iterator(const ItTy &It2) : It(It2) {}
3118     NodeRef operator*() { return It->get(); }
3119     nodes_iterator operator++() {
3120       ++It;
3121       return *this;
3122     }
3123     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3124   };
3125 
3126   static nodes_iterator nodes_begin(BoUpSLP *R) {
3127     return nodes_iterator(R->VectorizableTree.begin());
3128   }
3129 
3130   static nodes_iterator nodes_end(BoUpSLP *R) {
3131     return nodes_iterator(R->VectorizableTree.end());
3132   }
3133 
3134   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3135 };
3136 
3137 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3138   using TreeEntry = BoUpSLP::TreeEntry;
3139 
3140   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3141 
3142   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3143     std::string Str;
3144     raw_string_ostream OS(Str);
3145     if (isSplat(Entry->Scalars))
3146       OS << "<splat> ";
3147     for (auto V : Entry->Scalars) {
3148       OS << *V;
3149       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3150             return EU.Scalar == V;
3151           }))
3152         OS << " <extract>";
3153       OS << "\n";
3154     }
3155     return Str;
3156   }
3157 
3158   static std::string getNodeAttributes(const TreeEntry *Entry,
3159                                        const BoUpSLP *) {
3160     if (Entry->State == TreeEntry::NeedToGather)
3161       return "color=red";
3162     return "";
3163   }
3164 };
3165 
3166 } // end namespace llvm
3167 
3168 BoUpSLP::~BoUpSLP() {
3169   for (const auto &Pair : DeletedInstructions) {
3170     // Replace operands of ignored instructions with Undefs in case if they were
3171     // marked for deletion.
3172     if (Pair.getSecond()) {
3173       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3174       Pair.getFirst()->replaceAllUsesWith(Undef);
3175     }
3176     Pair.getFirst()->dropAllReferences();
3177   }
3178   for (const auto &Pair : DeletedInstructions) {
3179     assert(Pair.getFirst()->use_empty() &&
3180            "trying to erase instruction with users.");
3181     Pair.getFirst()->eraseFromParent();
3182   }
3183 #ifdef EXPENSIVE_CHECKS
3184   // If we could guarantee that this call is not extremely slow, we could
3185   // remove the ifdef limitation (see PR47712).
3186   assert(!verifyFunction(*F, &dbgs()));
3187 #endif
3188 }
3189 
3190 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3191   for (auto *V : AV) {
3192     if (auto *I = dyn_cast<Instruction>(V))
3193       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3194   };
3195 }
3196 
3197 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3198 /// contains original mask for the scalars reused in the node. Procedure
3199 /// transform this mask in accordance with the given \p Mask.
3200 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3201   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3202          "Expected non-empty mask.");
3203   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3204   Prev.swap(Reuses);
3205   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3206     if (Mask[I] != UndefMaskElem)
3207       Reuses[Mask[I]] = Prev[I];
3208 }
3209 
3210 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3211 /// the original order of the scalars. Procedure transforms the provided order
3212 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3213 /// identity order, \p Order is cleared.
3214 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3215   assert(!Mask.empty() && "Expected non-empty mask.");
3216   SmallVector<int> MaskOrder;
3217   if (Order.empty()) {
3218     MaskOrder.resize(Mask.size());
3219     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3220   } else {
3221     inversePermutation(Order, MaskOrder);
3222   }
3223   reorderReuses(MaskOrder, Mask);
3224   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3225     Order.clear();
3226     return;
3227   }
3228   Order.assign(Mask.size(), Mask.size());
3229   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3230     if (MaskOrder[I] != UndefMaskElem)
3231       Order[MaskOrder[I]] = I;
3232   fixupOrderingIndices(Order);
3233 }
3234 
3235 Optional<BoUpSLP::OrdersType>
3236 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3237   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3238   unsigned NumScalars = TE.Scalars.size();
3239   OrdersType CurrentOrder(NumScalars, NumScalars);
3240   SmallVector<int> Positions;
3241   SmallBitVector UsedPositions(NumScalars);
3242   const TreeEntry *STE = nullptr;
3243   // Try to find all gathered scalars that are gets vectorized in other
3244   // vectorize node. Here we can have only one single tree vector node to
3245   // correctly identify order of the gathered scalars.
3246   for (unsigned I = 0; I < NumScalars; ++I) {
3247     Value *V = TE.Scalars[I];
3248     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3249       continue;
3250     if (const auto *LocalSTE = getTreeEntry(V)) {
3251       if (!STE)
3252         STE = LocalSTE;
3253       else if (STE != LocalSTE)
3254         // Take the order only from the single vector node.
3255         return None;
3256       unsigned Lane =
3257           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3258       if (Lane >= NumScalars)
3259         return None;
3260       if (CurrentOrder[Lane] != NumScalars) {
3261         if (Lane != I)
3262           continue;
3263         UsedPositions.reset(CurrentOrder[Lane]);
3264       }
3265       // The partial identity (where only some elements of the gather node are
3266       // in the identity order) is good.
3267       CurrentOrder[Lane] = I;
3268       UsedPositions.set(I);
3269     }
3270   }
3271   // Need to keep the order if we have a vector entry and at least 2 scalars or
3272   // the vectorized entry has just 2 scalars.
3273   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3274     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3275       for (unsigned I = 0; I < NumScalars; ++I)
3276         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3277           return false;
3278       return true;
3279     };
3280     if (IsIdentityOrder(CurrentOrder)) {
3281       CurrentOrder.clear();
3282       return CurrentOrder;
3283     }
3284     auto *It = CurrentOrder.begin();
3285     for (unsigned I = 0; I < NumScalars;) {
3286       if (UsedPositions.test(I)) {
3287         ++I;
3288         continue;
3289       }
3290       if (*It == NumScalars) {
3291         *It = I;
3292         ++I;
3293       }
3294       ++It;
3295     }
3296     return CurrentOrder;
3297   }
3298   return None;
3299 }
3300 
3301 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3302                                                          bool TopToBottom) {
3303   // No need to reorder if need to shuffle reuses, still need to shuffle the
3304   // node.
3305   if (!TE.ReuseShuffleIndices.empty())
3306     return None;
3307   if (TE.State == TreeEntry::Vectorize &&
3308       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3309        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3310       !TE.isAltShuffle())
3311     return TE.ReorderIndices;
3312   if (TE.State == TreeEntry::NeedToGather) {
3313     // TODO: add analysis of other gather nodes with extractelement
3314     // instructions and other values/instructions, not only undefs.
3315     if (((TE.getOpcode() == Instruction::ExtractElement &&
3316           !TE.isAltShuffle()) ||
3317          (all_of(TE.Scalars,
3318                  [](Value *V) {
3319                    return isa<UndefValue, ExtractElementInst>(V);
3320                  }) &&
3321           any_of(TE.Scalars,
3322                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3323         all_of(TE.Scalars,
3324                [](Value *V) {
3325                  auto *EE = dyn_cast<ExtractElementInst>(V);
3326                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3327                }) &&
3328         allSameType(TE.Scalars)) {
3329       // Check that gather of extractelements can be represented as
3330       // just a shuffle of a single vector.
3331       OrdersType CurrentOrder;
3332       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3333       if (Reuse || !CurrentOrder.empty()) {
3334         if (!CurrentOrder.empty())
3335           fixupOrderingIndices(CurrentOrder);
3336         return CurrentOrder;
3337       }
3338     }
3339     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3340       return CurrentOrder;
3341   }
3342   return None;
3343 }
3344 
3345 void BoUpSLP::reorderTopToBottom() {
3346   // Maps VF to the graph nodes.
3347   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3348   // ExtractElement gather nodes which can be vectorized and need to handle
3349   // their ordering.
3350   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3351   // Find all reorderable nodes with the given VF.
3352   // Currently the are vectorized stores,loads,extracts + some gathering of
3353   // extracts.
3354   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3355                                  const std::unique_ptr<TreeEntry> &TE) {
3356     if (Optional<OrdersType> CurrentOrder =
3357             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3358       // Do not include ordering for nodes used in the alt opcode vectorization,
3359       // better to reorder them during bottom-to-top stage. If follow the order
3360       // here, it causes reordering of the whole graph though actually it is
3361       // profitable just to reorder the subgraph that starts from the alternate
3362       // opcode vectorization node. Such nodes already end-up with the shuffle
3363       // instruction and it is just enough to change this shuffle rather than
3364       // rotate the scalars for the whole graph.
3365       unsigned Cnt = 0;
3366       const TreeEntry *UserTE = TE.get();
3367       while (UserTE && Cnt < RecursionMaxDepth) {
3368         if (UserTE->UserTreeIndices.size() != 1)
3369           break;
3370         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3371               return EI.UserTE->State == TreeEntry::Vectorize &&
3372                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3373             }))
3374           return;
3375         if (UserTE->UserTreeIndices.empty())
3376           UserTE = nullptr;
3377         else
3378           UserTE = UserTE->UserTreeIndices.back().UserTE;
3379         ++Cnt;
3380       }
3381       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3382       if (TE->State != TreeEntry::Vectorize)
3383         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3384     }
3385   });
3386 
3387   // Reorder the graph nodes according to their vectorization factor.
3388   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3389        VF /= 2) {
3390     auto It = VFToOrderedEntries.find(VF);
3391     if (It == VFToOrderedEntries.end())
3392       continue;
3393     // Try to find the most profitable order. We just are looking for the most
3394     // used order and reorder scalar elements in the nodes according to this
3395     // mostly used order.
3396     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3397     // All operands are reordered and used only in this node - propagate the
3398     // most used order to the user node.
3399     MapVector<OrdersType, unsigned,
3400               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3401         OrdersUses;
3402     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3403     for (const TreeEntry *OpTE : OrderedEntries) {
3404       // No need to reorder this nodes, still need to extend and to use shuffle,
3405       // just need to merge reordering shuffle and the reuse shuffle.
3406       if (!OpTE->ReuseShuffleIndices.empty())
3407         continue;
3408       // Count number of orders uses.
3409       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3410         if (OpTE->State == TreeEntry::NeedToGather)
3411           return GathersToOrders.find(OpTE)->second;
3412         return OpTE->ReorderIndices;
3413       }();
3414       // Stores actually store the mask, not the order, need to invert.
3415       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3416           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3417         SmallVector<int> Mask;
3418         inversePermutation(Order, Mask);
3419         unsigned E = Order.size();
3420         OrdersType CurrentOrder(E, E);
3421         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3422           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3423         });
3424         fixupOrderingIndices(CurrentOrder);
3425         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3426       } else {
3427         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3428       }
3429     }
3430     // Set order of the user node.
3431     if (OrdersUses.empty())
3432       continue;
3433     // Choose the most used order.
3434     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3435     unsigned Cnt = OrdersUses.front().second;
3436     for (const auto &Pair : drop_begin(OrdersUses)) {
3437       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3438         BestOrder = Pair.first;
3439         Cnt = Pair.second;
3440       }
3441     }
3442     // Set order of the user node.
3443     if (BestOrder.empty())
3444       continue;
3445     SmallVector<int> Mask;
3446     inversePermutation(BestOrder, Mask);
3447     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3448     unsigned E = BestOrder.size();
3449     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3450       return I < E ? static_cast<int>(I) : UndefMaskElem;
3451     });
3452     // Do an actual reordering, if profitable.
3453     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3454       // Just do the reordering for the nodes with the given VF.
3455       if (TE->Scalars.size() != VF) {
3456         if (TE->ReuseShuffleIndices.size() == VF) {
3457           // Need to reorder the reuses masks of the operands with smaller VF to
3458           // be able to find the match between the graph nodes and scalar
3459           // operands of the given node during vectorization/cost estimation.
3460           assert(all_of(TE->UserTreeIndices,
3461                         [VF, &TE](const EdgeInfo &EI) {
3462                           return EI.UserTE->Scalars.size() == VF ||
3463                                  EI.UserTE->Scalars.size() ==
3464                                      TE->Scalars.size();
3465                         }) &&
3466                  "All users must be of VF size.");
3467           // Update ordering of the operands with the smaller VF than the given
3468           // one.
3469           reorderReuses(TE->ReuseShuffleIndices, Mask);
3470         }
3471         continue;
3472       }
3473       if (TE->State == TreeEntry::Vectorize &&
3474           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3475               InsertElementInst>(TE->getMainOp()) &&
3476           !TE->isAltShuffle()) {
3477         // Build correct orders for extract{element,value}, loads and
3478         // stores.
3479         reorderOrder(TE->ReorderIndices, Mask);
3480         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3481           TE->reorderOperands(Mask);
3482       } else {
3483         // Reorder the node and its operands.
3484         TE->reorderOperands(Mask);
3485         assert(TE->ReorderIndices.empty() &&
3486                "Expected empty reorder sequence.");
3487         reorderScalars(TE->Scalars, Mask);
3488       }
3489       if (!TE->ReuseShuffleIndices.empty()) {
3490         // Apply reversed order to keep the original ordering of the reused
3491         // elements to avoid extra reorder indices shuffling.
3492         OrdersType CurrentOrder;
3493         reorderOrder(CurrentOrder, MaskOrder);
3494         SmallVector<int> NewReuses;
3495         inversePermutation(CurrentOrder, NewReuses);
3496         addMask(NewReuses, TE->ReuseShuffleIndices);
3497         TE->ReuseShuffleIndices.swap(NewReuses);
3498       }
3499     }
3500   }
3501 }
3502 
3503 bool BoUpSLP::canReorderOperands(
3504     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3505     ArrayRef<TreeEntry *> ReorderableGathers,
3506     SmallVectorImpl<TreeEntry *> &GatherOps) {
3507   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3508     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3509           return OpData.first == I &&
3510                  OpData.second->State == TreeEntry::Vectorize;
3511         }))
3512       continue;
3513     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3514       // Do not reorder if operand node is used by many user nodes.
3515       if (any_of(TE->UserTreeIndices,
3516                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3517         return false;
3518       // Add the node to the list of the ordered nodes with the identity
3519       // order.
3520       Edges.emplace_back(I, TE);
3521       continue;
3522     }
3523     ArrayRef<Value *> VL = UserTE->getOperand(I);
3524     TreeEntry *Gather = nullptr;
3525     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3526           assert(TE->State != TreeEntry::Vectorize &&
3527                  "Only non-vectorized nodes are expected.");
3528           if (TE->isSame(VL)) {
3529             Gather = TE;
3530             return true;
3531           }
3532           return false;
3533         }) > 1)
3534       return false;
3535     if (Gather)
3536       GatherOps.push_back(Gather);
3537   }
3538   return true;
3539 }
3540 
3541 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3542   SetVector<TreeEntry *> OrderedEntries;
3543   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3544   // Find all reorderable leaf nodes with the given VF.
3545   // Currently the are vectorized loads,extracts without alternate operands +
3546   // some gathering of extracts.
3547   SmallVector<TreeEntry *> NonVectorized;
3548   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3549                               &NonVectorized](
3550                                  const std::unique_ptr<TreeEntry> &TE) {
3551     if (TE->State != TreeEntry::Vectorize)
3552       NonVectorized.push_back(TE.get());
3553     if (Optional<OrdersType> CurrentOrder =
3554             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3555       OrderedEntries.insert(TE.get());
3556       if (TE->State != TreeEntry::Vectorize)
3557         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3558     }
3559   });
3560 
3561   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3562   // I.e., if the node has operands, that are reordered, try to make at least
3563   // one operand order in the natural order and reorder others + reorder the
3564   // user node itself.
3565   SmallPtrSet<const TreeEntry *, 4> Visited;
3566   while (!OrderedEntries.empty()) {
3567     // 1. Filter out only reordered nodes.
3568     // 2. If the entry has multiple uses - skip it and jump to the next node.
3569     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3570     SmallVector<TreeEntry *> Filtered;
3571     for (TreeEntry *TE : OrderedEntries) {
3572       if (!(TE->State == TreeEntry::Vectorize ||
3573             (TE->State == TreeEntry::NeedToGather &&
3574              GathersToOrders.count(TE))) ||
3575           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3576           !all_of(drop_begin(TE->UserTreeIndices),
3577                   [TE](const EdgeInfo &EI) {
3578                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3579                   }) ||
3580           !Visited.insert(TE).second) {
3581         Filtered.push_back(TE);
3582         continue;
3583       }
3584       // Build a map between user nodes and their operands order to speedup
3585       // search. The graph currently does not provide this dependency directly.
3586       for (EdgeInfo &EI : TE->UserTreeIndices) {
3587         TreeEntry *UserTE = EI.UserTE;
3588         auto It = Users.find(UserTE);
3589         if (It == Users.end())
3590           It = Users.insert({UserTE, {}}).first;
3591         It->second.emplace_back(EI.EdgeIdx, TE);
3592       }
3593     }
3594     // Erase filtered entries.
3595     for_each(Filtered,
3596              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3597     for (auto &Data : Users) {
3598       // Check that operands are used only in the User node.
3599       SmallVector<TreeEntry *> GatherOps;
3600       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3601                               GatherOps)) {
3602         for_each(Data.second,
3603                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3604                    OrderedEntries.remove(Op.second);
3605                  });
3606         continue;
3607       }
3608       // All operands are reordered and used only in this node - propagate the
3609       // most used order to the user node.
3610       MapVector<OrdersType, unsigned,
3611                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3612           OrdersUses;
3613       // Do the analysis for each tree entry only once, otherwise the order of
3614       // the same node my be considered several times, though might be not
3615       // profitable.
3616       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3617       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3618       for (const auto &Op : Data.second) {
3619         TreeEntry *OpTE = Op.second;
3620         if (!VisitedOps.insert(OpTE).second)
3621           continue;
3622         if (!OpTE->ReuseShuffleIndices.empty() ||
3623             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3624           continue;
3625         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3626           if (OpTE->State == TreeEntry::NeedToGather)
3627             return GathersToOrders.find(OpTE)->second;
3628           return OpTE->ReorderIndices;
3629         }();
3630         unsigned NumOps = count_if(
3631             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3632               return P.second == OpTE;
3633             });
3634         // Stores actually store the mask, not the order, need to invert.
3635         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3636             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3637           SmallVector<int> Mask;
3638           inversePermutation(Order, Mask);
3639           unsigned E = Order.size();
3640           OrdersType CurrentOrder(E, E);
3641           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3642             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3643           });
3644           fixupOrderingIndices(CurrentOrder);
3645           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3646               NumOps;
3647         } else {
3648           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3649         }
3650         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3651         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3652                                             const TreeEntry *TE) {
3653           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3654               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3655               (IgnoreReorder && TE->Idx == 0))
3656             return true;
3657           if (TE->State == TreeEntry::NeedToGather) {
3658             auto It = GathersToOrders.find(TE);
3659             if (It != GathersToOrders.end())
3660               return !It->second.empty();
3661             return true;
3662           }
3663           return false;
3664         };
3665         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3666           TreeEntry *UserTE = EI.UserTE;
3667           if (!VisitedUsers.insert(UserTE).second)
3668             continue;
3669           // May reorder user node if it requires reordering, has reused
3670           // scalars, is an alternate op vectorize node or its op nodes require
3671           // reordering.
3672           if (AllowsReordering(UserTE))
3673             continue;
3674           // Check if users allow reordering.
3675           // Currently look up just 1 level of operands to avoid increase of
3676           // the compile time.
3677           // Profitable to reorder if definitely more operands allow
3678           // reordering rather than those with natural order.
3679           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3680           if (static_cast<unsigned>(count_if(
3681                   Ops, [UserTE, &AllowsReordering](
3682                            const std::pair<unsigned, TreeEntry *> &Op) {
3683                     return AllowsReordering(Op.second) &&
3684                            all_of(Op.second->UserTreeIndices,
3685                                   [UserTE](const EdgeInfo &EI) {
3686                                     return EI.UserTE == UserTE;
3687                                   });
3688                   })) <= Ops.size() / 2)
3689             ++Res.first->second;
3690         }
3691       }
3692       // If no orders - skip current nodes and jump to the next one, if any.
3693       if (OrdersUses.empty()) {
3694         for_each(Data.second,
3695                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3696                    OrderedEntries.remove(Op.second);
3697                  });
3698         continue;
3699       }
3700       // Choose the best order.
3701       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3702       unsigned Cnt = OrdersUses.front().second;
3703       for (const auto &Pair : drop_begin(OrdersUses)) {
3704         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3705           BestOrder = Pair.first;
3706           Cnt = Pair.second;
3707         }
3708       }
3709       // Set order of the user node (reordering of operands and user nodes).
3710       if (BestOrder.empty()) {
3711         for_each(Data.second,
3712                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3713                    OrderedEntries.remove(Op.second);
3714                  });
3715         continue;
3716       }
3717       // Erase operands from OrderedEntries list and adjust their orders.
3718       VisitedOps.clear();
3719       SmallVector<int> Mask;
3720       inversePermutation(BestOrder, Mask);
3721       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3722       unsigned E = BestOrder.size();
3723       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3724         return I < E ? static_cast<int>(I) : UndefMaskElem;
3725       });
3726       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3727         TreeEntry *TE = Op.second;
3728         OrderedEntries.remove(TE);
3729         if (!VisitedOps.insert(TE).second)
3730           continue;
3731         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3732           // Just reorder reuses indices.
3733           reorderReuses(TE->ReuseShuffleIndices, Mask);
3734           continue;
3735         }
3736         // Gathers are processed separately.
3737         if (TE->State != TreeEntry::Vectorize)
3738           continue;
3739         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3740                 TE->ReorderIndices.empty()) &&
3741                "Non-matching sizes of user/operand entries.");
3742         reorderOrder(TE->ReorderIndices, Mask);
3743       }
3744       // For gathers just need to reorder its scalars.
3745       for (TreeEntry *Gather : GatherOps) {
3746         assert(Gather->ReorderIndices.empty() &&
3747                "Unexpected reordering of gathers.");
3748         if (!Gather->ReuseShuffleIndices.empty()) {
3749           // Just reorder reuses indices.
3750           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3751           continue;
3752         }
3753         reorderScalars(Gather->Scalars, Mask);
3754         OrderedEntries.remove(Gather);
3755       }
3756       // Reorder operands of the user node and set the ordering for the user
3757       // node itself.
3758       if (Data.first->State != TreeEntry::Vectorize ||
3759           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3760               Data.first->getMainOp()) ||
3761           Data.first->isAltShuffle())
3762         Data.first->reorderOperands(Mask);
3763       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3764           Data.first->isAltShuffle()) {
3765         reorderScalars(Data.first->Scalars, Mask);
3766         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3767         if (Data.first->ReuseShuffleIndices.empty() &&
3768             !Data.first->ReorderIndices.empty() &&
3769             !Data.first->isAltShuffle()) {
3770           // Insert user node to the list to try to sink reordering deeper in
3771           // the graph.
3772           OrderedEntries.insert(Data.first);
3773         }
3774       } else {
3775         reorderOrder(Data.first->ReorderIndices, Mask);
3776       }
3777     }
3778   }
3779   // If the reordering is unnecessary, just remove the reorder.
3780   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3781       VectorizableTree.front()->ReuseShuffleIndices.empty())
3782     VectorizableTree.front()->ReorderIndices.clear();
3783 }
3784 
3785 void BoUpSLP::buildExternalUses(
3786     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3787   // Collect the values that we need to extract from the tree.
3788   for (auto &TEPtr : VectorizableTree) {
3789     TreeEntry *Entry = TEPtr.get();
3790 
3791     // No need to handle users of gathered values.
3792     if (Entry->State == TreeEntry::NeedToGather)
3793       continue;
3794 
3795     // For each lane:
3796     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3797       Value *Scalar = Entry->Scalars[Lane];
3798       int FoundLane = Entry->findLaneForValue(Scalar);
3799 
3800       // Check if the scalar is externally used as an extra arg.
3801       auto ExtI = ExternallyUsedValues.find(Scalar);
3802       if (ExtI != ExternallyUsedValues.end()) {
3803         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3804                           << Lane << " from " << *Scalar << ".\n");
3805         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3806       }
3807       for (User *U : Scalar->users()) {
3808         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3809 
3810         Instruction *UserInst = dyn_cast<Instruction>(U);
3811         if (!UserInst)
3812           continue;
3813 
3814         if (isDeleted(UserInst))
3815           continue;
3816 
3817         // Skip in-tree scalars that become vectors
3818         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3819           Value *UseScalar = UseEntry->Scalars[0];
3820           // Some in-tree scalars will remain as scalar in vectorized
3821           // instructions. If that is the case, the one in Lane 0 will
3822           // be used.
3823           if (UseScalar != U ||
3824               UseEntry->State == TreeEntry::ScatterVectorize ||
3825               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3826             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3827                               << ".\n");
3828             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3829             continue;
3830           }
3831         }
3832 
3833         // Ignore users in the user ignore list.
3834         if (is_contained(UserIgnoreList, UserInst))
3835           continue;
3836 
3837         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3838                           << Lane << " from " << *Scalar << ".\n");
3839         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3840       }
3841     }
3842   }
3843 }
3844 
3845 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3846                         ArrayRef<Value *> UserIgnoreLst) {
3847   deleteTree();
3848   UserIgnoreList = UserIgnoreLst;
3849   if (!allSameType(Roots))
3850     return;
3851   buildTree_rec(Roots, 0, EdgeInfo());
3852 }
3853 
3854 namespace {
3855 /// Tracks the state we can represent the loads in the given sequence.
3856 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3857 } // anonymous namespace
3858 
3859 /// Checks if the given array of loads can be represented as a vectorized,
3860 /// scatter or just simple gather.
3861 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3862                                     const TargetTransformInfo &TTI,
3863                                     const DataLayout &DL, ScalarEvolution &SE,
3864                                     SmallVectorImpl<unsigned> &Order,
3865                                     SmallVectorImpl<Value *> &PointerOps) {
3866   // Check that a vectorized load would load the same memory as a scalar
3867   // load. For example, we don't want to vectorize loads that are smaller
3868   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3869   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3870   // from such a struct, we read/write packed bits disagreeing with the
3871   // unvectorized version.
3872   Type *ScalarTy = VL0->getType();
3873 
3874   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3875     return LoadsState::Gather;
3876 
3877   // Make sure all loads in the bundle are simple - we can't vectorize
3878   // atomic or volatile loads.
3879   PointerOps.clear();
3880   PointerOps.resize(VL.size());
3881   auto *POIter = PointerOps.begin();
3882   for (Value *V : VL) {
3883     auto *L = cast<LoadInst>(V);
3884     if (!L->isSimple())
3885       return LoadsState::Gather;
3886     *POIter = L->getPointerOperand();
3887     ++POIter;
3888   }
3889 
3890   Order.clear();
3891   // Check the order of pointer operands.
3892   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3893     Value *Ptr0;
3894     Value *PtrN;
3895     if (Order.empty()) {
3896       Ptr0 = PointerOps.front();
3897       PtrN = PointerOps.back();
3898     } else {
3899       Ptr0 = PointerOps[Order.front()];
3900       PtrN = PointerOps[Order.back()];
3901     }
3902     Optional<int> Diff =
3903         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3904     // Check that the sorted loads are consecutive.
3905     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3906       return LoadsState::Vectorize;
3907     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3908     for (Value *V : VL)
3909       CommonAlignment =
3910           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3911     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3912                                 CommonAlignment))
3913       return LoadsState::ScatterVectorize;
3914   }
3915 
3916   return LoadsState::Gather;
3917 }
3918 
3919 /// \return true if the specified list of values has only one instruction that
3920 /// requires scheduling, false otherwise.
3921 #ifndef NDEBUG
3922 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3923   Value *NeedsScheduling = nullptr;
3924   for (Value *V : VL) {
3925     if (doesNotNeedToBeScheduled(V))
3926       continue;
3927     if (!NeedsScheduling) {
3928       NeedsScheduling = V;
3929       continue;
3930     }
3931     return false;
3932   }
3933   return NeedsScheduling;
3934 }
3935 #endif
3936 
3937 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3938                             const EdgeInfo &UserTreeIdx) {
3939   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3940 
3941   SmallVector<int> ReuseShuffleIndicies;
3942   SmallVector<Value *> UniqueValues;
3943   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3944                                 &UserTreeIdx,
3945                                 this](const InstructionsState &S) {
3946     // Check that every instruction appears once in this bundle.
3947     DenseMap<Value *, unsigned> UniquePositions;
3948     for (Value *V : VL) {
3949       if (isConstant(V)) {
3950         ReuseShuffleIndicies.emplace_back(
3951             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3952         UniqueValues.emplace_back(V);
3953         continue;
3954       }
3955       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3956       ReuseShuffleIndicies.emplace_back(Res.first->second);
3957       if (Res.second)
3958         UniqueValues.emplace_back(V);
3959     }
3960     size_t NumUniqueScalarValues = UniqueValues.size();
3961     if (NumUniqueScalarValues == VL.size()) {
3962       ReuseShuffleIndicies.clear();
3963     } else {
3964       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3965       if (NumUniqueScalarValues <= 1 ||
3966           (UniquePositions.size() == 1 && all_of(UniqueValues,
3967                                                  [](Value *V) {
3968                                                    return isa<UndefValue>(V) ||
3969                                                           !isConstant(V);
3970                                                  })) ||
3971           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3972         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3973         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3974         return false;
3975       }
3976       VL = UniqueValues;
3977     }
3978     return true;
3979   };
3980 
3981   InstructionsState S = getSameOpcode(VL);
3982   if (Depth == RecursionMaxDepth) {
3983     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3984     if (TryToFindDuplicates(S))
3985       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3986                    ReuseShuffleIndicies);
3987     return;
3988   }
3989 
3990   // Don't handle scalable vectors
3991   if (S.getOpcode() == Instruction::ExtractElement &&
3992       isa<ScalableVectorType>(
3993           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3994     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3995     if (TryToFindDuplicates(S))
3996       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3997                    ReuseShuffleIndicies);
3998     return;
3999   }
4000 
4001   // Don't handle vectors.
4002   if (S.OpValue->getType()->isVectorTy() &&
4003       !isa<InsertElementInst>(S.OpValue)) {
4004     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4005     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4006     return;
4007   }
4008 
4009   // Avoid attempting to schedule allocas; there are unmodeled dependencies
4010   // for "static" alloca status and for reordering with stacksave calls.
4011   for (Value *V : VL) {
4012     if (isa<AllocaInst>(V)) {
4013       LLVM_DEBUG(dbgs() << "SLP: Gathering due to alloca.\n");
4014       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4015       return;
4016     }
4017   }
4018 
4019   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4020     if (SI->getValueOperand()->getType()->isVectorTy()) {
4021       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4022       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4023       return;
4024     }
4025 
4026   // If all of the operands are identical or constant we have a simple solution.
4027   // If we deal with insert/extract instructions, they all must have constant
4028   // indices, otherwise we should gather them, not try to vectorize.
4029   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4030       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4031        !all_of(VL, isVectorLikeInstWithConstOps))) {
4032     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4033     if (TryToFindDuplicates(S))
4034       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4035                    ReuseShuffleIndicies);
4036     return;
4037   }
4038 
4039   // We now know that this is a vector of instructions of the same type from
4040   // the same block.
4041 
4042   // Don't vectorize ephemeral values.
4043   for (Value *V : VL) {
4044     if (EphValues.count(V)) {
4045       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4046                         << ") is ephemeral.\n");
4047       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4048       return;
4049     }
4050   }
4051 
4052   // Check if this is a duplicate of another entry.
4053   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4054     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4055     if (!E->isSame(VL)) {
4056       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4057       if (TryToFindDuplicates(S))
4058         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4059                      ReuseShuffleIndicies);
4060       return;
4061     }
4062     // Record the reuse of the tree node.  FIXME, currently this is only used to
4063     // properly draw the graph rather than for the actual vectorization.
4064     E->UserTreeIndices.push_back(UserTreeIdx);
4065     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4066                       << ".\n");
4067     return;
4068   }
4069 
4070   // Check that none of the instructions in the bundle are already in the tree.
4071   for (Value *V : VL) {
4072     auto *I = dyn_cast<Instruction>(V);
4073     if (!I)
4074       continue;
4075     if (getTreeEntry(I)) {
4076       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4077                         << ") is already in tree.\n");
4078       if (TryToFindDuplicates(S))
4079         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4080                      ReuseShuffleIndicies);
4081       return;
4082     }
4083   }
4084 
4085   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4086   for (Value *V : VL) {
4087     if (is_contained(UserIgnoreList, V)) {
4088       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4089       if (TryToFindDuplicates(S))
4090         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4091                      ReuseShuffleIndicies);
4092       return;
4093     }
4094   }
4095 
4096   // Check that all of the users of the scalars that we want to vectorize are
4097   // schedulable.
4098   auto *VL0 = cast<Instruction>(S.OpValue);
4099   BasicBlock *BB = VL0->getParent();
4100 
4101   if (!DT->isReachableFromEntry(BB)) {
4102     // Don't go into unreachable blocks. They may contain instructions with
4103     // dependency cycles which confuse the final scheduling.
4104     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4105     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4106     return;
4107   }
4108 
4109   // Check that every instruction appears once in this bundle.
4110   if (!TryToFindDuplicates(S))
4111     return;
4112 
4113   auto &BSRef = BlocksSchedules[BB];
4114   if (!BSRef)
4115     BSRef = std::make_unique<BlockScheduling>(BB);
4116 
4117   BlockScheduling &BS = *BSRef.get();
4118 
4119   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4120 #ifdef EXPENSIVE_CHECKS
4121   // Make sure we didn't break any internal invariants
4122   BS.verify();
4123 #endif
4124   if (!Bundle) {
4125     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4126     assert((!BS.getScheduleData(VL0) ||
4127             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4128            "tryScheduleBundle should cancelScheduling on failure");
4129     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4130                  ReuseShuffleIndicies);
4131     return;
4132   }
4133   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4134 
4135   unsigned ShuffleOrOp = S.isAltShuffle() ?
4136                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4137   switch (ShuffleOrOp) {
4138     case Instruction::PHI: {
4139       auto *PH = cast<PHINode>(VL0);
4140 
4141       // Check for terminator values (e.g. invoke).
4142       for (Value *V : VL)
4143         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4144           Instruction *Term = dyn_cast<Instruction>(Incoming);
4145           if (Term && Term->isTerminator()) {
4146             LLVM_DEBUG(dbgs()
4147                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4148             BS.cancelScheduling(VL, VL0);
4149             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4150                          ReuseShuffleIndicies);
4151             return;
4152           }
4153         }
4154 
4155       TreeEntry *TE =
4156           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4157       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4158 
4159       // Keeps the reordered operands to avoid code duplication.
4160       SmallVector<ValueList, 2> OperandsVec;
4161       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4162         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4163           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4164           TE->setOperand(I, Operands);
4165           OperandsVec.push_back(Operands);
4166           continue;
4167         }
4168         ValueList Operands;
4169         // Prepare the operand vector.
4170         for (Value *V : VL)
4171           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4172               PH->getIncomingBlock(I)));
4173         TE->setOperand(I, Operands);
4174         OperandsVec.push_back(Operands);
4175       }
4176       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4177         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4178       return;
4179     }
4180     case Instruction::ExtractValue:
4181     case Instruction::ExtractElement: {
4182       OrdersType CurrentOrder;
4183       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4184       if (Reuse) {
4185         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4186         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4187                      ReuseShuffleIndicies);
4188         // This is a special case, as it does not gather, but at the same time
4189         // we are not extending buildTree_rec() towards the operands.
4190         ValueList Op0;
4191         Op0.assign(VL.size(), VL0->getOperand(0));
4192         VectorizableTree.back()->setOperand(0, Op0);
4193         return;
4194       }
4195       if (!CurrentOrder.empty()) {
4196         LLVM_DEBUG({
4197           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4198                     "with order";
4199           for (unsigned Idx : CurrentOrder)
4200             dbgs() << " " << Idx;
4201           dbgs() << "\n";
4202         });
4203         fixupOrderingIndices(CurrentOrder);
4204         // Insert new order with initial value 0, if it does not exist,
4205         // otherwise return the iterator to the existing one.
4206         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4207                      ReuseShuffleIndicies, CurrentOrder);
4208         // This is a special case, as it does not gather, but at the same time
4209         // we are not extending buildTree_rec() towards the operands.
4210         ValueList Op0;
4211         Op0.assign(VL.size(), VL0->getOperand(0));
4212         VectorizableTree.back()->setOperand(0, Op0);
4213         return;
4214       }
4215       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4216       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4217                    ReuseShuffleIndicies);
4218       BS.cancelScheduling(VL, VL0);
4219       return;
4220     }
4221     case Instruction::InsertElement: {
4222       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4223 
4224       // Check that we have a buildvector and not a shuffle of 2 or more
4225       // different vectors.
4226       ValueSet SourceVectors;
4227       for (Value *V : VL) {
4228         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4229         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4230       }
4231 
4232       if (count_if(VL, [&SourceVectors](Value *V) {
4233             return !SourceVectors.contains(V);
4234           }) >= 2) {
4235         // Found 2nd source vector - cancel.
4236         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4237                              "different source vectors.\n");
4238         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4239         BS.cancelScheduling(VL, VL0);
4240         return;
4241       }
4242 
4243       auto OrdCompare = [](const std::pair<int, int> &P1,
4244                            const std::pair<int, int> &P2) {
4245         return P1.first > P2.first;
4246       };
4247       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4248                     decltype(OrdCompare)>
4249           Indices(OrdCompare);
4250       for (int I = 0, E = VL.size(); I < E; ++I) {
4251         unsigned Idx = *getInsertIndex(VL[I]);
4252         Indices.emplace(Idx, I);
4253       }
4254       OrdersType CurrentOrder(VL.size(), VL.size());
4255       bool IsIdentity = true;
4256       for (int I = 0, E = VL.size(); I < E; ++I) {
4257         CurrentOrder[Indices.top().second] = I;
4258         IsIdentity &= Indices.top().second == I;
4259         Indices.pop();
4260       }
4261       if (IsIdentity)
4262         CurrentOrder.clear();
4263       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4264                                    None, CurrentOrder);
4265       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4266 
4267       constexpr int NumOps = 2;
4268       ValueList VectorOperands[NumOps];
4269       for (int I = 0; I < NumOps; ++I) {
4270         for (Value *V : VL)
4271           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4272 
4273         TE->setOperand(I, VectorOperands[I]);
4274       }
4275       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4276       return;
4277     }
4278     case Instruction::Load: {
4279       // Check that a vectorized load would load the same memory as a scalar
4280       // load. For example, we don't want to vectorize loads that are smaller
4281       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4282       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4283       // from such a struct, we read/write packed bits disagreeing with the
4284       // unvectorized version.
4285       SmallVector<Value *> PointerOps;
4286       OrdersType CurrentOrder;
4287       TreeEntry *TE = nullptr;
4288       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4289                                 PointerOps)) {
4290       case LoadsState::Vectorize:
4291         if (CurrentOrder.empty()) {
4292           // Original loads are consecutive and does not require reordering.
4293           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4294                             ReuseShuffleIndicies);
4295           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4296         } else {
4297           fixupOrderingIndices(CurrentOrder);
4298           // Need to reorder.
4299           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4300                             ReuseShuffleIndicies, CurrentOrder);
4301           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4302         }
4303         TE->setOperandsInOrder();
4304         break;
4305       case LoadsState::ScatterVectorize:
4306         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4307         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4308                           UserTreeIdx, ReuseShuffleIndicies);
4309         TE->setOperandsInOrder();
4310         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4311         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4312         break;
4313       case LoadsState::Gather:
4314         BS.cancelScheduling(VL, VL0);
4315         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4316                      ReuseShuffleIndicies);
4317 #ifndef NDEBUG
4318         Type *ScalarTy = VL0->getType();
4319         if (DL->getTypeSizeInBits(ScalarTy) !=
4320             DL->getTypeAllocSizeInBits(ScalarTy))
4321           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4322         else if (any_of(VL, [](Value *V) {
4323                    return !cast<LoadInst>(V)->isSimple();
4324                  }))
4325           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4326         else
4327           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4328 #endif // NDEBUG
4329         break;
4330       }
4331       return;
4332     }
4333     case Instruction::ZExt:
4334     case Instruction::SExt:
4335     case Instruction::FPToUI:
4336     case Instruction::FPToSI:
4337     case Instruction::FPExt:
4338     case Instruction::PtrToInt:
4339     case Instruction::IntToPtr:
4340     case Instruction::SIToFP:
4341     case Instruction::UIToFP:
4342     case Instruction::Trunc:
4343     case Instruction::FPTrunc:
4344     case Instruction::BitCast: {
4345       Type *SrcTy = VL0->getOperand(0)->getType();
4346       for (Value *V : VL) {
4347         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4348         if (Ty != SrcTy || !isValidElementType(Ty)) {
4349           BS.cancelScheduling(VL, VL0);
4350           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4351                        ReuseShuffleIndicies);
4352           LLVM_DEBUG(dbgs()
4353                      << "SLP: Gathering casts with different src types.\n");
4354           return;
4355         }
4356       }
4357       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4358                                    ReuseShuffleIndicies);
4359       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4360 
4361       TE->setOperandsInOrder();
4362       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4363         ValueList Operands;
4364         // Prepare the operand vector.
4365         for (Value *V : VL)
4366           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4367 
4368         buildTree_rec(Operands, Depth + 1, {TE, i});
4369       }
4370       return;
4371     }
4372     case Instruction::ICmp:
4373     case Instruction::FCmp: {
4374       // Check that all of the compares have the same predicate.
4375       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4376       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4377       Type *ComparedTy = VL0->getOperand(0)->getType();
4378       for (Value *V : VL) {
4379         CmpInst *Cmp = cast<CmpInst>(V);
4380         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4381             Cmp->getOperand(0)->getType() != ComparedTy) {
4382           BS.cancelScheduling(VL, VL0);
4383           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4384                        ReuseShuffleIndicies);
4385           LLVM_DEBUG(dbgs()
4386                      << "SLP: Gathering cmp with different predicate.\n");
4387           return;
4388         }
4389       }
4390 
4391       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4392                                    ReuseShuffleIndicies);
4393       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4394 
4395       ValueList Left, Right;
4396       if (cast<CmpInst>(VL0)->isCommutative()) {
4397         // Commutative predicate - collect + sort operands of the instructions
4398         // so that each side is more likely to have the same opcode.
4399         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4400         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4401       } else {
4402         // Collect operands - commute if it uses the swapped predicate.
4403         for (Value *V : VL) {
4404           auto *Cmp = cast<CmpInst>(V);
4405           Value *LHS = Cmp->getOperand(0);
4406           Value *RHS = Cmp->getOperand(1);
4407           if (Cmp->getPredicate() != P0)
4408             std::swap(LHS, RHS);
4409           Left.push_back(LHS);
4410           Right.push_back(RHS);
4411         }
4412       }
4413       TE->setOperand(0, Left);
4414       TE->setOperand(1, Right);
4415       buildTree_rec(Left, Depth + 1, {TE, 0});
4416       buildTree_rec(Right, Depth + 1, {TE, 1});
4417       return;
4418     }
4419     case Instruction::Select:
4420     case Instruction::FNeg:
4421     case Instruction::Add:
4422     case Instruction::FAdd:
4423     case Instruction::Sub:
4424     case Instruction::FSub:
4425     case Instruction::Mul:
4426     case Instruction::FMul:
4427     case Instruction::UDiv:
4428     case Instruction::SDiv:
4429     case Instruction::FDiv:
4430     case Instruction::URem:
4431     case Instruction::SRem:
4432     case Instruction::FRem:
4433     case Instruction::Shl:
4434     case Instruction::LShr:
4435     case Instruction::AShr:
4436     case Instruction::And:
4437     case Instruction::Or:
4438     case Instruction::Xor: {
4439       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4440                                    ReuseShuffleIndicies);
4441       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4442 
4443       // Sort operands of the instructions so that each side is more likely to
4444       // have the same opcode.
4445       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4446         ValueList Left, Right;
4447         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4448         TE->setOperand(0, Left);
4449         TE->setOperand(1, Right);
4450         buildTree_rec(Left, Depth + 1, {TE, 0});
4451         buildTree_rec(Right, Depth + 1, {TE, 1});
4452         return;
4453       }
4454 
4455       TE->setOperandsInOrder();
4456       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4457         ValueList Operands;
4458         // Prepare the operand vector.
4459         for (Value *V : VL)
4460           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4461 
4462         buildTree_rec(Operands, Depth + 1, {TE, i});
4463       }
4464       return;
4465     }
4466     case Instruction::GetElementPtr: {
4467       // We don't combine GEPs with complicated (nested) indexing.
4468       for (Value *V : VL) {
4469         if (cast<Instruction>(V)->getNumOperands() != 2) {
4470           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4471           BS.cancelScheduling(VL, VL0);
4472           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4473                        ReuseShuffleIndicies);
4474           return;
4475         }
4476       }
4477 
4478       // We can't combine several GEPs into one vector if they operate on
4479       // different types.
4480       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4481       for (Value *V : VL) {
4482         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4483         if (Ty0 != CurTy) {
4484           LLVM_DEBUG(dbgs()
4485                      << "SLP: not-vectorizable GEP (different types).\n");
4486           BS.cancelScheduling(VL, VL0);
4487           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4488                        ReuseShuffleIndicies);
4489           return;
4490         }
4491       }
4492 
4493       // We don't combine GEPs with non-constant indexes.
4494       Type *Ty1 = VL0->getOperand(1)->getType();
4495       for (Value *V : VL) {
4496         auto Op = cast<Instruction>(V)->getOperand(1);
4497         if (!isa<ConstantInt>(Op) ||
4498             (Op->getType() != Ty1 &&
4499              Op->getType()->getScalarSizeInBits() >
4500                  DL->getIndexSizeInBits(
4501                      V->getType()->getPointerAddressSpace()))) {
4502           LLVM_DEBUG(dbgs()
4503                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4504           BS.cancelScheduling(VL, VL0);
4505           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4506                        ReuseShuffleIndicies);
4507           return;
4508         }
4509       }
4510 
4511       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4512                                    ReuseShuffleIndicies);
4513       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4514       SmallVector<ValueList, 2> Operands(2);
4515       // Prepare the operand vector for pointer operands.
4516       for (Value *V : VL)
4517         Operands.front().push_back(
4518             cast<GetElementPtrInst>(V)->getPointerOperand());
4519       TE->setOperand(0, Operands.front());
4520       // Need to cast all indices to the same type before vectorization to
4521       // avoid crash.
4522       // Required to be able to find correct matches between different gather
4523       // nodes and reuse the vectorized values rather than trying to gather them
4524       // again.
4525       int IndexIdx = 1;
4526       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4527       Type *Ty = all_of(VL,
4528                         [VL0Ty, IndexIdx](Value *V) {
4529                           return VL0Ty == cast<GetElementPtrInst>(V)
4530                                               ->getOperand(IndexIdx)
4531                                               ->getType();
4532                         })
4533                      ? VL0Ty
4534                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4535                                             ->getPointerOperandType()
4536                                             ->getScalarType());
4537       // Prepare the operand vector.
4538       for (Value *V : VL) {
4539         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4540         auto *CI = cast<ConstantInt>(Op);
4541         Operands.back().push_back(ConstantExpr::getIntegerCast(
4542             CI, Ty, CI->getValue().isSignBitSet()));
4543       }
4544       TE->setOperand(IndexIdx, Operands.back());
4545 
4546       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4547         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4548       return;
4549     }
4550     case Instruction::Store: {
4551       // Check if the stores are consecutive or if we need to swizzle them.
4552       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4553       // Avoid types that are padded when being allocated as scalars, while
4554       // being packed together in a vector (such as i1).
4555       if (DL->getTypeSizeInBits(ScalarTy) !=
4556           DL->getTypeAllocSizeInBits(ScalarTy)) {
4557         BS.cancelScheduling(VL, VL0);
4558         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4559                      ReuseShuffleIndicies);
4560         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4561         return;
4562       }
4563       // Make sure all stores in the bundle are simple - we can't vectorize
4564       // atomic or volatile stores.
4565       SmallVector<Value *, 4> PointerOps(VL.size());
4566       ValueList Operands(VL.size());
4567       auto POIter = PointerOps.begin();
4568       auto OIter = Operands.begin();
4569       for (Value *V : VL) {
4570         auto *SI = cast<StoreInst>(V);
4571         if (!SI->isSimple()) {
4572           BS.cancelScheduling(VL, VL0);
4573           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4574                        ReuseShuffleIndicies);
4575           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4576           return;
4577         }
4578         *POIter = SI->getPointerOperand();
4579         *OIter = SI->getValueOperand();
4580         ++POIter;
4581         ++OIter;
4582       }
4583 
4584       OrdersType CurrentOrder;
4585       // Check the order of pointer operands.
4586       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4587         Value *Ptr0;
4588         Value *PtrN;
4589         if (CurrentOrder.empty()) {
4590           Ptr0 = PointerOps.front();
4591           PtrN = PointerOps.back();
4592         } else {
4593           Ptr0 = PointerOps[CurrentOrder.front()];
4594           PtrN = PointerOps[CurrentOrder.back()];
4595         }
4596         Optional<int> Dist =
4597             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4598         // Check that the sorted pointer operands are consecutive.
4599         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4600           if (CurrentOrder.empty()) {
4601             // Original stores are consecutive and does not require reordering.
4602             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4603                                          UserTreeIdx, ReuseShuffleIndicies);
4604             TE->setOperandsInOrder();
4605             buildTree_rec(Operands, Depth + 1, {TE, 0});
4606             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4607           } else {
4608             fixupOrderingIndices(CurrentOrder);
4609             TreeEntry *TE =
4610                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4611                              ReuseShuffleIndicies, CurrentOrder);
4612             TE->setOperandsInOrder();
4613             buildTree_rec(Operands, Depth + 1, {TE, 0});
4614             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4615           }
4616           return;
4617         }
4618       }
4619 
4620       BS.cancelScheduling(VL, VL0);
4621       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4622                    ReuseShuffleIndicies);
4623       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4624       return;
4625     }
4626     case Instruction::Call: {
4627       // Check if the calls are all to the same vectorizable intrinsic or
4628       // library function.
4629       CallInst *CI = cast<CallInst>(VL0);
4630       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4631 
4632       VFShape Shape = VFShape::get(
4633           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4634           false /*HasGlobalPred*/);
4635       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4636 
4637       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4638         BS.cancelScheduling(VL, VL0);
4639         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4640                      ReuseShuffleIndicies);
4641         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4642         return;
4643       }
4644       Function *F = CI->getCalledFunction();
4645       unsigned NumArgs = CI->arg_size();
4646       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4647       for (unsigned j = 0; j != NumArgs; ++j)
4648         if (hasVectorInstrinsicScalarOpd(ID, j))
4649           ScalarArgs[j] = CI->getArgOperand(j);
4650       for (Value *V : VL) {
4651         CallInst *CI2 = dyn_cast<CallInst>(V);
4652         if (!CI2 || CI2->getCalledFunction() != F ||
4653             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4654             (VecFunc &&
4655              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4656             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4657           BS.cancelScheduling(VL, VL0);
4658           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4659                        ReuseShuffleIndicies);
4660           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4661                             << "\n");
4662           return;
4663         }
4664         // Some intrinsics have scalar arguments and should be same in order for
4665         // them to be vectorized.
4666         for (unsigned j = 0; j != NumArgs; ++j) {
4667           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4668             Value *A1J = CI2->getArgOperand(j);
4669             if (ScalarArgs[j] != A1J) {
4670               BS.cancelScheduling(VL, VL0);
4671               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4672                            ReuseShuffleIndicies);
4673               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4674                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4675                                 << "\n");
4676               return;
4677             }
4678           }
4679         }
4680         // Verify that the bundle operands are identical between the two calls.
4681         if (CI->hasOperandBundles() &&
4682             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4683                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4684                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4685           BS.cancelScheduling(VL, VL0);
4686           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4687                        ReuseShuffleIndicies);
4688           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4689                             << *CI << "!=" << *V << '\n');
4690           return;
4691         }
4692       }
4693 
4694       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4695                                    ReuseShuffleIndicies);
4696       TE->setOperandsInOrder();
4697       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4698         // For scalar operands no need to to create an entry since no need to
4699         // vectorize it.
4700         if (hasVectorInstrinsicScalarOpd(ID, i))
4701           continue;
4702         ValueList Operands;
4703         // Prepare the operand vector.
4704         for (Value *V : VL) {
4705           auto *CI2 = cast<CallInst>(V);
4706           Operands.push_back(CI2->getArgOperand(i));
4707         }
4708         buildTree_rec(Operands, Depth + 1, {TE, i});
4709       }
4710       return;
4711     }
4712     case Instruction::ShuffleVector: {
4713       // If this is not an alternate sequence of opcode like add-sub
4714       // then do not vectorize this instruction.
4715       if (!S.isAltShuffle()) {
4716         BS.cancelScheduling(VL, VL0);
4717         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4718                      ReuseShuffleIndicies);
4719         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4720         return;
4721       }
4722       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4723                                    ReuseShuffleIndicies);
4724       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4725 
4726       // Reorder operands if reordering would enable vectorization.
4727       auto *CI = dyn_cast<CmpInst>(VL0);
4728       if (isa<BinaryOperator>(VL0) || CI) {
4729         ValueList Left, Right;
4730         if (!CI || all_of(VL, [](Value *V) {
4731               return cast<CmpInst>(V)->isCommutative();
4732             })) {
4733           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4734         } else {
4735           CmpInst::Predicate P0 = CI->getPredicate();
4736           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4737           assert(P0 != AltP0 &&
4738                  "Expected different main/alternate predicates.");
4739           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4740           Value *BaseOp0 = VL0->getOperand(0);
4741           Value *BaseOp1 = VL0->getOperand(1);
4742           // Collect operands - commute if it uses the swapped predicate or
4743           // alternate operation.
4744           for (Value *V : VL) {
4745             auto *Cmp = cast<CmpInst>(V);
4746             Value *LHS = Cmp->getOperand(0);
4747             Value *RHS = Cmp->getOperand(1);
4748             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4749             if (P0 == AltP0Swapped) {
4750               if (CI != Cmp && S.AltOp != Cmp &&
4751                   ((P0 == CurrentPred &&
4752                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4753                    (AltP0 == CurrentPred &&
4754                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4755                 std::swap(LHS, RHS);
4756             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4757               std::swap(LHS, RHS);
4758             }
4759             Left.push_back(LHS);
4760             Right.push_back(RHS);
4761           }
4762         }
4763         TE->setOperand(0, Left);
4764         TE->setOperand(1, Right);
4765         buildTree_rec(Left, Depth + 1, {TE, 0});
4766         buildTree_rec(Right, Depth + 1, {TE, 1});
4767         return;
4768       }
4769 
4770       TE->setOperandsInOrder();
4771       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4772         ValueList Operands;
4773         // Prepare the operand vector.
4774         for (Value *V : VL)
4775           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4776 
4777         buildTree_rec(Operands, Depth + 1, {TE, i});
4778       }
4779       return;
4780     }
4781     default:
4782       BS.cancelScheduling(VL, VL0);
4783       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4784                    ReuseShuffleIndicies);
4785       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4786       return;
4787   }
4788 }
4789 
4790 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4791   unsigned N = 1;
4792   Type *EltTy = T;
4793 
4794   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4795          isa<VectorType>(EltTy)) {
4796     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4797       // Check that struct is homogeneous.
4798       for (const auto *Ty : ST->elements())
4799         if (Ty != *ST->element_begin())
4800           return 0;
4801       N *= ST->getNumElements();
4802       EltTy = *ST->element_begin();
4803     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4804       N *= AT->getNumElements();
4805       EltTy = AT->getElementType();
4806     } else {
4807       auto *VT = cast<FixedVectorType>(EltTy);
4808       N *= VT->getNumElements();
4809       EltTy = VT->getElementType();
4810     }
4811   }
4812 
4813   if (!isValidElementType(EltTy))
4814     return 0;
4815   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4816   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4817     return 0;
4818   return N;
4819 }
4820 
4821 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4822                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4823   const auto *It = find_if(VL, [](Value *V) {
4824     return isa<ExtractElementInst, ExtractValueInst>(V);
4825   });
4826   assert(It != VL.end() && "Expected at least one extract instruction.");
4827   auto *E0 = cast<Instruction>(*It);
4828   assert(all_of(VL,
4829                 [](Value *V) {
4830                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4831                       V);
4832                 }) &&
4833          "Invalid opcode");
4834   // Check if all of the extracts come from the same vector and from the
4835   // correct offset.
4836   Value *Vec = E0->getOperand(0);
4837 
4838   CurrentOrder.clear();
4839 
4840   // We have to extract from a vector/aggregate with the same number of elements.
4841   unsigned NElts;
4842   if (E0->getOpcode() == Instruction::ExtractValue) {
4843     const DataLayout &DL = E0->getModule()->getDataLayout();
4844     NElts = canMapToVector(Vec->getType(), DL);
4845     if (!NElts)
4846       return false;
4847     // Check if load can be rewritten as load of vector.
4848     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4849     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4850       return false;
4851   } else {
4852     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4853   }
4854 
4855   if (NElts != VL.size())
4856     return false;
4857 
4858   // Check that all of the indices extract from the correct offset.
4859   bool ShouldKeepOrder = true;
4860   unsigned E = VL.size();
4861   // Assign to all items the initial value E + 1 so we can check if the extract
4862   // instruction index was used already.
4863   // Also, later we can check that all the indices are used and we have a
4864   // consecutive access in the extract instructions, by checking that no
4865   // element of CurrentOrder still has value E + 1.
4866   CurrentOrder.assign(E, E);
4867   unsigned I = 0;
4868   for (; I < E; ++I) {
4869     auto *Inst = dyn_cast<Instruction>(VL[I]);
4870     if (!Inst)
4871       continue;
4872     if (Inst->getOperand(0) != Vec)
4873       break;
4874     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4875       if (isa<UndefValue>(EE->getIndexOperand()))
4876         continue;
4877     Optional<unsigned> Idx = getExtractIndex(Inst);
4878     if (!Idx)
4879       break;
4880     const unsigned ExtIdx = *Idx;
4881     if (ExtIdx != I) {
4882       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4883         break;
4884       ShouldKeepOrder = false;
4885       CurrentOrder[ExtIdx] = I;
4886     } else {
4887       if (CurrentOrder[I] != E)
4888         break;
4889       CurrentOrder[I] = I;
4890     }
4891   }
4892   if (I < E) {
4893     CurrentOrder.clear();
4894     return false;
4895   }
4896   if (ShouldKeepOrder)
4897     CurrentOrder.clear();
4898 
4899   return ShouldKeepOrder;
4900 }
4901 
4902 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4903                                     ArrayRef<Value *> VectorizedVals) const {
4904   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4905          all_of(I->users(), [this](User *U) {
4906            return ScalarToTreeEntry.count(U) > 0 ||
4907                   isVectorLikeInstWithConstOps(U) ||
4908                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4909          });
4910 }
4911 
4912 static std::pair<InstructionCost, InstructionCost>
4913 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4914                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4915   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4916 
4917   // Calculate the cost of the scalar and vector calls.
4918   SmallVector<Type *, 4> VecTys;
4919   for (Use &Arg : CI->args())
4920     VecTys.push_back(
4921         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4922   FastMathFlags FMF;
4923   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4924     FMF = FPCI->getFastMathFlags();
4925   SmallVector<const Value *> Arguments(CI->args());
4926   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4927                                     dyn_cast<IntrinsicInst>(CI));
4928   auto IntrinsicCost =
4929     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4930 
4931   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4932                                      VecTy->getNumElements())),
4933                             false /*HasGlobalPred*/);
4934   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4935   auto LibCost = IntrinsicCost;
4936   if (!CI->isNoBuiltin() && VecFunc) {
4937     // Calculate the cost of the vector library call.
4938     // If the corresponding vector call is cheaper, return its cost.
4939     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4940                                     TTI::TCK_RecipThroughput);
4941   }
4942   return {IntrinsicCost, LibCost};
4943 }
4944 
4945 /// Compute the cost of creating a vector of type \p VecTy containing the
4946 /// extracted values from \p VL.
4947 static InstructionCost
4948 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4949                    TargetTransformInfo::ShuffleKind ShuffleKind,
4950                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4951   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4952 
4953   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4954       VecTy->getNumElements() < NumOfParts)
4955     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4956 
4957   bool AllConsecutive = true;
4958   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4959   unsigned Idx = -1;
4960   InstructionCost Cost = 0;
4961 
4962   // Process extracts in blocks of EltsPerVector to check if the source vector
4963   // operand can be re-used directly. If not, add the cost of creating a shuffle
4964   // to extract the values into a vector register.
4965   for (auto *V : VL) {
4966     ++Idx;
4967 
4968     // Need to exclude undefs from analysis.
4969     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4970       continue;
4971 
4972     // Reached the start of a new vector registers.
4973     if (Idx % EltsPerVector == 0) {
4974       AllConsecutive = true;
4975       continue;
4976     }
4977 
4978     // Check all extracts for a vector register on the target directly
4979     // extract values in order.
4980     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4981     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4982       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4983       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4984                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4985     }
4986 
4987     if (AllConsecutive)
4988       continue;
4989 
4990     // Skip all indices, except for the last index per vector block.
4991     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4992       continue;
4993 
4994     // If we have a series of extracts which are not consecutive and hence
4995     // cannot re-use the source vector register directly, compute the shuffle
4996     // cost to extract the a vector with EltsPerVector elements.
4997     Cost += TTI.getShuffleCost(
4998         TargetTransformInfo::SK_PermuteSingleSrc,
4999         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5000   }
5001   return Cost;
5002 }
5003 
5004 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5005 /// operations operands.
5006 static void
5007 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5008                       ArrayRef<int> ReusesIndices,
5009                       const function_ref<bool(Instruction *)> IsAltOp,
5010                       SmallVectorImpl<int> &Mask,
5011                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5012                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5013   unsigned Sz = VL.size();
5014   Mask.assign(Sz, UndefMaskElem);
5015   SmallVector<int> OrderMask;
5016   if (!ReorderIndices.empty())
5017     inversePermutation(ReorderIndices, OrderMask);
5018   for (unsigned I = 0; I < Sz; ++I) {
5019     unsigned Idx = I;
5020     if (!ReorderIndices.empty())
5021       Idx = OrderMask[I];
5022     auto *OpInst = cast<Instruction>(VL[Idx]);
5023     if (IsAltOp(OpInst)) {
5024       Mask[I] = Sz + Idx;
5025       if (AltScalars)
5026         AltScalars->push_back(OpInst);
5027     } else {
5028       Mask[I] = Idx;
5029       if (OpScalars)
5030         OpScalars->push_back(OpInst);
5031     }
5032   }
5033   if (!ReusesIndices.empty()) {
5034     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5035     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5036       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5037     });
5038     Mask.swap(NewMask);
5039   }
5040 }
5041 
5042 /// Checks if the specified instruction \p I is an alternate operation for the
5043 /// given \p MainOp and \p AltOp instructions.
5044 static bool isAlternateInstruction(const Instruction *I,
5045                                    const Instruction *MainOp,
5046                                    const Instruction *AltOp) {
5047   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5048     auto *AltCI0 = cast<CmpInst>(AltOp);
5049     auto *CI = cast<CmpInst>(I);
5050     CmpInst::Predicate P0 = CI0->getPredicate();
5051     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5052     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5053     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5054     CmpInst::Predicate CurrentPred = CI->getPredicate();
5055     if (P0 == AltP0Swapped)
5056       return I == AltCI0 ||
5057              (I != MainOp &&
5058               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5059                                    CI->getOperand(0), CI->getOperand(1)));
5060     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5061   }
5062   return I->getOpcode() == AltOp->getOpcode();
5063 }
5064 
5065 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5066                                       ArrayRef<Value *> VectorizedVals) {
5067   ArrayRef<Value*> VL = E->Scalars;
5068 
5069   Type *ScalarTy = VL[0]->getType();
5070   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5071     ScalarTy = SI->getValueOperand()->getType();
5072   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5073     ScalarTy = CI->getOperand(0)->getType();
5074   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5075     ScalarTy = IE->getOperand(1)->getType();
5076   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5077   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5078 
5079   // If we have computed a smaller type for the expression, update VecTy so
5080   // that the costs will be accurate.
5081   if (MinBWs.count(VL[0]))
5082     VecTy = FixedVectorType::get(
5083         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5084   unsigned EntryVF = E->getVectorFactor();
5085   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5086 
5087   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5088   // FIXME: it tries to fix a problem with MSVC buildbots.
5089   TargetTransformInfo &TTIRef = *TTI;
5090   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5091                                VectorizedVals, E](InstructionCost &Cost) {
5092     DenseMap<Value *, int> ExtractVectorsTys;
5093     SmallPtrSet<Value *, 4> CheckedExtracts;
5094     for (auto *V : VL) {
5095       if (isa<UndefValue>(V))
5096         continue;
5097       // If all users of instruction are going to be vectorized and this
5098       // instruction itself is not going to be vectorized, consider this
5099       // instruction as dead and remove its cost from the final cost of the
5100       // vectorized tree.
5101       // Also, avoid adjusting the cost for extractelements with multiple uses
5102       // in different graph entries.
5103       const TreeEntry *VE = getTreeEntry(V);
5104       if (!CheckedExtracts.insert(V).second ||
5105           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5106           (VE && VE != E))
5107         continue;
5108       auto *EE = cast<ExtractElementInst>(V);
5109       Optional<unsigned> EEIdx = getExtractIndex(EE);
5110       if (!EEIdx)
5111         continue;
5112       unsigned Idx = *EEIdx;
5113       if (TTIRef.getNumberOfParts(VecTy) !=
5114           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5115         auto It =
5116             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5117         It->getSecond() = std::min<int>(It->second, Idx);
5118       }
5119       // Take credit for instruction that will become dead.
5120       if (EE->hasOneUse()) {
5121         Instruction *Ext = EE->user_back();
5122         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5123             all_of(Ext->users(),
5124                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5125           // Use getExtractWithExtendCost() to calculate the cost of
5126           // extractelement/ext pair.
5127           Cost -=
5128               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5129                                               EE->getVectorOperandType(), Idx);
5130           // Add back the cost of s|zext which is subtracted separately.
5131           Cost += TTIRef.getCastInstrCost(
5132               Ext->getOpcode(), Ext->getType(), EE->getType(),
5133               TTI::getCastContextHint(Ext), CostKind, Ext);
5134           continue;
5135         }
5136       }
5137       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5138                                         EE->getVectorOperandType(), Idx);
5139     }
5140     // Add a cost for subvector extracts/inserts if required.
5141     for (const auto &Data : ExtractVectorsTys) {
5142       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5143       unsigned NumElts = VecTy->getNumElements();
5144       if (Data.second % NumElts == 0)
5145         continue;
5146       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5147         unsigned Idx = (Data.second / NumElts) * NumElts;
5148         unsigned EENumElts = EEVTy->getNumElements();
5149         if (Idx + NumElts <= EENumElts) {
5150           Cost +=
5151               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5152                                     EEVTy, None, Idx, VecTy);
5153         } else {
5154           // Need to round up the subvector type vectorization factor to avoid a
5155           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5156           // <= EENumElts.
5157           auto *SubVT =
5158               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5159           Cost +=
5160               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5161                                     EEVTy, None, Idx, SubVT);
5162         }
5163       } else {
5164         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5165                                       VecTy, None, 0, EEVTy);
5166       }
5167     }
5168   };
5169   if (E->State == TreeEntry::NeedToGather) {
5170     if (allConstant(VL))
5171       return 0;
5172     if (isa<InsertElementInst>(VL[0]))
5173       return InstructionCost::getInvalid();
5174     SmallVector<int> Mask;
5175     SmallVector<const TreeEntry *> Entries;
5176     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5177         isGatherShuffledEntry(E, Mask, Entries);
5178     if (Shuffle.hasValue()) {
5179       InstructionCost GatherCost = 0;
5180       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5181         // Perfect match in the graph, will reuse the previously vectorized
5182         // node. Cost is 0.
5183         LLVM_DEBUG(
5184             dbgs()
5185             << "SLP: perfect diamond match for gather bundle that starts with "
5186             << *VL.front() << ".\n");
5187         if (NeedToShuffleReuses)
5188           GatherCost =
5189               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5190                                   FinalVecTy, E->ReuseShuffleIndices);
5191       } else {
5192         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5193                           << " entries for bundle that starts with "
5194                           << *VL.front() << ".\n");
5195         // Detected that instead of gather we can emit a shuffle of single/two
5196         // previously vectorized nodes. Add the cost of the permutation rather
5197         // than gather.
5198         ::addMask(Mask, E->ReuseShuffleIndices);
5199         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5200       }
5201       return GatherCost;
5202     }
5203     if ((E->getOpcode() == Instruction::ExtractElement ||
5204          all_of(E->Scalars,
5205                 [](Value *V) {
5206                   return isa<ExtractElementInst, UndefValue>(V);
5207                 })) &&
5208         allSameType(VL)) {
5209       // Check that gather of extractelements can be represented as just a
5210       // shuffle of a single/two vectors the scalars are extracted from.
5211       SmallVector<int> Mask;
5212       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5213           isFixedVectorShuffle(VL, Mask);
5214       if (ShuffleKind.hasValue()) {
5215         // Found the bunch of extractelement instructions that must be gathered
5216         // into a vector and can be represented as a permutation elements in a
5217         // single input vector or of 2 input vectors.
5218         InstructionCost Cost =
5219             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5220         AdjustExtractsCost(Cost);
5221         if (NeedToShuffleReuses)
5222           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5223                                       FinalVecTy, E->ReuseShuffleIndices);
5224         return Cost;
5225       }
5226     }
5227     if (isSplat(VL)) {
5228       // Found the broadcasting of the single scalar, calculate the cost as the
5229       // broadcast.
5230       assert(VecTy == FinalVecTy &&
5231              "No reused scalars expected for broadcast.");
5232       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5233     }
5234     InstructionCost ReuseShuffleCost = 0;
5235     if (NeedToShuffleReuses)
5236       ReuseShuffleCost = TTI->getShuffleCost(
5237           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5238     // Improve gather cost for gather of loads, if we can group some of the
5239     // loads into vector loads.
5240     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5241         !E->isAltShuffle()) {
5242       BoUpSLP::ValueSet VectorizedLoads;
5243       unsigned StartIdx = 0;
5244       unsigned VF = VL.size() / 2;
5245       unsigned VectorizedCnt = 0;
5246       unsigned ScatterVectorizeCnt = 0;
5247       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5248       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5249         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5250              Cnt += VF) {
5251           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5252           if (!VectorizedLoads.count(Slice.front()) &&
5253               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5254             SmallVector<Value *> PointerOps;
5255             OrdersType CurrentOrder;
5256             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5257                                               *SE, CurrentOrder, PointerOps);
5258             switch (LS) {
5259             case LoadsState::Vectorize:
5260             case LoadsState::ScatterVectorize:
5261               // Mark the vectorized loads so that we don't vectorize them
5262               // again.
5263               if (LS == LoadsState::Vectorize)
5264                 ++VectorizedCnt;
5265               else
5266                 ++ScatterVectorizeCnt;
5267               VectorizedLoads.insert(Slice.begin(), Slice.end());
5268               // If we vectorized initial block, no need to try to vectorize it
5269               // again.
5270               if (Cnt == StartIdx)
5271                 StartIdx += VF;
5272               break;
5273             case LoadsState::Gather:
5274               break;
5275             }
5276           }
5277         }
5278         // Check if the whole array was vectorized already - exit.
5279         if (StartIdx >= VL.size())
5280           break;
5281         // Found vectorizable parts - exit.
5282         if (!VectorizedLoads.empty())
5283           break;
5284       }
5285       if (!VectorizedLoads.empty()) {
5286         InstructionCost GatherCost = 0;
5287         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5288         bool NeedInsertSubvectorAnalysis =
5289             !NumParts || (VL.size() / VF) > NumParts;
5290         // Get the cost for gathered loads.
5291         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5292           if (VectorizedLoads.contains(VL[I]))
5293             continue;
5294           GatherCost += getGatherCost(VL.slice(I, VF));
5295         }
5296         // The cost for vectorized loads.
5297         InstructionCost ScalarsCost = 0;
5298         for (Value *V : VectorizedLoads) {
5299           auto *LI = cast<LoadInst>(V);
5300           ScalarsCost += TTI->getMemoryOpCost(
5301               Instruction::Load, LI->getType(), LI->getAlign(),
5302               LI->getPointerAddressSpace(), CostKind, LI);
5303         }
5304         auto *LI = cast<LoadInst>(E->getMainOp());
5305         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5306         Align Alignment = LI->getAlign();
5307         GatherCost +=
5308             VectorizedCnt *
5309             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5310                                  LI->getPointerAddressSpace(), CostKind, LI);
5311         GatherCost += ScatterVectorizeCnt *
5312                       TTI->getGatherScatterOpCost(
5313                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5314                           /*VariableMask=*/false, Alignment, CostKind, LI);
5315         if (NeedInsertSubvectorAnalysis) {
5316           // Add the cost for the subvectors insert.
5317           for (int I = VF, E = VL.size(); I < E; I += VF)
5318             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5319                                               None, I, LoadTy);
5320         }
5321         return ReuseShuffleCost + GatherCost - ScalarsCost;
5322       }
5323     }
5324     return ReuseShuffleCost + getGatherCost(VL);
5325   }
5326   InstructionCost CommonCost = 0;
5327   SmallVector<int> Mask;
5328   if (!E->ReorderIndices.empty()) {
5329     SmallVector<int> NewMask;
5330     if (E->getOpcode() == Instruction::Store) {
5331       // For stores the order is actually a mask.
5332       NewMask.resize(E->ReorderIndices.size());
5333       copy(E->ReorderIndices, NewMask.begin());
5334     } else {
5335       inversePermutation(E->ReorderIndices, NewMask);
5336     }
5337     ::addMask(Mask, NewMask);
5338   }
5339   if (NeedToShuffleReuses)
5340     ::addMask(Mask, E->ReuseShuffleIndices);
5341   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5342     CommonCost =
5343         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5344   assert((E->State == TreeEntry::Vectorize ||
5345           E->State == TreeEntry::ScatterVectorize) &&
5346          "Unhandled state");
5347   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5348   Instruction *VL0 = E->getMainOp();
5349   unsigned ShuffleOrOp =
5350       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5351   switch (ShuffleOrOp) {
5352     case Instruction::PHI:
5353       return 0;
5354 
5355     case Instruction::ExtractValue:
5356     case Instruction::ExtractElement: {
5357       // The common cost of removal ExtractElement/ExtractValue instructions +
5358       // the cost of shuffles, if required to resuffle the original vector.
5359       if (NeedToShuffleReuses) {
5360         unsigned Idx = 0;
5361         for (unsigned I : E->ReuseShuffleIndices) {
5362           if (ShuffleOrOp == Instruction::ExtractElement) {
5363             auto *EE = cast<ExtractElementInst>(VL[I]);
5364             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5365                                                   EE->getVectorOperandType(),
5366                                                   *getExtractIndex(EE));
5367           } else {
5368             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5369                                                   VecTy, Idx);
5370             ++Idx;
5371           }
5372         }
5373         Idx = EntryVF;
5374         for (Value *V : VL) {
5375           if (ShuffleOrOp == Instruction::ExtractElement) {
5376             auto *EE = cast<ExtractElementInst>(V);
5377             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5378                                                   EE->getVectorOperandType(),
5379                                                   *getExtractIndex(EE));
5380           } else {
5381             --Idx;
5382             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5383                                                   VecTy, Idx);
5384           }
5385         }
5386       }
5387       if (ShuffleOrOp == Instruction::ExtractValue) {
5388         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5389           auto *EI = cast<Instruction>(VL[I]);
5390           // Take credit for instruction that will become dead.
5391           if (EI->hasOneUse()) {
5392             Instruction *Ext = EI->user_back();
5393             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5394                 all_of(Ext->users(),
5395                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5396               // Use getExtractWithExtendCost() to calculate the cost of
5397               // extractelement/ext pair.
5398               CommonCost -= TTI->getExtractWithExtendCost(
5399                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5400               // Add back the cost of s|zext which is subtracted separately.
5401               CommonCost += TTI->getCastInstrCost(
5402                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5403                   TTI::getCastContextHint(Ext), CostKind, Ext);
5404               continue;
5405             }
5406           }
5407           CommonCost -=
5408               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5409         }
5410       } else {
5411         AdjustExtractsCost(CommonCost);
5412       }
5413       return CommonCost;
5414     }
5415     case Instruction::InsertElement: {
5416       assert(E->ReuseShuffleIndices.empty() &&
5417              "Unique insertelements only are expected.");
5418       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5419 
5420       unsigned const NumElts = SrcVecTy->getNumElements();
5421       unsigned const NumScalars = VL.size();
5422       APInt DemandedElts = APInt::getZero(NumElts);
5423       // TODO: Add support for Instruction::InsertValue.
5424       SmallVector<int> Mask;
5425       if (!E->ReorderIndices.empty()) {
5426         inversePermutation(E->ReorderIndices, Mask);
5427         Mask.append(NumElts - NumScalars, UndefMaskElem);
5428       } else {
5429         Mask.assign(NumElts, UndefMaskElem);
5430         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5431       }
5432       unsigned Offset = *getInsertIndex(VL0);
5433       bool IsIdentity = true;
5434       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5435       Mask.swap(PrevMask);
5436       for (unsigned I = 0; I < NumScalars; ++I) {
5437         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5438         DemandedElts.setBit(InsertIdx);
5439         IsIdentity &= InsertIdx - Offset == I;
5440         Mask[InsertIdx - Offset] = I;
5441       }
5442       assert(Offset < NumElts && "Failed to find vector index offset");
5443 
5444       InstructionCost Cost = 0;
5445       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5446                                             /*Insert*/ true, /*Extract*/ false);
5447 
5448       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5449         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5450         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5451         Cost += TTI->getShuffleCost(
5452             TargetTransformInfo::SK_PermuteSingleSrc,
5453             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5454       } else if (!IsIdentity) {
5455         auto *FirstInsert =
5456             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5457               return !is_contained(E->Scalars,
5458                                    cast<Instruction>(V)->getOperand(0));
5459             }));
5460         if (isUndefVector(FirstInsert->getOperand(0))) {
5461           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5462         } else {
5463           SmallVector<int> InsertMask(NumElts);
5464           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5465           for (unsigned I = 0; I < NumElts; I++) {
5466             if (Mask[I] != UndefMaskElem)
5467               InsertMask[Offset + I] = NumElts + I;
5468           }
5469           Cost +=
5470               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5471         }
5472       }
5473 
5474       return Cost;
5475     }
5476     case Instruction::ZExt:
5477     case Instruction::SExt:
5478     case Instruction::FPToUI:
5479     case Instruction::FPToSI:
5480     case Instruction::FPExt:
5481     case Instruction::PtrToInt:
5482     case Instruction::IntToPtr:
5483     case Instruction::SIToFP:
5484     case Instruction::UIToFP:
5485     case Instruction::Trunc:
5486     case Instruction::FPTrunc:
5487     case Instruction::BitCast: {
5488       Type *SrcTy = VL0->getOperand(0)->getType();
5489       InstructionCost ScalarEltCost =
5490           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5491                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5492       if (NeedToShuffleReuses) {
5493         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5494       }
5495 
5496       // Calculate the cost of this instruction.
5497       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5498 
5499       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5500       InstructionCost VecCost = 0;
5501       // Check if the values are candidates to demote.
5502       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5503         VecCost = CommonCost + TTI->getCastInstrCost(
5504                                    E->getOpcode(), VecTy, SrcVecTy,
5505                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5506       }
5507       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5508       return VecCost - ScalarCost;
5509     }
5510     case Instruction::FCmp:
5511     case Instruction::ICmp:
5512     case Instruction::Select: {
5513       // Calculate the cost of this instruction.
5514       InstructionCost ScalarEltCost =
5515           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5516                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5517       if (NeedToShuffleReuses) {
5518         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5519       }
5520       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5521       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5522 
5523       // Check if all entries in VL are either compares or selects with compares
5524       // as condition that have the same predicates.
5525       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5526       bool First = true;
5527       for (auto *V : VL) {
5528         CmpInst::Predicate CurrentPred;
5529         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5530         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5531              !match(V, MatchCmp)) ||
5532             (!First && VecPred != CurrentPred)) {
5533           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5534           break;
5535         }
5536         First = false;
5537         VecPred = CurrentPred;
5538       }
5539 
5540       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5541           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5542       // Check if it is possible and profitable to use min/max for selects in
5543       // VL.
5544       //
5545       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5546       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5547         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5548                                           {VecTy, VecTy});
5549         InstructionCost IntrinsicCost =
5550             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5551         // If the selects are the only uses of the compares, they will be dead
5552         // and we can adjust the cost by removing their cost.
5553         if (IntrinsicAndUse.second)
5554           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5555                                                    MaskTy, VecPred, CostKind);
5556         VecCost = std::min(VecCost, IntrinsicCost);
5557       }
5558       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5559       return CommonCost + VecCost - ScalarCost;
5560     }
5561     case Instruction::FNeg:
5562     case Instruction::Add:
5563     case Instruction::FAdd:
5564     case Instruction::Sub:
5565     case Instruction::FSub:
5566     case Instruction::Mul:
5567     case Instruction::FMul:
5568     case Instruction::UDiv:
5569     case Instruction::SDiv:
5570     case Instruction::FDiv:
5571     case Instruction::URem:
5572     case Instruction::SRem:
5573     case Instruction::FRem:
5574     case Instruction::Shl:
5575     case Instruction::LShr:
5576     case Instruction::AShr:
5577     case Instruction::And:
5578     case Instruction::Or:
5579     case Instruction::Xor: {
5580       // Certain instructions can be cheaper to vectorize if they have a
5581       // constant second vector operand.
5582       TargetTransformInfo::OperandValueKind Op1VK =
5583           TargetTransformInfo::OK_AnyValue;
5584       TargetTransformInfo::OperandValueKind Op2VK =
5585           TargetTransformInfo::OK_UniformConstantValue;
5586       TargetTransformInfo::OperandValueProperties Op1VP =
5587           TargetTransformInfo::OP_None;
5588       TargetTransformInfo::OperandValueProperties Op2VP =
5589           TargetTransformInfo::OP_PowerOf2;
5590 
5591       // If all operands are exactly the same ConstantInt then set the
5592       // operand kind to OK_UniformConstantValue.
5593       // If instead not all operands are constants, then set the operand kind
5594       // to OK_AnyValue. If all operands are constants but not the same,
5595       // then set the operand kind to OK_NonUniformConstantValue.
5596       ConstantInt *CInt0 = nullptr;
5597       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5598         const Instruction *I = cast<Instruction>(VL[i]);
5599         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5600         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5601         if (!CInt) {
5602           Op2VK = TargetTransformInfo::OK_AnyValue;
5603           Op2VP = TargetTransformInfo::OP_None;
5604           break;
5605         }
5606         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5607             !CInt->getValue().isPowerOf2())
5608           Op2VP = TargetTransformInfo::OP_None;
5609         if (i == 0) {
5610           CInt0 = CInt;
5611           continue;
5612         }
5613         if (CInt0 != CInt)
5614           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5615       }
5616 
5617       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5618       InstructionCost ScalarEltCost =
5619           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5620                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5621       if (NeedToShuffleReuses) {
5622         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5623       }
5624       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5625       InstructionCost VecCost =
5626           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5627                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5628       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5629       return CommonCost + VecCost - ScalarCost;
5630     }
5631     case Instruction::GetElementPtr: {
5632       TargetTransformInfo::OperandValueKind Op1VK =
5633           TargetTransformInfo::OK_AnyValue;
5634       TargetTransformInfo::OperandValueKind Op2VK =
5635           TargetTransformInfo::OK_UniformConstantValue;
5636 
5637       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5638           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5639       if (NeedToShuffleReuses) {
5640         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5641       }
5642       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5643       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5644           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5645       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5646       return CommonCost + VecCost - ScalarCost;
5647     }
5648     case Instruction::Load: {
5649       // Cost of wide load - cost of scalar loads.
5650       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5651       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5652           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5653       if (NeedToShuffleReuses) {
5654         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5655       }
5656       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5657       InstructionCost VecLdCost;
5658       if (E->State == TreeEntry::Vectorize) {
5659         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5660                                          CostKind, VL0);
5661       } else {
5662         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5663         Align CommonAlignment = Alignment;
5664         for (Value *V : VL)
5665           CommonAlignment =
5666               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5667         VecLdCost = TTI->getGatherScatterOpCost(
5668             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5669             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5670       }
5671       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5672       return CommonCost + VecLdCost - ScalarLdCost;
5673     }
5674     case Instruction::Store: {
5675       // We know that we can merge the stores. Calculate the cost.
5676       bool IsReorder = !E->ReorderIndices.empty();
5677       auto *SI =
5678           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5679       Align Alignment = SI->getAlign();
5680       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5681           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5682       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5683       InstructionCost VecStCost = TTI->getMemoryOpCost(
5684           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5685       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5686       return CommonCost + VecStCost - ScalarStCost;
5687     }
5688     case Instruction::Call: {
5689       CallInst *CI = cast<CallInst>(VL0);
5690       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5691 
5692       // Calculate the cost of the scalar and vector calls.
5693       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5694       InstructionCost ScalarEltCost =
5695           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5696       if (NeedToShuffleReuses) {
5697         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5698       }
5699       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5700 
5701       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5702       InstructionCost VecCallCost =
5703           std::min(VecCallCosts.first, VecCallCosts.second);
5704 
5705       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5706                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5707                         << " for " << *CI << "\n");
5708 
5709       return CommonCost + VecCallCost - ScalarCallCost;
5710     }
5711     case Instruction::ShuffleVector: {
5712       assert(E->isAltShuffle() &&
5713              ((Instruction::isBinaryOp(E->getOpcode()) &&
5714                Instruction::isBinaryOp(E->getAltOpcode())) ||
5715               (Instruction::isCast(E->getOpcode()) &&
5716                Instruction::isCast(E->getAltOpcode())) ||
5717               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5718              "Invalid Shuffle Vector Operand");
5719       InstructionCost ScalarCost = 0;
5720       if (NeedToShuffleReuses) {
5721         for (unsigned Idx : E->ReuseShuffleIndices) {
5722           Instruction *I = cast<Instruction>(VL[Idx]);
5723           CommonCost -= TTI->getInstructionCost(I, CostKind);
5724         }
5725         for (Value *V : VL) {
5726           Instruction *I = cast<Instruction>(V);
5727           CommonCost += TTI->getInstructionCost(I, CostKind);
5728         }
5729       }
5730       for (Value *V : VL) {
5731         Instruction *I = cast<Instruction>(V);
5732         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5733         ScalarCost += TTI->getInstructionCost(I, CostKind);
5734       }
5735       // VecCost is equal to sum of the cost of creating 2 vectors
5736       // and the cost of creating shuffle.
5737       InstructionCost VecCost = 0;
5738       // Try to find the previous shuffle node with the same operands and same
5739       // main/alternate ops.
5740       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5741         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5742           if (TE.get() == E)
5743             break;
5744           if (TE->isAltShuffle() &&
5745               ((TE->getOpcode() == E->getOpcode() &&
5746                 TE->getAltOpcode() == E->getAltOpcode()) ||
5747                (TE->getOpcode() == E->getAltOpcode() &&
5748                 TE->getAltOpcode() == E->getOpcode())) &&
5749               TE->hasEqualOperands(*E))
5750             return true;
5751         }
5752         return false;
5753       };
5754       if (TryFindNodeWithEqualOperands()) {
5755         LLVM_DEBUG({
5756           dbgs() << "SLP: diamond match for alternate node found.\n";
5757           E->dump();
5758         });
5759         // No need to add new vector costs here since we're going to reuse
5760         // same main/alternate vector ops, just do different shuffling.
5761       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5762         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5763         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5764                                                CostKind);
5765       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5766         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5767                                           Builder.getInt1Ty(),
5768                                           CI0->getPredicate(), CostKind, VL0);
5769         VecCost += TTI->getCmpSelInstrCost(
5770             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5771             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5772             E->getAltOp());
5773       } else {
5774         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5775         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5776         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5777         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5778         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5779                                         TTI::CastContextHint::None, CostKind);
5780         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5781                                          TTI::CastContextHint::None, CostKind);
5782       }
5783 
5784       SmallVector<int> Mask;
5785       buildShuffleEntryMask(
5786           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5787           [E](Instruction *I) {
5788             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5789             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5790           },
5791           Mask);
5792       CommonCost =
5793           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5794       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5795       return CommonCost + VecCost - ScalarCost;
5796     }
5797     default:
5798       llvm_unreachable("Unknown instruction");
5799   }
5800 }
5801 
5802 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5803   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5804                     << VectorizableTree.size() << " is fully vectorizable .\n");
5805 
5806   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5807     SmallVector<int> Mask;
5808     return TE->State == TreeEntry::NeedToGather &&
5809            !any_of(TE->Scalars,
5810                    [this](Value *V) { return EphValues.contains(V); }) &&
5811            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5812             TE->Scalars.size() < Limit ||
5813             ((TE->getOpcode() == Instruction::ExtractElement ||
5814               all_of(TE->Scalars,
5815                      [](Value *V) {
5816                        return isa<ExtractElementInst, UndefValue>(V);
5817                      })) &&
5818              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5819             (TE->State == TreeEntry::NeedToGather &&
5820              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5821   };
5822 
5823   // We only handle trees of heights 1 and 2.
5824   if (VectorizableTree.size() == 1 &&
5825       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5826        (ForReduction &&
5827         AreVectorizableGathers(VectorizableTree[0].get(),
5828                                VectorizableTree[0]->Scalars.size()) &&
5829         VectorizableTree[0]->getVectorFactor() > 2)))
5830     return true;
5831 
5832   if (VectorizableTree.size() != 2)
5833     return false;
5834 
5835   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5836   // with the second gather nodes if they have less scalar operands rather than
5837   // the initial tree element (may be profitable to shuffle the second gather)
5838   // or they are extractelements, which form shuffle.
5839   SmallVector<int> Mask;
5840   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5841       AreVectorizableGathers(VectorizableTree[1].get(),
5842                              VectorizableTree[0]->Scalars.size()))
5843     return true;
5844 
5845   // Gathering cost would be too much for tiny trees.
5846   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5847       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5848        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5849     return false;
5850 
5851   return true;
5852 }
5853 
5854 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5855                                        TargetTransformInfo *TTI,
5856                                        bool MustMatchOrInst) {
5857   // Look past the root to find a source value. Arbitrarily follow the
5858   // path through operand 0 of any 'or'. Also, peek through optional
5859   // shift-left-by-multiple-of-8-bits.
5860   Value *ZextLoad = Root;
5861   const APInt *ShAmtC;
5862   bool FoundOr = false;
5863   while (!isa<ConstantExpr>(ZextLoad) &&
5864          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5865           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5866            ShAmtC->urem(8) == 0))) {
5867     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5868     ZextLoad = BinOp->getOperand(0);
5869     if (BinOp->getOpcode() == Instruction::Or)
5870       FoundOr = true;
5871   }
5872   // Check if the input is an extended load of the required or/shift expression.
5873   Value *Load;
5874   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5875       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5876     return false;
5877 
5878   // Require that the total load bit width is a legal integer type.
5879   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5880   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5881   Type *SrcTy = Load->getType();
5882   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5883   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5884     return false;
5885 
5886   // Everything matched - assume that we can fold the whole sequence using
5887   // load combining.
5888   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5889              << *(cast<Instruction>(Root)) << "\n");
5890 
5891   return true;
5892 }
5893 
5894 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5895   if (RdxKind != RecurKind::Or)
5896     return false;
5897 
5898   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5899   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5900   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5901                                     /* MatchOr */ false);
5902 }
5903 
5904 bool BoUpSLP::isLoadCombineCandidate() const {
5905   // Peek through a final sequence of stores and check if all operations are
5906   // likely to be load-combined.
5907   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5908   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5909     Value *X;
5910     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5911         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5912       return false;
5913   }
5914   return true;
5915 }
5916 
5917 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5918   // No need to vectorize inserts of gathered values.
5919   if (VectorizableTree.size() == 2 &&
5920       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5921       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5922     return true;
5923 
5924   // We can vectorize the tree if its size is greater than or equal to the
5925   // minimum size specified by the MinTreeSize command line option.
5926   if (VectorizableTree.size() >= MinTreeSize)
5927     return false;
5928 
5929   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5930   // can vectorize it if we can prove it fully vectorizable.
5931   if (isFullyVectorizableTinyTree(ForReduction))
5932     return false;
5933 
5934   assert(VectorizableTree.empty()
5935              ? ExternalUses.empty()
5936              : true && "We shouldn't have any external users");
5937 
5938   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5939   // vectorizable.
5940   return true;
5941 }
5942 
5943 InstructionCost BoUpSLP::getSpillCost() const {
5944   // Walk from the bottom of the tree to the top, tracking which values are
5945   // live. When we see a call instruction that is not part of our tree,
5946   // query TTI to see if there is a cost to keeping values live over it
5947   // (for example, if spills and fills are required).
5948   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5949   InstructionCost Cost = 0;
5950 
5951   SmallPtrSet<Instruction*, 4> LiveValues;
5952   Instruction *PrevInst = nullptr;
5953 
5954   // The entries in VectorizableTree are not necessarily ordered by their
5955   // position in basic blocks. Collect them and order them by dominance so later
5956   // instructions are guaranteed to be visited first. For instructions in
5957   // different basic blocks, we only scan to the beginning of the block, so
5958   // their order does not matter, as long as all instructions in a basic block
5959   // are grouped together. Using dominance ensures a deterministic order.
5960   SmallVector<Instruction *, 16> OrderedScalars;
5961   for (const auto &TEPtr : VectorizableTree) {
5962     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5963     if (!Inst)
5964       continue;
5965     OrderedScalars.push_back(Inst);
5966   }
5967   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5968     auto *NodeA = DT->getNode(A->getParent());
5969     auto *NodeB = DT->getNode(B->getParent());
5970     assert(NodeA && "Should only process reachable instructions");
5971     assert(NodeB && "Should only process reachable instructions");
5972     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5973            "Different nodes should have different DFS numbers");
5974     if (NodeA != NodeB)
5975       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5976     return B->comesBefore(A);
5977   });
5978 
5979   for (Instruction *Inst : OrderedScalars) {
5980     if (!PrevInst) {
5981       PrevInst = Inst;
5982       continue;
5983     }
5984 
5985     // Update LiveValues.
5986     LiveValues.erase(PrevInst);
5987     for (auto &J : PrevInst->operands()) {
5988       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5989         LiveValues.insert(cast<Instruction>(&*J));
5990     }
5991 
5992     LLVM_DEBUG({
5993       dbgs() << "SLP: #LV: " << LiveValues.size();
5994       for (auto *X : LiveValues)
5995         dbgs() << " " << X->getName();
5996       dbgs() << ", Looking at ";
5997       Inst->dump();
5998     });
5999 
6000     // Now find the sequence of instructions between PrevInst and Inst.
6001     unsigned NumCalls = 0;
6002     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6003                                  PrevInstIt =
6004                                      PrevInst->getIterator().getReverse();
6005     while (InstIt != PrevInstIt) {
6006       if (PrevInstIt == PrevInst->getParent()->rend()) {
6007         PrevInstIt = Inst->getParent()->rbegin();
6008         continue;
6009       }
6010 
6011       // Debug information does not impact spill cost.
6012       if ((isa<CallInst>(&*PrevInstIt) &&
6013            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6014           &*PrevInstIt != PrevInst)
6015         NumCalls++;
6016 
6017       ++PrevInstIt;
6018     }
6019 
6020     if (NumCalls) {
6021       SmallVector<Type*, 4> V;
6022       for (auto *II : LiveValues) {
6023         auto *ScalarTy = II->getType();
6024         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6025           ScalarTy = VectorTy->getElementType();
6026         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6027       }
6028       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6029     }
6030 
6031     PrevInst = Inst;
6032   }
6033 
6034   return Cost;
6035 }
6036 
6037 /// Check if two insertelement instructions are from the same buildvector.
6038 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6039                                             InsertElementInst *V) {
6040   // Instructions must be from the same basic blocks.
6041   if (VU->getParent() != V->getParent())
6042     return false;
6043   // Checks if 2 insertelements are from the same buildvector.
6044   if (VU->getType() != V->getType())
6045     return false;
6046   // Multiple used inserts are separate nodes.
6047   if (!VU->hasOneUse() && !V->hasOneUse())
6048     return false;
6049   auto *IE1 = VU;
6050   auto *IE2 = V;
6051   // Go through the vector operand of insertelement instructions trying to find
6052   // either VU as the original vector for IE2 or V as the original vector for
6053   // IE1.
6054   do {
6055     if (IE2 == VU || IE1 == V)
6056       return true;
6057     if (IE1) {
6058       if (IE1 != VU && !IE1->hasOneUse())
6059         IE1 = nullptr;
6060       else
6061         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6062     }
6063     if (IE2) {
6064       if (IE2 != V && !IE2->hasOneUse())
6065         IE2 = nullptr;
6066       else
6067         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6068     }
6069   } while (IE1 || IE2);
6070   return false;
6071 }
6072 
6073 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6074   InstructionCost Cost = 0;
6075   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6076                     << VectorizableTree.size() << ".\n");
6077 
6078   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6079 
6080   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6081     TreeEntry &TE = *VectorizableTree[I].get();
6082 
6083     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6084     Cost += C;
6085     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6086                       << " for bundle that starts with " << *TE.Scalars[0]
6087                       << ".\n"
6088                       << "SLP: Current total cost = " << Cost << "\n");
6089   }
6090 
6091   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6092   InstructionCost ExtractCost = 0;
6093   SmallVector<unsigned> VF;
6094   SmallVector<SmallVector<int>> ShuffleMask;
6095   SmallVector<Value *> FirstUsers;
6096   SmallVector<APInt> DemandedElts;
6097   for (ExternalUser &EU : ExternalUses) {
6098     // We only add extract cost once for the same scalar.
6099     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6100         !ExtractCostCalculated.insert(EU.Scalar).second)
6101       continue;
6102 
6103     // Uses by ephemeral values are free (because the ephemeral value will be
6104     // removed prior to code generation, and so the extraction will be
6105     // removed as well).
6106     if (EphValues.count(EU.User))
6107       continue;
6108 
6109     // No extract cost for vector "scalar"
6110     if (isa<FixedVectorType>(EU.Scalar->getType()))
6111       continue;
6112 
6113     // Already counted the cost for external uses when tried to adjust the cost
6114     // for extractelements, no need to add it again.
6115     if (isa<ExtractElementInst>(EU.Scalar))
6116       continue;
6117 
6118     // If found user is an insertelement, do not calculate extract cost but try
6119     // to detect it as a final shuffled/identity match.
6120     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6121       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6122         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6123         if (InsertIdx) {
6124           auto *It = find_if(FirstUsers, [VU](Value *V) {
6125             return areTwoInsertFromSameBuildVector(VU,
6126                                                    cast<InsertElementInst>(V));
6127           });
6128           int VecId = -1;
6129           if (It == FirstUsers.end()) {
6130             VF.push_back(FTy->getNumElements());
6131             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6132             // Find the insertvector, vectorized in tree, if any.
6133             Value *Base = VU;
6134             while (isa<InsertElementInst>(Base)) {
6135               // Build the mask for the vectorized insertelement instructions.
6136               if (const TreeEntry *E = getTreeEntry(Base)) {
6137                 VU = cast<InsertElementInst>(Base);
6138                 do {
6139                   int Idx = E->findLaneForValue(Base);
6140                   ShuffleMask.back()[Idx] = Idx;
6141                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6142                 } while (E == getTreeEntry(Base));
6143                 break;
6144               }
6145               Base = cast<InsertElementInst>(Base)->getOperand(0);
6146             }
6147             FirstUsers.push_back(VU);
6148             DemandedElts.push_back(APInt::getZero(VF.back()));
6149             VecId = FirstUsers.size() - 1;
6150           } else {
6151             VecId = std::distance(FirstUsers.begin(), It);
6152           }
6153           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6154           DemandedElts[VecId].setBit(*InsertIdx);
6155           continue;
6156         }
6157       }
6158     }
6159 
6160     // If we plan to rewrite the tree in a smaller type, we will need to sign
6161     // extend the extracted value back to the original type. Here, we account
6162     // for the extract and the added cost of the sign extend if needed.
6163     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6164     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6165     if (MinBWs.count(ScalarRoot)) {
6166       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6167       auto Extend =
6168           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6169       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6170       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6171                                                    VecTy, EU.Lane);
6172     } else {
6173       ExtractCost +=
6174           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6175     }
6176   }
6177 
6178   InstructionCost SpillCost = getSpillCost();
6179   Cost += SpillCost + ExtractCost;
6180   if (FirstUsers.size() == 1) {
6181     int Limit = ShuffleMask.front().size() * 2;
6182     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6183         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6184       InstructionCost C = TTI->getShuffleCost(
6185           TTI::SK_PermuteSingleSrc,
6186           cast<FixedVectorType>(FirstUsers.front()->getType()),
6187           ShuffleMask.front());
6188       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6189                         << " for final shuffle of insertelement external users "
6190                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6191                         << "SLP: Current total cost = " << Cost << "\n");
6192       Cost += C;
6193     }
6194     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6195         cast<FixedVectorType>(FirstUsers.front()->getType()),
6196         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6197     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6198                       << " for insertelements gather.\n"
6199                       << "SLP: Current total cost = " << Cost << "\n");
6200     Cost -= InsertCost;
6201   } else if (FirstUsers.size() >= 2) {
6202     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6203     // Combined masks of the first 2 vectors.
6204     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6205     copy(ShuffleMask.front(), CombinedMask.begin());
6206     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6207     auto *VecTy = FixedVectorType::get(
6208         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6209         MaxVF);
6210     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6211       if (ShuffleMask[1][I] != UndefMaskElem) {
6212         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6213         CombinedDemandedElts.setBit(I);
6214       }
6215     }
6216     InstructionCost C =
6217         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6218     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6219                       << " for final shuffle of vector node and external "
6220                          "insertelement users "
6221                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6222                       << "SLP: Current total cost = " << Cost << "\n");
6223     Cost += C;
6224     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6225         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6226     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6227                       << " for insertelements gather.\n"
6228                       << "SLP: Current total cost = " << Cost << "\n");
6229     Cost -= InsertCost;
6230     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6231       // Other elements - permutation of 2 vectors (the initial one and the
6232       // next Ith incoming vector).
6233       unsigned VF = ShuffleMask[I].size();
6234       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6235         int Mask = ShuffleMask[I][Idx];
6236         if (Mask != UndefMaskElem)
6237           CombinedMask[Idx] = MaxVF + Mask;
6238         else if (CombinedMask[Idx] != UndefMaskElem)
6239           CombinedMask[Idx] = Idx;
6240       }
6241       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6242         if (CombinedMask[Idx] != UndefMaskElem)
6243           CombinedMask[Idx] = Idx;
6244       InstructionCost C =
6245           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6246       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6247                         << " for final shuffle of vector node and external "
6248                            "insertelement users "
6249                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6250                         << "SLP: Current total cost = " << Cost << "\n");
6251       Cost += C;
6252       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6253           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6254           /*Insert*/ true, /*Extract*/ false);
6255       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6256                         << " for insertelements gather.\n"
6257                         << "SLP: Current total cost = " << Cost << "\n");
6258       Cost -= InsertCost;
6259     }
6260   }
6261 
6262 #ifndef NDEBUG
6263   SmallString<256> Str;
6264   {
6265     raw_svector_ostream OS(Str);
6266     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6267        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6268        << "SLP: Total Cost = " << Cost << ".\n";
6269   }
6270   LLVM_DEBUG(dbgs() << Str);
6271   if (ViewSLPTree)
6272     ViewGraph(this, "SLP" + F->getName(), false, Str);
6273 #endif
6274 
6275   return Cost;
6276 }
6277 
6278 Optional<TargetTransformInfo::ShuffleKind>
6279 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6280                                SmallVectorImpl<const TreeEntry *> &Entries) {
6281   // TODO: currently checking only for Scalars in the tree entry, need to count
6282   // reused elements too for better cost estimation.
6283   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6284   Entries.clear();
6285   // Build a lists of values to tree entries.
6286   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6287   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6288     if (EntryPtr.get() == TE)
6289       break;
6290     if (EntryPtr->State != TreeEntry::NeedToGather)
6291       continue;
6292     for (Value *V : EntryPtr->Scalars)
6293       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6294   }
6295   // Find all tree entries used by the gathered values. If no common entries
6296   // found - not a shuffle.
6297   // Here we build a set of tree nodes for each gathered value and trying to
6298   // find the intersection between these sets. If we have at least one common
6299   // tree node for each gathered value - we have just a permutation of the
6300   // single vector. If we have 2 different sets, we're in situation where we
6301   // have a permutation of 2 input vectors.
6302   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6303   DenseMap<Value *, int> UsedValuesEntry;
6304   for (Value *V : TE->Scalars) {
6305     if (isa<UndefValue>(V))
6306       continue;
6307     // Build a list of tree entries where V is used.
6308     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6309     auto It = ValueToTEs.find(V);
6310     if (It != ValueToTEs.end())
6311       VToTEs = It->second;
6312     if (const TreeEntry *VTE = getTreeEntry(V))
6313       VToTEs.insert(VTE);
6314     if (VToTEs.empty())
6315       return None;
6316     if (UsedTEs.empty()) {
6317       // The first iteration, just insert the list of nodes to vector.
6318       UsedTEs.push_back(VToTEs);
6319     } else {
6320       // Need to check if there are any previously used tree nodes which use V.
6321       // If there are no such nodes, consider that we have another one input
6322       // vector.
6323       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6324       unsigned Idx = 0;
6325       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6326         // Do we have a non-empty intersection of previously listed tree entries
6327         // and tree entries using current V?
6328         set_intersect(VToTEs, Set);
6329         if (!VToTEs.empty()) {
6330           // Yes, write the new subset and continue analysis for the next
6331           // scalar.
6332           Set.swap(VToTEs);
6333           break;
6334         }
6335         VToTEs = SavedVToTEs;
6336         ++Idx;
6337       }
6338       // No non-empty intersection found - need to add a second set of possible
6339       // source vectors.
6340       if (Idx == UsedTEs.size()) {
6341         // If the number of input vectors is greater than 2 - not a permutation,
6342         // fallback to the regular gather.
6343         if (UsedTEs.size() == 2)
6344           return None;
6345         UsedTEs.push_back(SavedVToTEs);
6346         Idx = UsedTEs.size() - 1;
6347       }
6348       UsedValuesEntry.try_emplace(V, Idx);
6349     }
6350   }
6351 
6352   unsigned VF = 0;
6353   if (UsedTEs.size() == 1) {
6354     // Try to find the perfect match in another gather node at first.
6355     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6356       return EntryPtr->isSame(TE->Scalars);
6357     });
6358     if (It != UsedTEs.front().end()) {
6359       Entries.push_back(*It);
6360       std::iota(Mask.begin(), Mask.end(), 0);
6361       return TargetTransformInfo::SK_PermuteSingleSrc;
6362     }
6363     // No perfect match, just shuffle, so choose the first tree node.
6364     Entries.push_back(*UsedTEs.front().begin());
6365   } else {
6366     // Try to find nodes with the same vector factor.
6367     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6368     DenseMap<int, const TreeEntry *> VFToTE;
6369     for (const TreeEntry *TE : UsedTEs.front())
6370       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6371     for (const TreeEntry *TE : UsedTEs.back()) {
6372       auto It = VFToTE.find(TE->getVectorFactor());
6373       if (It != VFToTE.end()) {
6374         VF = It->first;
6375         Entries.push_back(It->second);
6376         Entries.push_back(TE);
6377         break;
6378       }
6379     }
6380     // No 2 source vectors with the same vector factor - give up and do regular
6381     // gather.
6382     if (Entries.empty())
6383       return None;
6384   }
6385 
6386   // Build a shuffle mask for better cost estimation and vector emission.
6387   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6388     Value *V = TE->Scalars[I];
6389     if (isa<UndefValue>(V))
6390       continue;
6391     unsigned Idx = UsedValuesEntry.lookup(V);
6392     const TreeEntry *VTE = Entries[Idx];
6393     int FoundLane = VTE->findLaneForValue(V);
6394     Mask[I] = Idx * VF + FoundLane;
6395     // Extra check required by isSingleSourceMaskImpl function (called by
6396     // ShuffleVectorInst::isSingleSourceMask).
6397     if (Mask[I] >= 2 * E)
6398       return None;
6399   }
6400   switch (Entries.size()) {
6401   case 1:
6402     return TargetTransformInfo::SK_PermuteSingleSrc;
6403   case 2:
6404     return TargetTransformInfo::SK_PermuteTwoSrc;
6405   default:
6406     break;
6407   }
6408   return None;
6409 }
6410 
6411 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6412                                        const APInt &ShuffledIndices,
6413                                        bool NeedToShuffle) const {
6414   InstructionCost Cost =
6415       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6416                                     /*Extract*/ false);
6417   if (NeedToShuffle)
6418     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6419   return Cost;
6420 }
6421 
6422 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6423   // Find the type of the operands in VL.
6424   Type *ScalarTy = VL[0]->getType();
6425   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6426     ScalarTy = SI->getValueOperand()->getType();
6427   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6428   bool DuplicateNonConst = false;
6429   // Find the cost of inserting/extracting values from the vector.
6430   // Check if the same elements are inserted several times and count them as
6431   // shuffle candidates.
6432   APInt ShuffledElements = APInt::getZero(VL.size());
6433   DenseSet<Value *> UniqueElements;
6434   // Iterate in reverse order to consider insert elements with the high cost.
6435   for (unsigned I = VL.size(); I > 0; --I) {
6436     unsigned Idx = I - 1;
6437     // No need to shuffle duplicates for constants.
6438     if (isConstant(VL[Idx])) {
6439       ShuffledElements.setBit(Idx);
6440       continue;
6441     }
6442     if (!UniqueElements.insert(VL[Idx]).second) {
6443       DuplicateNonConst = true;
6444       ShuffledElements.setBit(Idx);
6445     }
6446   }
6447   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6448 }
6449 
6450 // Perform operand reordering on the instructions in VL and return the reordered
6451 // operands in Left and Right.
6452 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6453                                              SmallVectorImpl<Value *> &Left,
6454                                              SmallVectorImpl<Value *> &Right,
6455                                              const DataLayout &DL,
6456                                              ScalarEvolution &SE,
6457                                              const BoUpSLP &R) {
6458   if (VL.empty())
6459     return;
6460   VLOperands Ops(VL, DL, SE, R);
6461   // Reorder the operands in place.
6462   Ops.reorder();
6463   Left = Ops.getVL(0);
6464   Right = Ops.getVL(1);
6465 }
6466 
6467 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6468   // Get the basic block this bundle is in. All instructions in the bundle
6469   // should be in this block.
6470   auto *Front = E->getMainOp();
6471   auto *BB = Front->getParent();
6472   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6473     auto *I = cast<Instruction>(V);
6474     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6475   }));
6476 
6477   auto &&FindLastInst = [E, Front]() {
6478     Instruction *LastInst = Front;
6479     for (Value *V : E->Scalars) {
6480       auto *I = dyn_cast<Instruction>(V);
6481       if (!I)
6482         continue;
6483       if (LastInst->comesBefore(I))
6484         LastInst = I;
6485     }
6486     return LastInst;
6487   };
6488 
6489   auto &&FindFirstInst = [E, Front]() {
6490     Instruction *FirstInst = Front;
6491     for (Value *V : E->Scalars) {
6492       auto *I = dyn_cast<Instruction>(V);
6493       if (!I)
6494         continue;
6495       if (I->comesBefore(FirstInst))
6496         FirstInst = I;
6497     }
6498     return FirstInst;
6499   };
6500 
6501   // Set the insert point to the beginning of the basic block if the entry
6502   // should not be scheduled.
6503   if (E->State != TreeEntry::NeedToGather &&
6504       doesNotNeedToSchedule(E->Scalars)) {
6505     BasicBlock::iterator InsertPt;
6506     if (all_of(E->Scalars, isUsedOutsideBlock))
6507       InsertPt = FindLastInst()->getIterator();
6508     else
6509       InsertPt = FindFirstInst()->getIterator();
6510     Builder.SetInsertPoint(BB, InsertPt);
6511     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6512     return;
6513   }
6514 
6515   // The last instruction in the bundle in program order.
6516   Instruction *LastInst = nullptr;
6517 
6518   // Find the last instruction. The common case should be that BB has been
6519   // scheduled, and the last instruction is VL.back(). So we start with
6520   // VL.back() and iterate over schedule data until we reach the end of the
6521   // bundle. The end of the bundle is marked by null ScheduleData.
6522   if (BlocksSchedules.count(BB)) {
6523     Value *V = E->isOneOf(E->Scalars.back());
6524     if (doesNotNeedToBeScheduled(V))
6525       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6526     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6527     if (Bundle && Bundle->isPartOfBundle())
6528       for (; Bundle; Bundle = Bundle->NextInBundle)
6529         if (Bundle->OpValue == Bundle->Inst)
6530           LastInst = Bundle->Inst;
6531   }
6532 
6533   // LastInst can still be null at this point if there's either not an entry
6534   // for BB in BlocksSchedules or there's no ScheduleData available for
6535   // VL.back(). This can be the case if buildTree_rec aborts for various
6536   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6537   // size is reached, etc.). ScheduleData is initialized in the scheduling
6538   // "dry-run".
6539   //
6540   // If this happens, we can still find the last instruction by brute force. We
6541   // iterate forwards from Front (inclusive) until we either see all
6542   // instructions in the bundle or reach the end of the block. If Front is the
6543   // last instruction in program order, LastInst will be set to Front, and we
6544   // will visit all the remaining instructions in the block.
6545   //
6546   // One of the reasons we exit early from buildTree_rec is to place an upper
6547   // bound on compile-time. Thus, taking an additional compile-time hit here is
6548   // not ideal. However, this should be exceedingly rare since it requires that
6549   // we both exit early from buildTree_rec and that the bundle be out-of-order
6550   // (causing us to iterate all the way to the end of the block).
6551   if (!LastInst)
6552     LastInst = FindLastInst();
6553   assert(LastInst && "Failed to find last instruction in bundle");
6554 
6555   // Set the insertion point after the last instruction in the bundle. Set the
6556   // debug location to Front.
6557   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6558   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6559 }
6560 
6561 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6562   // List of instructions/lanes from current block and/or the blocks which are
6563   // part of the current loop. These instructions will be inserted at the end to
6564   // make it possible to optimize loops and hoist invariant instructions out of
6565   // the loops body with better chances for success.
6566   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6567   SmallSet<int, 4> PostponedIndices;
6568   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6569   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6570     SmallPtrSet<BasicBlock *, 4> Visited;
6571     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6572       InsertBB = InsertBB->getSinglePredecessor();
6573     return InsertBB && InsertBB == InstBB;
6574   };
6575   for (int I = 0, E = VL.size(); I < E; ++I) {
6576     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6577       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6578            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6579           PostponedIndices.insert(I).second)
6580         PostponedInsts.emplace_back(Inst, I);
6581   }
6582 
6583   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6584     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6585     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6586     if (!InsElt)
6587       return Vec;
6588     GatherShuffleSeq.insert(InsElt);
6589     CSEBlocks.insert(InsElt->getParent());
6590     // Add to our 'need-to-extract' list.
6591     if (TreeEntry *Entry = getTreeEntry(V)) {
6592       // Find which lane we need to extract.
6593       unsigned FoundLane = Entry->findLaneForValue(V);
6594       ExternalUses.emplace_back(V, InsElt, FoundLane);
6595     }
6596     return Vec;
6597   };
6598   Value *Val0 =
6599       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6600   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6601   Value *Vec = PoisonValue::get(VecTy);
6602   SmallVector<int> NonConsts;
6603   // Insert constant values at first.
6604   for (int I = 0, E = VL.size(); I < E; ++I) {
6605     if (PostponedIndices.contains(I))
6606       continue;
6607     if (!isConstant(VL[I])) {
6608       NonConsts.push_back(I);
6609       continue;
6610     }
6611     Vec = CreateInsertElement(Vec, VL[I], I);
6612   }
6613   // Insert non-constant values.
6614   for (int I : NonConsts)
6615     Vec = CreateInsertElement(Vec, VL[I], I);
6616   // Append instructions, which are/may be part of the loop, in the end to make
6617   // it possible to hoist non-loop-based instructions.
6618   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6619     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6620 
6621   return Vec;
6622 }
6623 
6624 namespace {
6625 /// Merges shuffle masks and emits final shuffle instruction, if required.
6626 class ShuffleInstructionBuilder {
6627   IRBuilderBase &Builder;
6628   const unsigned VF = 0;
6629   bool IsFinalized = false;
6630   SmallVector<int, 4> Mask;
6631   /// Holds all of the instructions that we gathered.
6632   SetVector<Instruction *> &GatherShuffleSeq;
6633   /// A list of blocks that we are going to CSE.
6634   SetVector<BasicBlock *> &CSEBlocks;
6635 
6636 public:
6637   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6638                             SetVector<Instruction *> &GatherShuffleSeq,
6639                             SetVector<BasicBlock *> &CSEBlocks)
6640       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6641         CSEBlocks(CSEBlocks) {}
6642 
6643   /// Adds a mask, inverting it before applying.
6644   void addInversedMask(ArrayRef<unsigned> SubMask) {
6645     if (SubMask.empty())
6646       return;
6647     SmallVector<int, 4> NewMask;
6648     inversePermutation(SubMask, NewMask);
6649     addMask(NewMask);
6650   }
6651 
6652   /// Functions adds masks, merging them into  single one.
6653   void addMask(ArrayRef<unsigned> SubMask) {
6654     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6655     addMask(NewMask);
6656   }
6657 
6658   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6659 
6660   Value *finalize(Value *V) {
6661     IsFinalized = true;
6662     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6663     if (VF == ValueVF && Mask.empty())
6664       return V;
6665     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6666     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6667     addMask(NormalizedMask);
6668 
6669     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6670       return V;
6671     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6672     if (auto *I = dyn_cast<Instruction>(Vec)) {
6673       GatherShuffleSeq.insert(I);
6674       CSEBlocks.insert(I->getParent());
6675     }
6676     return Vec;
6677   }
6678 
6679   ~ShuffleInstructionBuilder() {
6680     assert((IsFinalized || Mask.empty()) &&
6681            "Shuffle construction must be finalized.");
6682   }
6683 };
6684 } // namespace
6685 
6686 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6687   const unsigned VF = VL.size();
6688   InstructionsState S = getSameOpcode(VL);
6689   if (S.getOpcode()) {
6690     if (TreeEntry *E = getTreeEntry(S.OpValue))
6691       if (E->isSame(VL)) {
6692         Value *V = vectorizeTree(E);
6693         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6694           if (!E->ReuseShuffleIndices.empty()) {
6695             // Reshuffle to get only unique values.
6696             // If some of the scalars are duplicated in the vectorization tree
6697             // entry, we do not vectorize them but instead generate a mask for
6698             // the reuses. But if there are several users of the same entry,
6699             // they may have different vectorization factors. This is especially
6700             // important for PHI nodes. In this case, we need to adapt the
6701             // resulting instruction for the user vectorization factor and have
6702             // to reshuffle it again to take only unique elements of the vector.
6703             // Without this code the function incorrectly returns reduced vector
6704             // instruction with the same elements, not with the unique ones.
6705 
6706             // block:
6707             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6708             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6709             // ... (use %2)
6710             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6711             // br %block
6712             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6713             SmallSet<int, 4> UsedIdxs;
6714             int Pos = 0;
6715             int Sz = VL.size();
6716             for (int Idx : E->ReuseShuffleIndices) {
6717               if (Idx != Sz && Idx != UndefMaskElem &&
6718                   UsedIdxs.insert(Idx).second)
6719                 UniqueIdxs[Idx] = Pos;
6720               ++Pos;
6721             }
6722             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6723                                             "less than original vector size.");
6724             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6725             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6726           } else {
6727             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6728                    "Expected vectorization factor less "
6729                    "than original vector size.");
6730             SmallVector<int> UniformMask(VF, 0);
6731             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6732             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6733           }
6734           if (auto *I = dyn_cast<Instruction>(V)) {
6735             GatherShuffleSeq.insert(I);
6736             CSEBlocks.insert(I->getParent());
6737           }
6738         }
6739         return V;
6740       }
6741   }
6742 
6743   // Can't vectorize this, so simply build a new vector with each lane
6744   // corresponding to the requested value.
6745   return createBuildVector(VL);
6746 }
6747 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6748   unsigned VF = VL.size();
6749   // Exploit possible reuse of values across lanes.
6750   SmallVector<int> ReuseShuffleIndicies;
6751   SmallVector<Value *> UniqueValues;
6752   if (VL.size() > 2) {
6753     DenseMap<Value *, unsigned> UniquePositions;
6754     unsigned NumValues =
6755         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6756                                     return !isa<UndefValue>(V);
6757                                   }).base());
6758     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6759     int UniqueVals = 0;
6760     for (Value *V : VL.drop_back(VL.size() - VF)) {
6761       if (isa<UndefValue>(V)) {
6762         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6763         continue;
6764       }
6765       if (isConstant(V)) {
6766         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6767         UniqueValues.emplace_back(V);
6768         continue;
6769       }
6770       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6771       ReuseShuffleIndicies.emplace_back(Res.first->second);
6772       if (Res.second) {
6773         UniqueValues.emplace_back(V);
6774         ++UniqueVals;
6775       }
6776     }
6777     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6778       // Emit pure splat vector.
6779       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6780                                   UndefMaskElem);
6781     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6782       ReuseShuffleIndicies.clear();
6783       UniqueValues.clear();
6784       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6785     }
6786     UniqueValues.append(VF - UniqueValues.size(),
6787                         PoisonValue::get(VL[0]->getType()));
6788     VL = UniqueValues;
6789   }
6790 
6791   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6792                                            CSEBlocks);
6793   Value *Vec = gather(VL);
6794   if (!ReuseShuffleIndicies.empty()) {
6795     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6796     Vec = ShuffleBuilder.finalize(Vec);
6797   }
6798   return Vec;
6799 }
6800 
6801 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6802   IRBuilder<>::InsertPointGuard Guard(Builder);
6803 
6804   if (E->VectorizedValue) {
6805     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6806     return E->VectorizedValue;
6807   }
6808 
6809   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6810   unsigned VF = E->getVectorFactor();
6811   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6812                                            CSEBlocks);
6813   if (E->State == TreeEntry::NeedToGather) {
6814     if (E->getMainOp())
6815       setInsertPointAfterBundle(E);
6816     Value *Vec;
6817     SmallVector<int> Mask;
6818     SmallVector<const TreeEntry *> Entries;
6819     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6820         isGatherShuffledEntry(E, Mask, Entries);
6821     if (Shuffle.hasValue()) {
6822       assert((Entries.size() == 1 || Entries.size() == 2) &&
6823              "Expected shuffle of 1 or 2 entries.");
6824       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6825                                         Entries.back()->VectorizedValue, Mask);
6826       if (auto *I = dyn_cast<Instruction>(Vec)) {
6827         GatherShuffleSeq.insert(I);
6828         CSEBlocks.insert(I->getParent());
6829       }
6830     } else {
6831       Vec = gather(E->Scalars);
6832     }
6833     if (NeedToShuffleReuses) {
6834       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6835       Vec = ShuffleBuilder.finalize(Vec);
6836     }
6837     E->VectorizedValue = Vec;
6838     return Vec;
6839   }
6840 
6841   assert((E->State == TreeEntry::Vectorize ||
6842           E->State == TreeEntry::ScatterVectorize) &&
6843          "Unhandled state");
6844   unsigned ShuffleOrOp =
6845       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6846   Instruction *VL0 = E->getMainOp();
6847   Type *ScalarTy = VL0->getType();
6848   if (auto *Store = dyn_cast<StoreInst>(VL0))
6849     ScalarTy = Store->getValueOperand()->getType();
6850   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6851     ScalarTy = IE->getOperand(1)->getType();
6852   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6853   switch (ShuffleOrOp) {
6854     case Instruction::PHI: {
6855       assert(
6856           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6857           "PHI reordering is free.");
6858       auto *PH = cast<PHINode>(VL0);
6859       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6860       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6861       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6862       Value *V = NewPhi;
6863 
6864       // Adjust insertion point once all PHI's have been generated.
6865       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6866       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6867 
6868       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6869       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6870       V = ShuffleBuilder.finalize(V);
6871 
6872       E->VectorizedValue = V;
6873 
6874       // PHINodes may have multiple entries from the same block. We want to
6875       // visit every block once.
6876       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6877 
6878       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6879         ValueList Operands;
6880         BasicBlock *IBB = PH->getIncomingBlock(i);
6881 
6882         if (!VisitedBBs.insert(IBB).second) {
6883           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6884           continue;
6885         }
6886 
6887         Builder.SetInsertPoint(IBB->getTerminator());
6888         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6889         Value *Vec = vectorizeTree(E->getOperand(i));
6890         NewPhi->addIncoming(Vec, IBB);
6891       }
6892 
6893       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6894              "Invalid number of incoming values");
6895       return V;
6896     }
6897 
6898     case Instruction::ExtractElement: {
6899       Value *V = E->getSingleOperand(0);
6900       Builder.SetInsertPoint(VL0);
6901       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6902       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6903       V = ShuffleBuilder.finalize(V);
6904       E->VectorizedValue = V;
6905       return V;
6906     }
6907     case Instruction::ExtractValue: {
6908       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6909       Builder.SetInsertPoint(LI);
6910       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6911       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6912       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6913       Value *NewV = propagateMetadata(V, E->Scalars);
6914       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6915       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6916       NewV = ShuffleBuilder.finalize(NewV);
6917       E->VectorizedValue = NewV;
6918       return NewV;
6919     }
6920     case Instruction::InsertElement: {
6921       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6922       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6923       Value *V = vectorizeTree(E->getOperand(1));
6924 
6925       // Create InsertVector shuffle if necessary
6926       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6927         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6928       }));
6929       const unsigned NumElts =
6930           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6931       const unsigned NumScalars = E->Scalars.size();
6932 
6933       unsigned Offset = *getInsertIndex(VL0);
6934       assert(Offset < NumElts && "Failed to find vector index offset");
6935 
6936       // Create shuffle to resize vector
6937       SmallVector<int> Mask;
6938       if (!E->ReorderIndices.empty()) {
6939         inversePermutation(E->ReorderIndices, Mask);
6940         Mask.append(NumElts - NumScalars, UndefMaskElem);
6941       } else {
6942         Mask.assign(NumElts, UndefMaskElem);
6943         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6944       }
6945       // Create InsertVector shuffle if necessary
6946       bool IsIdentity = true;
6947       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6948       Mask.swap(PrevMask);
6949       for (unsigned I = 0; I < NumScalars; ++I) {
6950         Value *Scalar = E->Scalars[PrevMask[I]];
6951         unsigned InsertIdx = *getInsertIndex(Scalar);
6952         IsIdentity &= InsertIdx - Offset == I;
6953         Mask[InsertIdx - Offset] = I;
6954       }
6955       if (!IsIdentity || NumElts != NumScalars) {
6956         V = Builder.CreateShuffleVector(V, Mask);
6957         if (auto *I = dyn_cast<Instruction>(V)) {
6958           GatherShuffleSeq.insert(I);
6959           CSEBlocks.insert(I->getParent());
6960         }
6961       }
6962 
6963       if ((!IsIdentity || Offset != 0 ||
6964            !isUndefVector(FirstInsert->getOperand(0))) &&
6965           NumElts != NumScalars) {
6966         SmallVector<int> InsertMask(NumElts);
6967         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6968         for (unsigned I = 0; I < NumElts; I++) {
6969           if (Mask[I] != UndefMaskElem)
6970             InsertMask[Offset + I] = NumElts + I;
6971         }
6972 
6973         V = Builder.CreateShuffleVector(
6974             FirstInsert->getOperand(0), V, InsertMask,
6975             cast<Instruction>(E->Scalars.back())->getName());
6976         if (auto *I = dyn_cast<Instruction>(V)) {
6977           GatherShuffleSeq.insert(I);
6978           CSEBlocks.insert(I->getParent());
6979         }
6980       }
6981 
6982       ++NumVectorInstructions;
6983       E->VectorizedValue = V;
6984       return V;
6985     }
6986     case Instruction::ZExt:
6987     case Instruction::SExt:
6988     case Instruction::FPToUI:
6989     case Instruction::FPToSI:
6990     case Instruction::FPExt:
6991     case Instruction::PtrToInt:
6992     case Instruction::IntToPtr:
6993     case Instruction::SIToFP:
6994     case Instruction::UIToFP:
6995     case Instruction::Trunc:
6996     case Instruction::FPTrunc:
6997     case Instruction::BitCast: {
6998       setInsertPointAfterBundle(E);
6999 
7000       Value *InVec = vectorizeTree(E->getOperand(0));
7001 
7002       if (E->VectorizedValue) {
7003         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7004         return E->VectorizedValue;
7005       }
7006 
7007       auto *CI = cast<CastInst>(VL0);
7008       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7009       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7010       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7011       V = ShuffleBuilder.finalize(V);
7012 
7013       E->VectorizedValue = V;
7014       ++NumVectorInstructions;
7015       return V;
7016     }
7017     case Instruction::FCmp:
7018     case Instruction::ICmp: {
7019       setInsertPointAfterBundle(E);
7020 
7021       Value *L = vectorizeTree(E->getOperand(0));
7022       Value *R = vectorizeTree(E->getOperand(1));
7023 
7024       if (E->VectorizedValue) {
7025         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7026         return E->VectorizedValue;
7027       }
7028 
7029       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7030       Value *V = Builder.CreateCmp(P0, L, R);
7031       propagateIRFlags(V, E->Scalars, VL0);
7032       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7033       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7034       V = ShuffleBuilder.finalize(V);
7035 
7036       E->VectorizedValue = V;
7037       ++NumVectorInstructions;
7038       return V;
7039     }
7040     case Instruction::Select: {
7041       setInsertPointAfterBundle(E);
7042 
7043       Value *Cond = vectorizeTree(E->getOperand(0));
7044       Value *True = vectorizeTree(E->getOperand(1));
7045       Value *False = vectorizeTree(E->getOperand(2));
7046 
7047       if (E->VectorizedValue) {
7048         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7049         return E->VectorizedValue;
7050       }
7051 
7052       Value *V = Builder.CreateSelect(Cond, True, False);
7053       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7054       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7055       V = ShuffleBuilder.finalize(V);
7056 
7057       E->VectorizedValue = V;
7058       ++NumVectorInstructions;
7059       return V;
7060     }
7061     case Instruction::FNeg: {
7062       setInsertPointAfterBundle(E);
7063 
7064       Value *Op = vectorizeTree(E->getOperand(0));
7065 
7066       if (E->VectorizedValue) {
7067         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7068         return E->VectorizedValue;
7069       }
7070 
7071       Value *V = Builder.CreateUnOp(
7072           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7073       propagateIRFlags(V, E->Scalars, VL0);
7074       if (auto *I = dyn_cast<Instruction>(V))
7075         V = propagateMetadata(I, E->Scalars);
7076 
7077       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7078       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7079       V = ShuffleBuilder.finalize(V);
7080 
7081       E->VectorizedValue = V;
7082       ++NumVectorInstructions;
7083 
7084       return V;
7085     }
7086     case Instruction::Add:
7087     case Instruction::FAdd:
7088     case Instruction::Sub:
7089     case Instruction::FSub:
7090     case Instruction::Mul:
7091     case Instruction::FMul:
7092     case Instruction::UDiv:
7093     case Instruction::SDiv:
7094     case Instruction::FDiv:
7095     case Instruction::URem:
7096     case Instruction::SRem:
7097     case Instruction::FRem:
7098     case Instruction::Shl:
7099     case Instruction::LShr:
7100     case Instruction::AShr:
7101     case Instruction::And:
7102     case Instruction::Or:
7103     case Instruction::Xor: {
7104       setInsertPointAfterBundle(E);
7105 
7106       Value *LHS = vectorizeTree(E->getOperand(0));
7107       Value *RHS = vectorizeTree(E->getOperand(1));
7108 
7109       if (E->VectorizedValue) {
7110         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7111         return E->VectorizedValue;
7112       }
7113 
7114       Value *V = Builder.CreateBinOp(
7115           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7116           RHS);
7117       propagateIRFlags(V, E->Scalars, VL0);
7118       if (auto *I = dyn_cast<Instruction>(V))
7119         V = propagateMetadata(I, E->Scalars);
7120 
7121       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7122       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7123       V = ShuffleBuilder.finalize(V);
7124 
7125       E->VectorizedValue = V;
7126       ++NumVectorInstructions;
7127 
7128       return V;
7129     }
7130     case Instruction::Load: {
7131       // Loads are inserted at the head of the tree because we don't want to
7132       // sink them all the way down past store instructions.
7133       setInsertPointAfterBundle(E);
7134 
7135       LoadInst *LI = cast<LoadInst>(VL0);
7136       Instruction *NewLI;
7137       unsigned AS = LI->getPointerAddressSpace();
7138       Value *PO = LI->getPointerOperand();
7139       if (E->State == TreeEntry::Vectorize) {
7140         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7141         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7142 
7143         // The pointer operand uses an in-tree scalar so we add the new BitCast
7144         // or LoadInst to ExternalUses list to make sure that an extract will
7145         // be generated in the future.
7146         if (TreeEntry *Entry = getTreeEntry(PO)) {
7147           // Find which lane we need to extract.
7148           unsigned FoundLane = Entry->findLaneForValue(PO);
7149           ExternalUses.emplace_back(
7150               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7151         }
7152       } else {
7153         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7154         Value *VecPtr = vectorizeTree(E->getOperand(0));
7155         // Use the minimum alignment of the gathered loads.
7156         Align CommonAlignment = LI->getAlign();
7157         for (Value *V : E->Scalars)
7158           CommonAlignment =
7159               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7160         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7161       }
7162       Value *V = propagateMetadata(NewLI, E->Scalars);
7163 
7164       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7165       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7166       V = ShuffleBuilder.finalize(V);
7167       E->VectorizedValue = V;
7168       ++NumVectorInstructions;
7169       return V;
7170     }
7171     case Instruction::Store: {
7172       auto *SI = cast<StoreInst>(VL0);
7173       unsigned AS = SI->getPointerAddressSpace();
7174 
7175       setInsertPointAfterBundle(E);
7176 
7177       Value *VecValue = vectorizeTree(E->getOperand(0));
7178       ShuffleBuilder.addMask(E->ReorderIndices);
7179       VecValue = ShuffleBuilder.finalize(VecValue);
7180 
7181       Value *ScalarPtr = SI->getPointerOperand();
7182       Value *VecPtr = Builder.CreateBitCast(
7183           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7184       StoreInst *ST =
7185           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7186 
7187       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7188       // StoreInst to ExternalUses to make sure that an extract will be
7189       // generated in the future.
7190       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7191         // Find which lane we need to extract.
7192         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7193         ExternalUses.push_back(ExternalUser(
7194             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7195             FoundLane));
7196       }
7197 
7198       Value *V = propagateMetadata(ST, E->Scalars);
7199 
7200       E->VectorizedValue = V;
7201       ++NumVectorInstructions;
7202       return V;
7203     }
7204     case Instruction::GetElementPtr: {
7205       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7206       setInsertPointAfterBundle(E);
7207 
7208       Value *Op0 = vectorizeTree(E->getOperand(0));
7209 
7210       SmallVector<Value *> OpVecs;
7211       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7212         Value *OpVec = vectorizeTree(E->getOperand(J));
7213         OpVecs.push_back(OpVec);
7214       }
7215 
7216       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7217       if (Instruction *I = dyn_cast<Instruction>(V))
7218         V = propagateMetadata(I, E->Scalars);
7219 
7220       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7221       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7222       V = ShuffleBuilder.finalize(V);
7223 
7224       E->VectorizedValue = V;
7225       ++NumVectorInstructions;
7226 
7227       return V;
7228     }
7229     case Instruction::Call: {
7230       CallInst *CI = cast<CallInst>(VL0);
7231       setInsertPointAfterBundle(E);
7232 
7233       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7234       if (Function *FI = CI->getCalledFunction())
7235         IID = FI->getIntrinsicID();
7236 
7237       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7238 
7239       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7240       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7241                           VecCallCosts.first <= VecCallCosts.second;
7242 
7243       Value *ScalarArg = nullptr;
7244       std::vector<Value *> OpVecs;
7245       SmallVector<Type *, 2> TysForDecl =
7246           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7247       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7248         ValueList OpVL;
7249         // Some intrinsics have scalar arguments. This argument should not be
7250         // vectorized.
7251         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7252           CallInst *CEI = cast<CallInst>(VL0);
7253           ScalarArg = CEI->getArgOperand(j);
7254           OpVecs.push_back(CEI->getArgOperand(j));
7255           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7256             TysForDecl.push_back(ScalarArg->getType());
7257           continue;
7258         }
7259 
7260         Value *OpVec = vectorizeTree(E->getOperand(j));
7261         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7262         OpVecs.push_back(OpVec);
7263       }
7264 
7265       Function *CF;
7266       if (!UseIntrinsic) {
7267         VFShape Shape =
7268             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7269                                   VecTy->getNumElements())),
7270                          false /*HasGlobalPred*/);
7271         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7272       } else {
7273         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7274       }
7275 
7276       SmallVector<OperandBundleDef, 1> OpBundles;
7277       CI->getOperandBundlesAsDefs(OpBundles);
7278       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7279 
7280       // The scalar argument uses an in-tree scalar so we add the new vectorized
7281       // call to ExternalUses list to make sure that an extract will be
7282       // generated in the future.
7283       if (ScalarArg) {
7284         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7285           // Find which lane we need to extract.
7286           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7287           ExternalUses.push_back(
7288               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7289         }
7290       }
7291 
7292       propagateIRFlags(V, E->Scalars, VL0);
7293       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7294       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7295       V = ShuffleBuilder.finalize(V);
7296 
7297       E->VectorizedValue = V;
7298       ++NumVectorInstructions;
7299       return V;
7300     }
7301     case Instruction::ShuffleVector: {
7302       assert(E->isAltShuffle() &&
7303              ((Instruction::isBinaryOp(E->getOpcode()) &&
7304                Instruction::isBinaryOp(E->getAltOpcode())) ||
7305               (Instruction::isCast(E->getOpcode()) &&
7306                Instruction::isCast(E->getAltOpcode())) ||
7307               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7308              "Invalid Shuffle Vector Operand");
7309 
7310       Value *LHS = nullptr, *RHS = nullptr;
7311       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7312         setInsertPointAfterBundle(E);
7313         LHS = vectorizeTree(E->getOperand(0));
7314         RHS = vectorizeTree(E->getOperand(1));
7315       } else {
7316         setInsertPointAfterBundle(E);
7317         LHS = vectorizeTree(E->getOperand(0));
7318       }
7319 
7320       if (E->VectorizedValue) {
7321         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7322         return E->VectorizedValue;
7323       }
7324 
7325       Value *V0, *V1;
7326       if (Instruction::isBinaryOp(E->getOpcode())) {
7327         V0 = Builder.CreateBinOp(
7328             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7329         V1 = Builder.CreateBinOp(
7330             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7331       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7332         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7333         auto *AltCI = cast<CmpInst>(E->getAltOp());
7334         CmpInst::Predicate AltPred = AltCI->getPredicate();
7335         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7336       } else {
7337         V0 = Builder.CreateCast(
7338             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7339         V1 = Builder.CreateCast(
7340             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7341       }
7342       // Add V0 and V1 to later analysis to try to find and remove matching
7343       // instruction, if any.
7344       for (Value *V : {V0, V1}) {
7345         if (auto *I = dyn_cast<Instruction>(V)) {
7346           GatherShuffleSeq.insert(I);
7347           CSEBlocks.insert(I->getParent());
7348         }
7349       }
7350 
7351       // Create shuffle to take alternate operations from the vector.
7352       // Also, gather up main and alt scalar ops to propagate IR flags to
7353       // each vector operation.
7354       ValueList OpScalars, AltScalars;
7355       SmallVector<int> Mask;
7356       buildShuffleEntryMask(
7357           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7358           [E](Instruction *I) {
7359             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7360             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7361           },
7362           Mask, &OpScalars, &AltScalars);
7363 
7364       propagateIRFlags(V0, OpScalars);
7365       propagateIRFlags(V1, AltScalars);
7366 
7367       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7368       if (auto *I = dyn_cast<Instruction>(V)) {
7369         V = propagateMetadata(I, E->Scalars);
7370         GatherShuffleSeq.insert(I);
7371         CSEBlocks.insert(I->getParent());
7372       }
7373       V = ShuffleBuilder.finalize(V);
7374 
7375       E->VectorizedValue = V;
7376       ++NumVectorInstructions;
7377 
7378       return V;
7379     }
7380     default:
7381     llvm_unreachable("unknown inst");
7382   }
7383   return nullptr;
7384 }
7385 
7386 Value *BoUpSLP::vectorizeTree() {
7387   ExtraValueToDebugLocsMap ExternallyUsedValues;
7388   return vectorizeTree(ExternallyUsedValues);
7389 }
7390 
7391 Value *
7392 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7393   // All blocks must be scheduled before any instructions are inserted.
7394   for (auto &BSIter : BlocksSchedules) {
7395     scheduleBlock(BSIter.second.get());
7396   }
7397 
7398   Builder.SetInsertPoint(&F->getEntryBlock().front());
7399   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7400 
7401   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7402   // vectorized root. InstCombine will then rewrite the entire expression. We
7403   // sign extend the extracted values below.
7404   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7405   if (MinBWs.count(ScalarRoot)) {
7406     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7407       // If current instr is a phi and not the last phi, insert it after the
7408       // last phi node.
7409       if (isa<PHINode>(I))
7410         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7411       else
7412         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7413     }
7414     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7415     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7416     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7417     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7418     VectorizableTree[0]->VectorizedValue = Trunc;
7419   }
7420 
7421   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7422                     << " values .\n");
7423 
7424   // Extract all of the elements with the external uses.
7425   for (const auto &ExternalUse : ExternalUses) {
7426     Value *Scalar = ExternalUse.Scalar;
7427     llvm::User *User = ExternalUse.User;
7428 
7429     // Skip users that we already RAUW. This happens when one instruction
7430     // has multiple uses of the same value.
7431     if (User && !is_contained(Scalar->users(), User))
7432       continue;
7433     TreeEntry *E = getTreeEntry(Scalar);
7434     assert(E && "Invalid scalar");
7435     assert(E->State != TreeEntry::NeedToGather &&
7436            "Extracting from a gather list");
7437 
7438     Value *Vec = E->VectorizedValue;
7439     assert(Vec && "Can't find vectorizable value");
7440 
7441     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7442     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7443       if (Scalar->getType() != Vec->getType()) {
7444         Value *Ex;
7445         // "Reuse" the existing extract to improve final codegen.
7446         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7447           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7448                                             ES->getOperand(1));
7449         } else {
7450           Ex = Builder.CreateExtractElement(Vec, Lane);
7451         }
7452         // If necessary, sign-extend or zero-extend ScalarRoot
7453         // to the larger type.
7454         if (!MinBWs.count(ScalarRoot))
7455           return Ex;
7456         if (MinBWs[ScalarRoot].second)
7457           return Builder.CreateSExt(Ex, Scalar->getType());
7458         return Builder.CreateZExt(Ex, Scalar->getType());
7459       }
7460       assert(isa<FixedVectorType>(Scalar->getType()) &&
7461              isa<InsertElementInst>(Scalar) &&
7462              "In-tree scalar of vector type is not insertelement?");
7463       return Vec;
7464     };
7465     // If User == nullptr, the Scalar is used as extra arg. Generate
7466     // ExtractElement instruction and update the record for this scalar in
7467     // ExternallyUsedValues.
7468     if (!User) {
7469       assert(ExternallyUsedValues.count(Scalar) &&
7470              "Scalar with nullptr as an external user must be registered in "
7471              "ExternallyUsedValues map");
7472       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7473         Builder.SetInsertPoint(VecI->getParent(),
7474                                std::next(VecI->getIterator()));
7475       } else {
7476         Builder.SetInsertPoint(&F->getEntryBlock().front());
7477       }
7478       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7479       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7480       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7481       auto It = ExternallyUsedValues.find(Scalar);
7482       assert(It != ExternallyUsedValues.end() &&
7483              "Externally used scalar is not found in ExternallyUsedValues");
7484       NewInstLocs.append(It->second);
7485       ExternallyUsedValues.erase(Scalar);
7486       // Required to update internally referenced instructions.
7487       Scalar->replaceAllUsesWith(NewInst);
7488       continue;
7489     }
7490 
7491     // Generate extracts for out-of-tree users.
7492     // Find the insertion point for the extractelement lane.
7493     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7494       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7495         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7496           if (PH->getIncomingValue(i) == Scalar) {
7497             Instruction *IncomingTerminator =
7498                 PH->getIncomingBlock(i)->getTerminator();
7499             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7500               Builder.SetInsertPoint(VecI->getParent(),
7501                                      std::next(VecI->getIterator()));
7502             } else {
7503               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7504             }
7505             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7506             CSEBlocks.insert(PH->getIncomingBlock(i));
7507             PH->setOperand(i, NewInst);
7508           }
7509         }
7510       } else {
7511         Builder.SetInsertPoint(cast<Instruction>(User));
7512         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7513         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7514         User->replaceUsesOfWith(Scalar, NewInst);
7515       }
7516     } else {
7517       Builder.SetInsertPoint(&F->getEntryBlock().front());
7518       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7519       CSEBlocks.insert(&F->getEntryBlock());
7520       User->replaceUsesOfWith(Scalar, NewInst);
7521     }
7522 
7523     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7524   }
7525 
7526   // For each vectorized value:
7527   for (auto &TEPtr : VectorizableTree) {
7528     TreeEntry *Entry = TEPtr.get();
7529 
7530     // No need to handle users of gathered values.
7531     if (Entry->State == TreeEntry::NeedToGather)
7532       continue;
7533 
7534     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7535 
7536     // For each lane:
7537     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7538       Value *Scalar = Entry->Scalars[Lane];
7539 
7540 #ifndef NDEBUG
7541       Type *Ty = Scalar->getType();
7542       if (!Ty->isVoidTy()) {
7543         for (User *U : Scalar->users()) {
7544           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7545 
7546           // It is legal to delete users in the ignorelist.
7547           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7548                   (isa_and_nonnull<Instruction>(U) &&
7549                    isDeleted(cast<Instruction>(U)))) &&
7550                  "Deleting out-of-tree value");
7551         }
7552       }
7553 #endif
7554       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7555       eraseInstruction(cast<Instruction>(Scalar));
7556     }
7557   }
7558 
7559   Builder.ClearInsertionPoint();
7560   InstrElementSize.clear();
7561 
7562   return VectorizableTree[0]->VectorizedValue;
7563 }
7564 
7565 void BoUpSLP::optimizeGatherSequence() {
7566   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7567                     << " gather sequences instructions.\n");
7568   // LICM InsertElementInst sequences.
7569   for (Instruction *I : GatherShuffleSeq) {
7570     if (isDeleted(I))
7571       continue;
7572 
7573     // Check if this block is inside a loop.
7574     Loop *L = LI->getLoopFor(I->getParent());
7575     if (!L)
7576       continue;
7577 
7578     // Check if it has a preheader.
7579     BasicBlock *PreHeader = L->getLoopPreheader();
7580     if (!PreHeader)
7581       continue;
7582 
7583     // If the vector or the element that we insert into it are
7584     // instructions that are defined in this basic block then we can't
7585     // hoist this instruction.
7586     if (any_of(I->operands(), [L](Value *V) {
7587           auto *OpI = dyn_cast<Instruction>(V);
7588           return OpI && L->contains(OpI);
7589         }))
7590       continue;
7591 
7592     // We can hoist this instruction. Move it to the pre-header.
7593     I->moveBefore(PreHeader->getTerminator());
7594   }
7595 
7596   // Make a list of all reachable blocks in our CSE queue.
7597   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7598   CSEWorkList.reserve(CSEBlocks.size());
7599   for (BasicBlock *BB : CSEBlocks)
7600     if (DomTreeNode *N = DT->getNode(BB)) {
7601       assert(DT->isReachableFromEntry(N));
7602       CSEWorkList.push_back(N);
7603     }
7604 
7605   // Sort blocks by domination. This ensures we visit a block after all blocks
7606   // dominating it are visited.
7607   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7608     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7609            "Different nodes should have different DFS numbers");
7610     return A->getDFSNumIn() < B->getDFSNumIn();
7611   });
7612 
7613   // Less defined shuffles can be replaced by the more defined copies.
7614   // Between two shuffles one is less defined if it has the same vector operands
7615   // and its mask indeces are the same as in the first one or undefs. E.g.
7616   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7617   // poison, <0, 0, 0, 0>.
7618   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7619                                            SmallVectorImpl<int> &NewMask) {
7620     if (I1->getType() != I2->getType())
7621       return false;
7622     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7623     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7624     if (!SI1 || !SI2)
7625       return I1->isIdenticalTo(I2);
7626     if (SI1->isIdenticalTo(SI2))
7627       return true;
7628     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7629       if (SI1->getOperand(I) != SI2->getOperand(I))
7630         return false;
7631     // Check if the second instruction is more defined than the first one.
7632     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7633     ArrayRef<int> SM1 = SI1->getShuffleMask();
7634     // Count trailing undefs in the mask to check the final number of used
7635     // registers.
7636     unsigned LastUndefsCnt = 0;
7637     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7638       if (SM1[I] == UndefMaskElem)
7639         ++LastUndefsCnt;
7640       else
7641         LastUndefsCnt = 0;
7642       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7643           NewMask[I] != SM1[I])
7644         return false;
7645       if (NewMask[I] == UndefMaskElem)
7646         NewMask[I] = SM1[I];
7647     }
7648     // Check if the last undefs actually change the final number of used vector
7649     // registers.
7650     return SM1.size() - LastUndefsCnt > 1 &&
7651            TTI->getNumberOfParts(SI1->getType()) ==
7652                TTI->getNumberOfParts(
7653                    FixedVectorType::get(SI1->getType()->getElementType(),
7654                                         SM1.size() - LastUndefsCnt));
7655   };
7656   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7657   // instructions. TODO: We can further optimize this scan if we split the
7658   // instructions into different buckets based on the insert lane.
7659   SmallVector<Instruction *, 16> Visited;
7660   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7661     assert(*I &&
7662            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7663            "Worklist not sorted properly!");
7664     BasicBlock *BB = (*I)->getBlock();
7665     // For all instructions in blocks containing gather sequences:
7666     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7667       if (isDeleted(&In))
7668         continue;
7669       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7670           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7671         continue;
7672 
7673       // Check if we can replace this instruction with any of the
7674       // visited instructions.
7675       bool Replaced = false;
7676       for (Instruction *&V : Visited) {
7677         SmallVector<int> NewMask;
7678         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7679             DT->dominates(V->getParent(), In.getParent())) {
7680           In.replaceAllUsesWith(V);
7681           eraseInstruction(&In);
7682           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7683             if (!NewMask.empty())
7684               SI->setShuffleMask(NewMask);
7685           Replaced = true;
7686           break;
7687         }
7688         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7689             GatherShuffleSeq.contains(V) &&
7690             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7691             DT->dominates(In.getParent(), V->getParent())) {
7692           In.moveAfter(V);
7693           V->replaceAllUsesWith(&In);
7694           eraseInstruction(V);
7695           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7696             if (!NewMask.empty())
7697               SI->setShuffleMask(NewMask);
7698           V = &In;
7699           Replaced = true;
7700           break;
7701         }
7702       }
7703       if (!Replaced) {
7704         assert(!is_contained(Visited, &In));
7705         Visited.push_back(&In);
7706       }
7707     }
7708   }
7709   CSEBlocks.clear();
7710   GatherShuffleSeq.clear();
7711 }
7712 
7713 BoUpSLP::ScheduleData *
7714 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7715   ScheduleData *Bundle = nullptr;
7716   ScheduleData *PrevInBundle = nullptr;
7717   for (Value *V : VL) {
7718     if (doesNotNeedToBeScheduled(V))
7719       continue;
7720     ScheduleData *BundleMember = getScheduleData(V);
7721     assert(BundleMember &&
7722            "no ScheduleData for bundle member "
7723            "(maybe not in same basic block)");
7724     assert(BundleMember->isSchedulingEntity() &&
7725            "bundle member already part of other bundle");
7726     if (PrevInBundle) {
7727       PrevInBundle->NextInBundle = BundleMember;
7728     } else {
7729       Bundle = BundleMember;
7730     }
7731 
7732     // Group the instructions to a bundle.
7733     BundleMember->FirstInBundle = Bundle;
7734     PrevInBundle = BundleMember;
7735   }
7736   assert(Bundle && "Failed to find schedule bundle");
7737   return Bundle;
7738 }
7739 
7740 // Groups the instructions to a bundle (which is then a single scheduling entity)
7741 // and schedules instructions until the bundle gets ready.
7742 Optional<BoUpSLP::ScheduleData *>
7743 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7744                                             const InstructionsState &S) {
7745   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7746   // instructions.
7747   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7748       doesNotNeedToSchedule(VL))
7749     return nullptr;
7750 
7751   // Initialize the instruction bundle.
7752   Instruction *OldScheduleEnd = ScheduleEnd;
7753   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7754 
7755   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7756                                                          ScheduleData *Bundle) {
7757     // The scheduling region got new instructions at the lower end (or it is a
7758     // new region for the first bundle). This makes it necessary to
7759     // recalculate all dependencies.
7760     // It is seldom that this needs to be done a second time after adding the
7761     // initial bundle to the region.
7762     if (ScheduleEnd != OldScheduleEnd) {
7763       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7764         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7765       ReSchedule = true;
7766     }
7767     if (Bundle) {
7768       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7769                         << " in block " << BB->getName() << "\n");
7770       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7771     }
7772 
7773     if (ReSchedule) {
7774       resetSchedule();
7775       initialFillReadyList(ReadyInsts);
7776     }
7777 
7778     // Now try to schedule the new bundle or (if no bundle) just calculate
7779     // dependencies. As soon as the bundle is "ready" it means that there are no
7780     // cyclic dependencies and we can schedule it. Note that's important that we
7781     // don't "schedule" the bundle yet (see cancelScheduling).
7782     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7783            !ReadyInsts.empty()) {
7784       ScheduleData *Picked = ReadyInsts.pop_back_val();
7785       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7786              "must be ready to schedule");
7787       schedule(Picked, ReadyInsts);
7788     }
7789   };
7790 
7791   // Make sure that the scheduling region contains all
7792   // instructions of the bundle.
7793   for (Value *V : VL) {
7794     if (doesNotNeedToBeScheduled(V))
7795       continue;
7796     if (!extendSchedulingRegion(V, S)) {
7797       // If the scheduling region got new instructions at the lower end (or it
7798       // is a new region for the first bundle). This makes it necessary to
7799       // recalculate all dependencies.
7800       // Otherwise the compiler may crash trying to incorrectly calculate
7801       // dependencies and emit instruction in the wrong order at the actual
7802       // scheduling.
7803       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7804       return None;
7805     }
7806   }
7807 
7808   bool ReSchedule = false;
7809   for (Value *V : VL) {
7810     if (doesNotNeedToBeScheduled(V))
7811       continue;
7812     ScheduleData *BundleMember = getScheduleData(V);
7813     assert(BundleMember &&
7814            "no ScheduleData for bundle member (maybe not in same basic block)");
7815 
7816     // Make sure we don't leave the pieces of the bundle in the ready list when
7817     // whole bundle might not be ready.
7818     ReadyInsts.remove(BundleMember);
7819 
7820     if (!BundleMember->IsScheduled)
7821       continue;
7822     // A bundle member was scheduled as single instruction before and now
7823     // needs to be scheduled as part of the bundle. We just get rid of the
7824     // existing schedule.
7825     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7826                       << " was already scheduled\n");
7827     ReSchedule = true;
7828   }
7829 
7830   auto *Bundle = buildBundle(VL);
7831   TryScheduleBundleImpl(ReSchedule, Bundle);
7832   if (!Bundle->isReady()) {
7833     cancelScheduling(VL, S.OpValue);
7834     return None;
7835   }
7836   return Bundle;
7837 }
7838 
7839 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7840                                                 Value *OpValue) {
7841   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7842       doesNotNeedToSchedule(VL))
7843     return;
7844 
7845   if (doesNotNeedToBeScheduled(OpValue))
7846     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7847   ScheduleData *Bundle = getScheduleData(OpValue);
7848   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7849   assert(!Bundle->IsScheduled &&
7850          "Can't cancel bundle which is already scheduled");
7851   assert(Bundle->isSchedulingEntity() &&
7852          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7853          "tried to unbundle something which is not a bundle");
7854 
7855   // Remove the bundle from the ready list.
7856   if (Bundle->isReady())
7857     ReadyInsts.remove(Bundle);
7858 
7859   // Un-bundle: make single instructions out of the bundle.
7860   ScheduleData *BundleMember = Bundle;
7861   while (BundleMember) {
7862     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7863     BundleMember->FirstInBundle = BundleMember;
7864     ScheduleData *Next = BundleMember->NextInBundle;
7865     BundleMember->NextInBundle = nullptr;
7866     BundleMember->TE = nullptr;
7867     if (BundleMember->unscheduledDepsInBundle() == 0) {
7868       ReadyInsts.insert(BundleMember);
7869     }
7870     BundleMember = Next;
7871   }
7872 }
7873 
7874 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7875   // Allocate a new ScheduleData for the instruction.
7876   if (ChunkPos >= ChunkSize) {
7877     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7878     ChunkPos = 0;
7879   }
7880   return &(ScheduleDataChunks.back()[ChunkPos++]);
7881 }
7882 
7883 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7884                                                       const InstructionsState &S) {
7885   if (getScheduleData(V, isOneOf(S, V)))
7886     return true;
7887   Instruction *I = dyn_cast<Instruction>(V);
7888   assert(I && "bundle member must be an instruction");
7889   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7890          !doesNotNeedToBeScheduled(I) &&
7891          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7892          "be scheduled");
7893   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7894     ScheduleData *ISD = getScheduleData(I);
7895     if (!ISD)
7896       return false;
7897     assert(isInSchedulingRegion(ISD) &&
7898            "ScheduleData not in scheduling region");
7899     ScheduleData *SD = allocateScheduleDataChunks();
7900     SD->Inst = I;
7901     SD->init(SchedulingRegionID, S.OpValue);
7902     ExtraScheduleDataMap[I][S.OpValue] = SD;
7903     return true;
7904   };
7905   if (CheckScheduleForI(I))
7906     return true;
7907   if (!ScheduleStart) {
7908     // It's the first instruction in the new region.
7909     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7910     ScheduleStart = I;
7911     ScheduleEnd = I->getNextNode();
7912     if (isOneOf(S, I) != I)
7913       CheckScheduleForI(I);
7914     assert(ScheduleEnd && "tried to vectorize a terminator?");
7915     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7916     return true;
7917   }
7918   // Search up and down at the same time, because we don't know if the new
7919   // instruction is above or below the existing scheduling region.
7920   BasicBlock::reverse_iterator UpIter =
7921       ++ScheduleStart->getIterator().getReverse();
7922   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7923   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7924   BasicBlock::iterator LowerEnd = BB->end();
7925   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7926          &*DownIter != I) {
7927     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7928       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7929       return false;
7930     }
7931 
7932     ++UpIter;
7933     ++DownIter;
7934   }
7935   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7936     assert(I->getParent() == ScheduleStart->getParent() &&
7937            "Instruction is in wrong basic block.");
7938     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7939     ScheduleStart = I;
7940     if (isOneOf(S, I) != I)
7941       CheckScheduleForI(I);
7942     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7943                       << "\n");
7944     return true;
7945   }
7946   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7947          "Expected to reach top of the basic block or instruction down the "
7948          "lower end.");
7949   assert(I->getParent() == ScheduleEnd->getParent() &&
7950          "Instruction is in wrong basic block.");
7951   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7952                    nullptr);
7953   ScheduleEnd = I->getNextNode();
7954   if (isOneOf(S, I) != I)
7955     CheckScheduleForI(I);
7956   assert(ScheduleEnd && "tried to vectorize a terminator?");
7957   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7958   return true;
7959 }
7960 
7961 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7962                                                 Instruction *ToI,
7963                                                 ScheduleData *PrevLoadStore,
7964                                                 ScheduleData *NextLoadStore) {
7965   ScheduleData *CurrentLoadStore = PrevLoadStore;
7966   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7967     // No need to allocate data for non-schedulable instructions.
7968     if (doesNotNeedToBeScheduled(I))
7969       continue;
7970     ScheduleData *SD = ScheduleDataMap.lookup(I);
7971     if (!SD) {
7972       SD = allocateScheduleDataChunks();
7973       ScheduleDataMap[I] = SD;
7974       SD->Inst = I;
7975     }
7976     assert(!isInSchedulingRegion(SD) &&
7977            "new ScheduleData already in scheduling region");
7978     SD->init(SchedulingRegionID, I);
7979 
7980     if (I->mayReadOrWriteMemory() &&
7981         (!isa<IntrinsicInst>(I) ||
7982          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7983           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7984               Intrinsic::pseudoprobe))) {
7985       // Update the linked list of memory accessing instructions.
7986       if (CurrentLoadStore) {
7987         CurrentLoadStore->NextLoadStore = SD;
7988       } else {
7989         FirstLoadStoreInRegion = SD;
7990       }
7991       CurrentLoadStore = SD;
7992     }
7993   }
7994   if (NextLoadStore) {
7995     if (CurrentLoadStore)
7996       CurrentLoadStore->NextLoadStore = NextLoadStore;
7997   } else {
7998     LastLoadStoreInRegion = CurrentLoadStore;
7999   }
8000 }
8001 
8002 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8003                                                      bool InsertInReadyList,
8004                                                      BoUpSLP *SLP) {
8005   assert(SD->isSchedulingEntity());
8006 
8007   SmallVector<ScheduleData *, 10> WorkList;
8008   WorkList.push_back(SD);
8009 
8010   while (!WorkList.empty()) {
8011     ScheduleData *SD = WorkList.pop_back_val();
8012     for (ScheduleData *BundleMember = SD; BundleMember;
8013          BundleMember = BundleMember->NextInBundle) {
8014       assert(isInSchedulingRegion(BundleMember));
8015       if (BundleMember->hasValidDependencies())
8016         continue;
8017 
8018       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8019                  << "\n");
8020       BundleMember->Dependencies = 0;
8021       BundleMember->resetUnscheduledDeps();
8022 
8023       // Handle def-use chain dependencies.
8024       if (BundleMember->OpValue != BundleMember->Inst) {
8025         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8026           BundleMember->Dependencies++;
8027           ScheduleData *DestBundle = UseSD->FirstInBundle;
8028           if (!DestBundle->IsScheduled)
8029             BundleMember->incrementUnscheduledDeps(1);
8030           if (!DestBundle->hasValidDependencies())
8031             WorkList.push_back(DestBundle);
8032         }
8033       } else {
8034         for (User *U : BundleMember->Inst->users()) {
8035           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8036             BundleMember->Dependencies++;
8037             ScheduleData *DestBundle = UseSD->FirstInBundle;
8038             if (!DestBundle->IsScheduled)
8039               BundleMember->incrementUnscheduledDeps(1);
8040             if (!DestBundle->hasValidDependencies())
8041               WorkList.push_back(DestBundle);
8042           }
8043         }
8044       }
8045 
8046       // Handle the memory dependencies (if any).
8047       ScheduleData *DepDest = BundleMember->NextLoadStore;
8048       if (!DepDest)
8049         continue;
8050       Instruction *SrcInst = BundleMember->Inst;
8051       assert(SrcInst->mayReadOrWriteMemory() &&
8052              "NextLoadStore list for non memory effecting bundle?");
8053       MemoryLocation SrcLoc = getLocation(SrcInst);
8054       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8055       unsigned numAliased = 0;
8056       unsigned DistToSrc = 1;
8057 
8058       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8059         assert(isInSchedulingRegion(DepDest));
8060 
8061         // We have two limits to reduce the complexity:
8062         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8063         //    SLP->isAliased (which is the expensive part in this loop).
8064         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8065         //    the whole loop (even if the loop is fast, it's quadratic).
8066         //    It's important for the loop break condition (see below) to
8067         //    check this limit even between two read-only instructions.
8068         if (DistToSrc >= MaxMemDepDistance ||
8069             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8070              (numAliased >= AliasedCheckLimit ||
8071               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8072 
8073           // We increment the counter only if the locations are aliased
8074           // (instead of counting all alias checks). This gives a better
8075           // balance between reduced runtime and accurate dependencies.
8076           numAliased++;
8077 
8078           DepDest->MemoryDependencies.push_back(BundleMember);
8079           BundleMember->Dependencies++;
8080           ScheduleData *DestBundle = DepDest->FirstInBundle;
8081           if (!DestBundle->IsScheduled) {
8082             BundleMember->incrementUnscheduledDeps(1);
8083           }
8084           if (!DestBundle->hasValidDependencies()) {
8085             WorkList.push_back(DestBundle);
8086           }
8087         }
8088 
8089         // Example, explaining the loop break condition: Let's assume our
8090         // starting instruction is i0 and MaxMemDepDistance = 3.
8091         //
8092         //                      +--------v--v--v
8093         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8094         //             +--------^--^--^
8095         //
8096         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8097         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8098         // Previously we already added dependencies from i3 to i6,i7,i8
8099         // (because of MaxMemDepDistance). As we added a dependency from
8100         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8101         // and we can abort this loop at i6.
8102         if (DistToSrc >= 2 * MaxMemDepDistance)
8103           break;
8104         DistToSrc++;
8105       }
8106     }
8107     if (InsertInReadyList && SD->isReady()) {
8108       ReadyInsts.insert(SD);
8109       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8110                         << "\n");
8111     }
8112   }
8113 }
8114 
8115 void BoUpSLP::BlockScheduling::resetSchedule() {
8116   assert(ScheduleStart &&
8117          "tried to reset schedule on block which has not been scheduled");
8118   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8119     doForAllOpcodes(I, [&](ScheduleData *SD) {
8120       assert(isInSchedulingRegion(SD) &&
8121              "ScheduleData not in scheduling region");
8122       SD->IsScheduled = false;
8123       SD->resetUnscheduledDeps();
8124     });
8125   }
8126   ReadyInsts.clear();
8127 }
8128 
8129 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8130   if (!BS->ScheduleStart)
8131     return;
8132 
8133   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8134 
8135   BS->resetSchedule();
8136 
8137   // For the real scheduling we use a more sophisticated ready-list: it is
8138   // sorted by the original instruction location. This lets the final schedule
8139   // be as  close as possible to the original instruction order.
8140   // WARNING: This required for correctness in several cases:
8141   // * We must prevent reordering of potentially infinte loops inside
8142   //   readnone calls with following potentially faulting instructions.
8143   // * We must prevent reordering of allocas with stacksave intrinsic calls.
8144   // In both cases, we rely on two instructions which are both ready (per the
8145   // def-use and memory dependency subgraph) not to be reordered.
8146   struct ScheduleDataCompare {
8147     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8148       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8149     }
8150   };
8151   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8152 
8153   // Ensure that all dependency data is updated and fill the ready-list with
8154   // initial instructions.
8155   int Idx = 0;
8156   int NumToSchedule = 0;
8157   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8158        I = I->getNextNode()) {
8159     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8160       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8161       (void)SDTE;
8162       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8163               SD->isPartOfBundle() ==
8164                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8165              "scheduler and vectorizer bundle mismatch");
8166       SD->FirstInBundle->SchedulingPriority = Idx++;
8167       if (SD->isSchedulingEntity()) {
8168         BS->calculateDependencies(SD, false, this);
8169         NumToSchedule++;
8170       }
8171     });
8172   }
8173   BS->initialFillReadyList(ReadyInsts);
8174 
8175   Instruction *LastScheduledInst = BS->ScheduleEnd;
8176 
8177   // Do the "real" scheduling.
8178   while (!ReadyInsts.empty()) {
8179     ScheduleData *picked = *ReadyInsts.begin();
8180     ReadyInsts.erase(ReadyInsts.begin());
8181 
8182     // Move the scheduled instruction(s) to their dedicated places, if not
8183     // there yet.
8184     for (ScheduleData *BundleMember = picked; BundleMember;
8185          BundleMember = BundleMember->NextInBundle) {
8186       Instruction *pickedInst = BundleMember->Inst;
8187       if (pickedInst->getNextNode() != LastScheduledInst)
8188         pickedInst->moveBefore(LastScheduledInst);
8189       LastScheduledInst = pickedInst;
8190     }
8191 
8192     BS->schedule(picked, ReadyInsts);
8193     NumToSchedule--;
8194   }
8195   assert(NumToSchedule == 0 && "could not schedule all instructions");
8196 
8197   // Check that we didn't break any of our invariants.
8198 #ifdef EXPENSIVE_CHECKS
8199   BS->verify();
8200 #endif
8201 
8202 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8203   // Check that all schedulable entities got scheduled
8204   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8205     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8206       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8207         assert(SD->IsScheduled && "must be scheduled at this point");
8208       }
8209     });
8210   }
8211 #endif
8212 
8213   // Avoid duplicate scheduling of the block.
8214   BS->ScheduleStart = nullptr;
8215 }
8216 
8217 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8218   // If V is a store, just return the width of the stored value (or value
8219   // truncated just before storing) without traversing the expression tree.
8220   // This is the common case.
8221   if (auto *Store = dyn_cast<StoreInst>(V)) {
8222     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8223       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8224     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8225   }
8226 
8227   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8228     return getVectorElementSize(IEI->getOperand(1));
8229 
8230   auto E = InstrElementSize.find(V);
8231   if (E != InstrElementSize.end())
8232     return E->second;
8233 
8234   // If V is not a store, we can traverse the expression tree to find loads
8235   // that feed it. The type of the loaded value may indicate a more suitable
8236   // width than V's type. We want to base the vector element size on the width
8237   // of memory operations where possible.
8238   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8239   SmallPtrSet<Instruction *, 16> Visited;
8240   if (auto *I = dyn_cast<Instruction>(V)) {
8241     Worklist.emplace_back(I, I->getParent());
8242     Visited.insert(I);
8243   }
8244 
8245   // Traverse the expression tree in bottom-up order looking for loads. If we
8246   // encounter an instruction we don't yet handle, we give up.
8247   auto Width = 0u;
8248   while (!Worklist.empty()) {
8249     Instruction *I;
8250     BasicBlock *Parent;
8251     std::tie(I, Parent) = Worklist.pop_back_val();
8252 
8253     // We should only be looking at scalar instructions here. If the current
8254     // instruction has a vector type, skip.
8255     auto *Ty = I->getType();
8256     if (isa<VectorType>(Ty))
8257       continue;
8258 
8259     // If the current instruction is a load, update MaxWidth to reflect the
8260     // width of the loaded value.
8261     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8262         isa<ExtractValueInst>(I))
8263       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8264 
8265     // Otherwise, we need to visit the operands of the instruction. We only
8266     // handle the interesting cases from buildTree here. If an operand is an
8267     // instruction we haven't yet visited and from the same basic block as the
8268     // user or the use is a PHI node, we add it to the worklist.
8269     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8270              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8271              isa<UnaryOperator>(I)) {
8272       for (Use &U : I->operands())
8273         if (auto *J = dyn_cast<Instruction>(U.get()))
8274           if (Visited.insert(J).second &&
8275               (isa<PHINode>(I) || J->getParent() == Parent))
8276             Worklist.emplace_back(J, J->getParent());
8277     } else {
8278       break;
8279     }
8280   }
8281 
8282   // If we didn't encounter a memory access in the expression tree, or if we
8283   // gave up for some reason, just return the width of V. Otherwise, return the
8284   // maximum width we found.
8285   if (!Width) {
8286     if (auto *CI = dyn_cast<CmpInst>(V))
8287       V = CI->getOperand(0);
8288     Width = DL->getTypeSizeInBits(V->getType());
8289   }
8290 
8291   for (Instruction *I : Visited)
8292     InstrElementSize[I] = Width;
8293 
8294   return Width;
8295 }
8296 
8297 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8298 // smaller type with a truncation. We collect the values that will be demoted
8299 // in ToDemote and additional roots that require investigating in Roots.
8300 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8301                                   SmallVectorImpl<Value *> &ToDemote,
8302                                   SmallVectorImpl<Value *> &Roots) {
8303   // We can always demote constants.
8304   if (isa<Constant>(V)) {
8305     ToDemote.push_back(V);
8306     return true;
8307   }
8308 
8309   // If the value is not an instruction in the expression with only one use, it
8310   // cannot be demoted.
8311   auto *I = dyn_cast<Instruction>(V);
8312   if (!I || !I->hasOneUse() || !Expr.count(I))
8313     return false;
8314 
8315   switch (I->getOpcode()) {
8316 
8317   // We can always demote truncations and extensions. Since truncations can
8318   // seed additional demotion, we save the truncated value.
8319   case Instruction::Trunc:
8320     Roots.push_back(I->getOperand(0));
8321     break;
8322   case Instruction::ZExt:
8323   case Instruction::SExt:
8324     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8325         isa<InsertElementInst>(I->getOperand(0)))
8326       return false;
8327     break;
8328 
8329   // We can demote certain binary operations if we can demote both of their
8330   // operands.
8331   case Instruction::Add:
8332   case Instruction::Sub:
8333   case Instruction::Mul:
8334   case Instruction::And:
8335   case Instruction::Or:
8336   case Instruction::Xor:
8337     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8338         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8339       return false;
8340     break;
8341 
8342   // We can demote selects if we can demote their true and false values.
8343   case Instruction::Select: {
8344     SelectInst *SI = cast<SelectInst>(I);
8345     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8346         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8347       return false;
8348     break;
8349   }
8350 
8351   // We can demote phis if we can demote all their incoming operands. Note that
8352   // we don't need to worry about cycles since we ensure single use above.
8353   case Instruction::PHI: {
8354     PHINode *PN = cast<PHINode>(I);
8355     for (Value *IncValue : PN->incoming_values())
8356       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8357         return false;
8358     break;
8359   }
8360 
8361   // Otherwise, conservatively give up.
8362   default:
8363     return false;
8364   }
8365 
8366   // Record the value that we can demote.
8367   ToDemote.push_back(V);
8368   return true;
8369 }
8370 
8371 void BoUpSLP::computeMinimumValueSizes() {
8372   // If there are no external uses, the expression tree must be rooted by a
8373   // store. We can't demote in-memory values, so there is nothing to do here.
8374   if (ExternalUses.empty())
8375     return;
8376 
8377   // We only attempt to truncate integer expressions.
8378   auto &TreeRoot = VectorizableTree[0]->Scalars;
8379   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8380   if (!TreeRootIT)
8381     return;
8382 
8383   // If the expression is not rooted by a store, these roots should have
8384   // external uses. We will rely on InstCombine to rewrite the expression in
8385   // the narrower type. However, InstCombine only rewrites single-use values.
8386   // This means that if a tree entry other than a root is used externally, it
8387   // must have multiple uses and InstCombine will not rewrite it. The code
8388   // below ensures that only the roots are used externally.
8389   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8390   for (auto &EU : ExternalUses)
8391     if (!Expr.erase(EU.Scalar))
8392       return;
8393   if (!Expr.empty())
8394     return;
8395 
8396   // Collect the scalar values of the vectorizable expression. We will use this
8397   // context to determine which values can be demoted. If we see a truncation,
8398   // we mark it as seeding another demotion.
8399   for (auto &EntryPtr : VectorizableTree)
8400     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8401 
8402   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8403   // have a single external user that is not in the vectorizable tree.
8404   for (auto *Root : TreeRoot)
8405     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8406       return;
8407 
8408   // Conservatively determine if we can actually truncate the roots of the
8409   // expression. Collect the values that can be demoted in ToDemote and
8410   // additional roots that require investigating in Roots.
8411   SmallVector<Value *, 32> ToDemote;
8412   SmallVector<Value *, 4> Roots;
8413   for (auto *Root : TreeRoot)
8414     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8415       return;
8416 
8417   // The maximum bit width required to represent all the values that can be
8418   // demoted without loss of precision. It would be safe to truncate the roots
8419   // of the expression to this width.
8420   auto MaxBitWidth = 8u;
8421 
8422   // We first check if all the bits of the roots are demanded. If they're not,
8423   // we can truncate the roots to this narrower type.
8424   for (auto *Root : TreeRoot) {
8425     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8426     MaxBitWidth = std::max<unsigned>(
8427         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8428   }
8429 
8430   // True if the roots can be zero-extended back to their original type, rather
8431   // than sign-extended. We know that if the leading bits are not demanded, we
8432   // can safely zero-extend. So we initialize IsKnownPositive to True.
8433   bool IsKnownPositive = true;
8434 
8435   // If all the bits of the roots are demanded, we can try a little harder to
8436   // compute a narrower type. This can happen, for example, if the roots are
8437   // getelementptr indices. InstCombine promotes these indices to the pointer
8438   // width. Thus, all their bits are technically demanded even though the
8439   // address computation might be vectorized in a smaller type.
8440   //
8441   // We start by looking at each entry that can be demoted. We compute the
8442   // maximum bit width required to store the scalar by using ValueTracking to
8443   // compute the number of high-order bits we can truncate.
8444   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8445       llvm::all_of(TreeRoot, [](Value *R) {
8446         assert(R->hasOneUse() && "Root should have only one use!");
8447         return isa<GetElementPtrInst>(R->user_back());
8448       })) {
8449     MaxBitWidth = 8u;
8450 
8451     // Determine if the sign bit of all the roots is known to be zero. If not,
8452     // IsKnownPositive is set to False.
8453     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8454       KnownBits Known = computeKnownBits(R, *DL);
8455       return Known.isNonNegative();
8456     });
8457 
8458     // Determine the maximum number of bits required to store the scalar
8459     // values.
8460     for (auto *Scalar : ToDemote) {
8461       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8462       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8463       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8464     }
8465 
8466     // If we can't prove that the sign bit is zero, we must add one to the
8467     // maximum bit width to account for the unknown sign bit. This preserves
8468     // the existing sign bit so we can safely sign-extend the root back to the
8469     // original type. Otherwise, if we know the sign bit is zero, we will
8470     // zero-extend the root instead.
8471     //
8472     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8473     //        one to the maximum bit width will yield a larger-than-necessary
8474     //        type. In general, we need to add an extra bit only if we can't
8475     //        prove that the upper bit of the original type is equal to the
8476     //        upper bit of the proposed smaller type. If these two bits are the
8477     //        same (either zero or one) we know that sign-extending from the
8478     //        smaller type will result in the same value. Here, since we can't
8479     //        yet prove this, we are just making the proposed smaller type
8480     //        larger to ensure correctness.
8481     if (!IsKnownPositive)
8482       ++MaxBitWidth;
8483   }
8484 
8485   // Round MaxBitWidth up to the next power-of-two.
8486   if (!isPowerOf2_64(MaxBitWidth))
8487     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8488 
8489   // If the maximum bit width we compute is less than the with of the roots'
8490   // type, we can proceed with the narrowing. Otherwise, do nothing.
8491   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8492     return;
8493 
8494   // If we can truncate the root, we must collect additional values that might
8495   // be demoted as a result. That is, those seeded by truncations we will
8496   // modify.
8497   while (!Roots.empty())
8498     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8499 
8500   // Finally, map the values we can demote to the maximum bit with we computed.
8501   for (auto *Scalar : ToDemote)
8502     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8503 }
8504 
8505 namespace {
8506 
8507 /// The SLPVectorizer Pass.
8508 struct SLPVectorizer : public FunctionPass {
8509   SLPVectorizerPass Impl;
8510 
8511   /// Pass identification, replacement for typeid
8512   static char ID;
8513 
8514   explicit SLPVectorizer() : FunctionPass(ID) {
8515     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8516   }
8517 
8518   bool doInitialization(Module &M) override { return false; }
8519 
8520   bool runOnFunction(Function &F) override {
8521     if (skipFunction(F))
8522       return false;
8523 
8524     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8525     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8526     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8527     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8528     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8529     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8530     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8531     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8532     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8533     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8534 
8535     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8536   }
8537 
8538   void getAnalysisUsage(AnalysisUsage &AU) const override {
8539     FunctionPass::getAnalysisUsage(AU);
8540     AU.addRequired<AssumptionCacheTracker>();
8541     AU.addRequired<ScalarEvolutionWrapperPass>();
8542     AU.addRequired<AAResultsWrapperPass>();
8543     AU.addRequired<TargetTransformInfoWrapperPass>();
8544     AU.addRequired<LoopInfoWrapperPass>();
8545     AU.addRequired<DominatorTreeWrapperPass>();
8546     AU.addRequired<DemandedBitsWrapperPass>();
8547     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8548     AU.addRequired<InjectTLIMappingsLegacy>();
8549     AU.addPreserved<LoopInfoWrapperPass>();
8550     AU.addPreserved<DominatorTreeWrapperPass>();
8551     AU.addPreserved<AAResultsWrapperPass>();
8552     AU.addPreserved<GlobalsAAWrapperPass>();
8553     AU.setPreservesCFG();
8554   }
8555 };
8556 
8557 } // end anonymous namespace
8558 
8559 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8560   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8561   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8562   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8563   auto *AA = &AM.getResult<AAManager>(F);
8564   auto *LI = &AM.getResult<LoopAnalysis>(F);
8565   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8566   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8567   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8568   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8569 
8570   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8571   if (!Changed)
8572     return PreservedAnalyses::all();
8573 
8574   PreservedAnalyses PA;
8575   PA.preserveSet<CFGAnalyses>();
8576   return PA;
8577 }
8578 
8579 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8580                                 TargetTransformInfo *TTI_,
8581                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8582                                 LoopInfo *LI_, DominatorTree *DT_,
8583                                 AssumptionCache *AC_, DemandedBits *DB_,
8584                                 OptimizationRemarkEmitter *ORE_) {
8585   if (!RunSLPVectorization)
8586     return false;
8587   SE = SE_;
8588   TTI = TTI_;
8589   TLI = TLI_;
8590   AA = AA_;
8591   LI = LI_;
8592   DT = DT_;
8593   AC = AC_;
8594   DB = DB_;
8595   DL = &F.getParent()->getDataLayout();
8596 
8597   Stores.clear();
8598   GEPs.clear();
8599   bool Changed = false;
8600 
8601   // If the target claims to have no vector registers don't attempt
8602   // vectorization.
8603   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8604     LLVM_DEBUG(
8605         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8606     return false;
8607   }
8608 
8609   // Don't vectorize when the attribute NoImplicitFloat is used.
8610   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8611     return false;
8612 
8613   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8614 
8615   // Use the bottom up slp vectorizer to construct chains that start with
8616   // store instructions.
8617   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8618 
8619   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8620   // delete instructions.
8621 
8622   // Update DFS numbers now so that we can use them for ordering.
8623   DT->updateDFSNumbers();
8624 
8625   // Scan the blocks in the function in post order.
8626   for (auto BB : post_order(&F.getEntryBlock())) {
8627     collectSeedInstructions(BB);
8628 
8629     // Vectorize trees that end at stores.
8630     if (!Stores.empty()) {
8631       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8632                         << " underlying objects.\n");
8633       Changed |= vectorizeStoreChains(R);
8634     }
8635 
8636     // Vectorize trees that end at reductions.
8637     Changed |= vectorizeChainsInBlock(BB, R);
8638 
8639     // Vectorize the index computations of getelementptr instructions. This
8640     // is primarily intended to catch gather-like idioms ending at
8641     // non-consecutive loads.
8642     if (!GEPs.empty()) {
8643       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8644                         << " underlying objects.\n");
8645       Changed |= vectorizeGEPIndices(BB, R);
8646     }
8647   }
8648 
8649   if (Changed) {
8650     R.optimizeGatherSequence();
8651     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8652   }
8653   return Changed;
8654 }
8655 
8656 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8657                                             unsigned Idx) {
8658   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8659                     << "\n");
8660   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8661   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8662   unsigned VF = Chain.size();
8663 
8664   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8665     return false;
8666 
8667   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8668                     << "\n");
8669 
8670   R.buildTree(Chain);
8671   if (R.isTreeTinyAndNotFullyVectorizable())
8672     return false;
8673   if (R.isLoadCombineCandidate())
8674     return false;
8675   R.reorderTopToBottom();
8676   R.reorderBottomToTop();
8677   R.buildExternalUses();
8678 
8679   R.computeMinimumValueSizes();
8680 
8681   InstructionCost Cost = R.getTreeCost();
8682 
8683   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8684   if (Cost < -SLPCostThreshold) {
8685     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8686 
8687     using namespace ore;
8688 
8689     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8690                                         cast<StoreInst>(Chain[0]))
8691                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8692                      << " and with tree size "
8693                      << NV("TreeSize", R.getTreeSize()));
8694 
8695     R.vectorizeTree();
8696     return true;
8697   }
8698 
8699   return false;
8700 }
8701 
8702 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8703                                         BoUpSLP &R) {
8704   // We may run into multiple chains that merge into a single chain. We mark the
8705   // stores that we vectorized so that we don't visit the same store twice.
8706   BoUpSLP::ValueSet VectorizedStores;
8707   bool Changed = false;
8708 
8709   int E = Stores.size();
8710   SmallBitVector Tails(E, false);
8711   int MaxIter = MaxStoreLookup.getValue();
8712   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8713       E, std::make_pair(E, INT_MAX));
8714   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8715   int IterCnt;
8716   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8717                                   &CheckedPairs,
8718                                   &ConsecutiveChain](int K, int Idx) {
8719     if (IterCnt >= MaxIter)
8720       return true;
8721     if (CheckedPairs[Idx].test(K))
8722       return ConsecutiveChain[K].second == 1 &&
8723              ConsecutiveChain[K].first == Idx;
8724     ++IterCnt;
8725     CheckedPairs[Idx].set(K);
8726     CheckedPairs[K].set(Idx);
8727     Optional<int> Diff = getPointersDiff(
8728         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8729         Stores[Idx]->getValueOperand()->getType(),
8730         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8731     if (!Diff || *Diff == 0)
8732       return false;
8733     int Val = *Diff;
8734     if (Val < 0) {
8735       if (ConsecutiveChain[Idx].second > -Val) {
8736         Tails.set(K);
8737         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8738       }
8739       return false;
8740     }
8741     if (ConsecutiveChain[K].second <= Val)
8742       return false;
8743 
8744     Tails.set(Idx);
8745     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8746     return Val == 1;
8747   };
8748   // Do a quadratic search on all of the given stores in reverse order and find
8749   // all of the pairs of stores that follow each other.
8750   for (int Idx = E - 1; Idx >= 0; --Idx) {
8751     // If a store has multiple consecutive store candidates, search according
8752     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8753     // This is because usually pairing with immediate succeeding or preceding
8754     // candidate create the best chance to find slp vectorization opportunity.
8755     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8756     IterCnt = 0;
8757     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8758       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8759           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8760         break;
8761   }
8762 
8763   // Tracks if we tried to vectorize stores starting from the given tail
8764   // already.
8765   SmallBitVector TriedTails(E, false);
8766   // For stores that start but don't end a link in the chain:
8767   for (int Cnt = E; Cnt > 0; --Cnt) {
8768     int I = Cnt - 1;
8769     if (ConsecutiveChain[I].first == E || Tails.test(I))
8770       continue;
8771     // We found a store instr that starts a chain. Now follow the chain and try
8772     // to vectorize it.
8773     BoUpSLP::ValueList Operands;
8774     // Collect the chain into a list.
8775     while (I != E && !VectorizedStores.count(Stores[I])) {
8776       Operands.push_back(Stores[I]);
8777       Tails.set(I);
8778       if (ConsecutiveChain[I].second != 1) {
8779         // Mark the new end in the chain and go back, if required. It might be
8780         // required if the original stores come in reversed order, for example.
8781         if (ConsecutiveChain[I].first != E &&
8782             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8783             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8784           TriedTails.set(I);
8785           Tails.reset(ConsecutiveChain[I].first);
8786           if (Cnt < ConsecutiveChain[I].first + 2)
8787             Cnt = ConsecutiveChain[I].first + 2;
8788         }
8789         break;
8790       }
8791       // Move to the next value in the chain.
8792       I = ConsecutiveChain[I].first;
8793     }
8794     assert(!Operands.empty() && "Expected non-empty list of stores.");
8795 
8796     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8797     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8798     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8799 
8800     unsigned MinVF = R.getMinVF(EltSize);
8801     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8802                               MaxElts);
8803 
8804     // FIXME: Is division-by-2 the correct step? Should we assert that the
8805     // register size is a power-of-2?
8806     unsigned StartIdx = 0;
8807     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8808       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8809         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8810         if (!VectorizedStores.count(Slice.front()) &&
8811             !VectorizedStores.count(Slice.back()) &&
8812             vectorizeStoreChain(Slice, R, Cnt)) {
8813           // Mark the vectorized stores so that we don't vectorize them again.
8814           VectorizedStores.insert(Slice.begin(), Slice.end());
8815           Changed = true;
8816           // If we vectorized initial block, no need to try to vectorize it
8817           // again.
8818           if (Cnt == StartIdx)
8819             StartIdx += Size;
8820           Cnt += Size;
8821           continue;
8822         }
8823         ++Cnt;
8824       }
8825       // Check if the whole array was vectorized already - exit.
8826       if (StartIdx >= Operands.size())
8827         break;
8828     }
8829   }
8830 
8831   return Changed;
8832 }
8833 
8834 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8835   // Initialize the collections. We will make a single pass over the block.
8836   Stores.clear();
8837   GEPs.clear();
8838 
8839   // Visit the store and getelementptr instructions in BB and organize them in
8840   // Stores and GEPs according to the underlying objects of their pointer
8841   // operands.
8842   for (Instruction &I : *BB) {
8843     // Ignore store instructions that are volatile or have a pointer operand
8844     // that doesn't point to a scalar type.
8845     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8846       if (!SI->isSimple())
8847         continue;
8848       if (!isValidElementType(SI->getValueOperand()->getType()))
8849         continue;
8850       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8851     }
8852 
8853     // Ignore getelementptr instructions that have more than one index, a
8854     // constant index, or a pointer operand that doesn't point to a scalar
8855     // type.
8856     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8857       auto Idx = GEP->idx_begin()->get();
8858       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8859         continue;
8860       if (!isValidElementType(Idx->getType()))
8861         continue;
8862       if (GEP->getType()->isVectorTy())
8863         continue;
8864       GEPs[GEP->getPointerOperand()].push_back(GEP);
8865     }
8866   }
8867 }
8868 
8869 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8870   if (!A || !B)
8871     return false;
8872   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8873     return false;
8874   Value *VL[] = {A, B};
8875   return tryToVectorizeList(VL, R);
8876 }
8877 
8878 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8879                                            bool LimitForRegisterSize) {
8880   if (VL.size() < 2)
8881     return false;
8882 
8883   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8884                     << VL.size() << ".\n");
8885 
8886   // Check that all of the parts are instructions of the same type,
8887   // we permit an alternate opcode via InstructionsState.
8888   InstructionsState S = getSameOpcode(VL);
8889   if (!S.getOpcode())
8890     return false;
8891 
8892   Instruction *I0 = cast<Instruction>(S.OpValue);
8893   // Make sure invalid types (including vector type) are rejected before
8894   // determining vectorization factor for scalar instructions.
8895   for (Value *V : VL) {
8896     Type *Ty = V->getType();
8897     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8898       // NOTE: the following will give user internal llvm type name, which may
8899       // not be useful.
8900       R.getORE()->emit([&]() {
8901         std::string type_str;
8902         llvm::raw_string_ostream rso(type_str);
8903         Ty->print(rso);
8904         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8905                << "Cannot SLP vectorize list: type "
8906                << rso.str() + " is unsupported by vectorizer";
8907       });
8908       return false;
8909     }
8910   }
8911 
8912   unsigned Sz = R.getVectorElementSize(I0);
8913   unsigned MinVF = R.getMinVF(Sz);
8914   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8915   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8916   if (MaxVF < 2) {
8917     R.getORE()->emit([&]() {
8918       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8919              << "Cannot SLP vectorize list: vectorization factor "
8920              << "less than 2 is not supported";
8921     });
8922     return false;
8923   }
8924 
8925   bool Changed = false;
8926   bool CandidateFound = false;
8927   InstructionCost MinCost = SLPCostThreshold.getValue();
8928   Type *ScalarTy = VL[0]->getType();
8929   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8930     ScalarTy = IE->getOperand(1)->getType();
8931 
8932   unsigned NextInst = 0, MaxInst = VL.size();
8933   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8934     // No actual vectorization should happen, if number of parts is the same as
8935     // provided vectorization factor (i.e. the scalar type is used for vector
8936     // code during codegen).
8937     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8938     if (TTI->getNumberOfParts(VecTy) == VF)
8939       continue;
8940     for (unsigned I = NextInst; I < MaxInst; ++I) {
8941       unsigned OpsWidth = 0;
8942 
8943       if (I + VF > MaxInst)
8944         OpsWidth = MaxInst - I;
8945       else
8946         OpsWidth = VF;
8947 
8948       if (!isPowerOf2_32(OpsWidth))
8949         continue;
8950 
8951       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8952           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8953         break;
8954 
8955       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8956       // Check that a previous iteration of this loop did not delete the Value.
8957       if (llvm::any_of(Ops, [&R](Value *V) {
8958             auto *I = dyn_cast<Instruction>(V);
8959             return I && R.isDeleted(I);
8960           }))
8961         continue;
8962 
8963       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8964                         << "\n");
8965 
8966       R.buildTree(Ops);
8967       if (R.isTreeTinyAndNotFullyVectorizable())
8968         continue;
8969       R.reorderTopToBottom();
8970       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8971       R.buildExternalUses();
8972 
8973       R.computeMinimumValueSizes();
8974       InstructionCost Cost = R.getTreeCost();
8975       CandidateFound = true;
8976       MinCost = std::min(MinCost, Cost);
8977 
8978       if (Cost < -SLPCostThreshold) {
8979         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8980         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8981                                                     cast<Instruction>(Ops[0]))
8982                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8983                                  << " and with tree size "
8984                                  << ore::NV("TreeSize", R.getTreeSize()));
8985 
8986         R.vectorizeTree();
8987         // Move to the next bundle.
8988         I += VF - 1;
8989         NextInst = I + 1;
8990         Changed = true;
8991       }
8992     }
8993   }
8994 
8995   if (!Changed && CandidateFound) {
8996     R.getORE()->emit([&]() {
8997       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8998              << "List vectorization was possible but not beneficial with cost "
8999              << ore::NV("Cost", MinCost) << " >= "
9000              << ore::NV("Treshold", -SLPCostThreshold);
9001     });
9002   } else if (!Changed) {
9003     R.getORE()->emit([&]() {
9004       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9005              << "Cannot SLP vectorize list: vectorization was impossible"
9006              << " with available vectorization factors";
9007     });
9008   }
9009   return Changed;
9010 }
9011 
9012 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9013   if (!I)
9014     return false;
9015 
9016   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9017     return false;
9018 
9019   Value *P = I->getParent();
9020 
9021   // Vectorize in current basic block only.
9022   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9023   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9024   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9025     return false;
9026 
9027   // Try to vectorize V.
9028   if (tryToVectorizePair(Op0, Op1, R))
9029     return true;
9030 
9031   auto *A = dyn_cast<BinaryOperator>(Op0);
9032   auto *B = dyn_cast<BinaryOperator>(Op1);
9033   // Try to skip B.
9034   if (B && B->hasOneUse()) {
9035     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9036     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9037     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9038       return true;
9039     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9040       return true;
9041   }
9042 
9043   // Try to skip A.
9044   if (A && A->hasOneUse()) {
9045     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9046     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9047     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9048       return true;
9049     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9050       return true;
9051   }
9052   return false;
9053 }
9054 
9055 namespace {
9056 
9057 /// Model horizontal reductions.
9058 ///
9059 /// A horizontal reduction is a tree of reduction instructions that has values
9060 /// that can be put into a vector as its leaves. For example:
9061 ///
9062 /// mul mul mul mul
9063 ///  \  /    \  /
9064 ///   +       +
9065 ///    \     /
9066 ///       +
9067 /// This tree has "mul" as its leaf values and "+" as its reduction
9068 /// instructions. A reduction can feed into a store or a binary operation
9069 /// feeding a phi.
9070 ///    ...
9071 ///    \  /
9072 ///     +
9073 ///     |
9074 ///  phi +=
9075 ///
9076 ///  Or:
9077 ///    ...
9078 ///    \  /
9079 ///     +
9080 ///     |
9081 ///   *p =
9082 ///
9083 class HorizontalReduction {
9084   using ReductionOpsType = SmallVector<Value *, 16>;
9085   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9086   ReductionOpsListType ReductionOps;
9087   SmallVector<Value *, 32> ReducedVals;
9088   // Use map vector to make stable output.
9089   MapVector<Instruction *, Value *> ExtraArgs;
9090   WeakTrackingVH ReductionRoot;
9091   /// The type of reduction operation.
9092   RecurKind RdxKind;
9093 
9094   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9095 
9096   static bool isCmpSelMinMax(Instruction *I) {
9097     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9098            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9099   }
9100 
9101   // And/or are potentially poison-safe logical patterns like:
9102   // select x, y, false
9103   // select x, true, y
9104   static bool isBoolLogicOp(Instruction *I) {
9105     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9106            match(I, m_LogicalOr(m_Value(), m_Value()));
9107   }
9108 
9109   /// Checks if instruction is associative and can be vectorized.
9110   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9111     if (Kind == RecurKind::None)
9112       return false;
9113 
9114     // Integer ops that map to select instructions or intrinsics are fine.
9115     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9116         isBoolLogicOp(I))
9117       return true;
9118 
9119     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9120       // FP min/max are associative except for NaN and -0.0. We do not
9121       // have to rule out -0.0 here because the intrinsic semantics do not
9122       // specify a fixed result for it.
9123       return I->getFastMathFlags().noNaNs();
9124     }
9125 
9126     return I->isAssociative();
9127   }
9128 
9129   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9130     // Poison-safe 'or' takes the form: select X, true, Y
9131     // To make that work with the normal operand processing, we skip the
9132     // true value operand.
9133     // TODO: Change the code and data structures to handle this without a hack.
9134     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9135       return I->getOperand(2);
9136     return I->getOperand(Index);
9137   }
9138 
9139   /// Checks if the ParentStackElem.first should be marked as a reduction
9140   /// operation with an extra argument or as extra argument itself.
9141   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9142                     Value *ExtraArg) {
9143     if (ExtraArgs.count(ParentStackElem.first)) {
9144       ExtraArgs[ParentStackElem.first] = nullptr;
9145       // We ran into something like:
9146       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9147       // The whole ParentStackElem.first should be considered as an extra value
9148       // in this case.
9149       // Do not perform analysis of remaining operands of ParentStackElem.first
9150       // instruction, this whole instruction is an extra argument.
9151       ParentStackElem.second = INVALID_OPERAND_INDEX;
9152     } else {
9153       // We ran into something like:
9154       // ParentStackElem.first += ... + ExtraArg + ...
9155       ExtraArgs[ParentStackElem.first] = ExtraArg;
9156     }
9157   }
9158 
9159   /// Creates reduction operation with the current opcode.
9160   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9161                          Value *RHS, const Twine &Name, bool UseSelect) {
9162     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9163     switch (Kind) {
9164     case RecurKind::Or:
9165       if (UseSelect &&
9166           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9167         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9168       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9169                                  Name);
9170     case RecurKind::And:
9171       if (UseSelect &&
9172           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9173         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9174       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9175                                  Name);
9176     case RecurKind::Add:
9177     case RecurKind::Mul:
9178     case RecurKind::Xor:
9179     case RecurKind::FAdd:
9180     case RecurKind::FMul:
9181       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9182                                  Name);
9183     case RecurKind::FMax:
9184       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9185     case RecurKind::FMin:
9186       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9187     case RecurKind::SMax:
9188       if (UseSelect) {
9189         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9190         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9191       }
9192       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9193     case RecurKind::SMin:
9194       if (UseSelect) {
9195         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9196         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9197       }
9198       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9199     case RecurKind::UMax:
9200       if (UseSelect) {
9201         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9202         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9203       }
9204       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9205     case RecurKind::UMin:
9206       if (UseSelect) {
9207         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9208         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9209       }
9210       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9211     default:
9212       llvm_unreachable("Unknown reduction operation.");
9213     }
9214   }
9215 
9216   /// Creates reduction operation with the current opcode with the IR flags
9217   /// from \p ReductionOps.
9218   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9219                          Value *RHS, const Twine &Name,
9220                          const ReductionOpsListType &ReductionOps) {
9221     bool UseSelect = ReductionOps.size() == 2 ||
9222                      // Logical or/and.
9223                      (ReductionOps.size() == 1 &&
9224                       isa<SelectInst>(ReductionOps.front().front()));
9225     assert((!UseSelect || ReductionOps.size() != 2 ||
9226             isa<SelectInst>(ReductionOps[1][0])) &&
9227            "Expected cmp + select pairs for reduction");
9228     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9229     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9230       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9231         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9232         propagateIRFlags(Op, ReductionOps[1]);
9233         return Op;
9234       }
9235     }
9236     propagateIRFlags(Op, ReductionOps[0]);
9237     return Op;
9238   }
9239 
9240   /// Creates reduction operation with the current opcode with the IR flags
9241   /// from \p I.
9242   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9243                          Value *RHS, const Twine &Name, Instruction *I) {
9244     auto *SelI = dyn_cast<SelectInst>(I);
9245     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9246     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9247       if (auto *Sel = dyn_cast<SelectInst>(Op))
9248         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9249     }
9250     propagateIRFlags(Op, I);
9251     return Op;
9252   }
9253 
9254   static RecurKind getRdxKind(Instruction *I) {
9255     assert(I && "Expected instruction for reduction matching");
9256     if (match(I, m_Add(m_Value(), m_Value())))
9257       return RecurKind::Add;
9258     if (match(I, m_Mul(m_Value(), m_Value())))
9259       return RecurKind::Mul;
9260     if (match(I, m_And(m_Value(), m_Value())) ||
9261         match(I, m_LogicalAnd(m_Value(), m_Value())))
9262       return RecurKind::And;
9263     if (match(I, m_Or(m_Value(), m_Value())) ||
9264         match(I, m_LogicalOr(m_Value(), m_Value())))
9265       return RecurKind::Or;
9266     if (match(I, m_Xor(m_Value(), m_Value())))
9267       return RecurKind::Xor;
9268     if (match(I, m_FAdd(m_Value(), m_Value())))
9269       return RecurKind::FAdd;
9270     if (match(I, m_FMul(m_Value(), m_Value())))
9271       return RecurKind::FMul;
9272 
9273     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9274       return RecurKind::FMax;
9275     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9276       return RecurKind::FMin;
9277 
9278     // This matches either cmp+select or intrinsics. SLP is expected to handle
9279     // either form.
9280     // TODO: If we are canonicalizing to intrinsics, we can remove several
9281     //       special-case paths that deal with selects.
9282     if (match(I, m_SMax(m_Value(), m_Value())))
9283       return RecurKind::SMax;
9284     if (match(I, m_SMin(m_Value(), m_Value())))
9285       return RecurKind::SMin;
9286     if (match(I, m_UMax(m_Value(), m_Value())))
9287       return RecurKind::UMax;
9288     if (match(I, m_UMin(m_Value(), m_Value())))
9289       return RecurKind::UMin;
9290 
9291     if (auto *Select = dyn_cast<SelectInst>(I)) {
9292       // Try harder: look for min/max pattern based on instructions producing
9293       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9294       // During the intermediate stages of SLP, it's very common to have
9295       // pattern like this (since optimizeGatherSequence is run only once
9296       // at the end):
9297       // %1 = extractelement <2 x i32> %a, i32 0
9298       // %2 = extractelement <2 x i32> %a, i32 1
9299       // %cond = icmp sgt i32 %1, %2
9300       // %3 = extractelement <2 x i32> %a, i32 0
9301       // %4 = extractelement <2 x i32> %a, i32 1
9302       // %select = select i1 %cond, i32 %3, i32 %4
9303       CmpInst::Predicate Pred;
9304       Instruction *L1;
9305       Instruction *L2;
9306 
9307       Value *LHS = Select->getTrueValue();
9308       Value *RHS = Select->getFalseValue();
9309       Value *Cond = Select->getCondition();
9310 
9311       // TODO: Support inverse predicates.
9312       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9313         if (!isa<ExtractElementInst>(RHS) ||
9314             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9315           return RecurKind::None;
9316       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9317         if (!isa<ExtractElementInst>(LHS) ||
9318             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9319           return RecurKind::None;
9320       } else {
9321         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9322           return RecurKind::None;
9323         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9324             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9325             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9326           return RecurKind::None;
9327       }
9328 
9329       switch (Pred) {
9330       default:
9331         return RecurKind::None;
9332       case CmpInst::ICMP_SGT:
9333       case CmpInst::ICMP_SGE:
9334         return RecurKind::SMax;
9335       case CmpInst::ICMP_SLT:
9336       case CmpInst::ICMP_SLE:
9337         return RecurKind::SMin;
9338       case CmpInst::ICMP_UGT:
9339       case CmpInst::ICMP_UGE:
9340         return RecurKind::UMax;
9341       case CmpInst::ICMP_ULT:
9342       case CmpInst::ICMP_ULE:
9343         return RecurKind::UMin;
9344       }
9345     }
9346     return RecurKind::None;
9347   }
9348 
9349   /// Get the index of the first operand.
9350   static unsigned getFirstOperandIndex(Instruction *I) {
9351     return isCmpSelMinMax(I) ? 1 : 0;
9352   }
9353 
9354   /// Total number of operands in the reduction operation.
9355   static unsigned getNumberOfOperands(Instruction *I) {
9356     return isCmpSelMinMax(I) ? 3 : 2;
9357   }
9358 
9359   /// Checks if the instruction is in basic block \p BB.
9360   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9361   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9362     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9363       auto *Sel = cast<SelectInst>(I);
9364       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9365       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9366     }
9367     return I->getParent() == BB;
9368   }
9369 
9370   /// Expected number of uses for reduction operations/reduced values.
9371   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9372     if (IsCmpSelMinMax) {
9373       // SelectInst must be used twice while the condition op must have single
9374       // use only.
9375       if (auto *Sel = dyn_cast<SelectInst>(I))
9376         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9377       return I->hasNUses(2);
9378     }
9379 
9380     // Arithmetic reduction operation must be used once only.
9381     return I->hasOneUse();
9382   }
9383 
9384   /// Initializes the list of reduction operations.
9385   void initReductionOps(Instruction *I) {
9386     if (isCmpSelMinMax(I))
9387       ReductionOps.assign(2, ReductionOpsType());
9388     else
9389       ReductionOps.assign(1, ReductionOpsType());
9390   }
9391 
9392   /// Add all reduction operations for the reduction instruction \p I.
9393   void addReductionOps(Instruction *I) {
9394     if (isCmpSelMinMax(I)) {
9395       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9396       ReductionOps[1].emplace_back(I);
9397     } else {
9398       ReductionOps[0].emplace_back(I);
9399     }
9400   }
9401 
9402   static Value *getLHS(RecurKind Kind, Instruction *I) {
9403     if (Kind == RecurKind::None)
9404       return nullptr;
9405     return I->getOperand(getFirstOperandIndex(I));
9406   }
9407   static Value *getRHS(RecurKind Kind, Instruction *I) {
9408     if (Kind == RecurKind::None)
9409       return nullptr;
9410     return I->getOperand(getFirstOperandIndex(I) + 1);
9411   }
9412 
9413 public:
9414   HorizontalReduction() = default;
9415 
9416   /// Try to find a reduction tree.
9417   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9418     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9419            "Phi needs to use the binary operator");
9420     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9421             isa<IntrinsicInst>(Inst)) &&
9422            "Expected binop, select, or intrinsic for reduction matching");
9423     RdxKind = getRdxKind(Inst);
9424 
9425     // We could have a initial reductions that is not an add.
9426     //  r *= v1 + v2 + v3 + v4
9427     // In such a case start looking for a tree rooted in the first '+'.
9428     if (Phi) {
9429       if (getLHS(RdxKind, Inst) == Phi) {
9430         Phi = nullptr;
9431         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9432         if (!Inst)
9433           return false;
9434         RdxKind = getRdxKind(Inst);
9435       } else if (getRHS(RdxKind, Inst) == Phi) {
9436         Phi = nullptr;
9437         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9438         if (!Inst)
9439           return false;
9440         RdxKind = getRdxKind(Inst);
9441       }
9442     }
9443 
9444     if (!isVectorizable(RdxKind, Inst))
9445       return false;
9446 
9447     // Analyze "regular" integer/FP types for reductions - no target-specific
9448     // types or pointers.
9449     Type *Ty = Inst->getType();
9450     if (!isValidElementType(Ty) || Ty->isPointerTy())
9451       return false;
9452 
9453     // Though the ultimate reduction may have multiple uses, its condition must
9454     // have only single use.
9455     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9456       if (!Sel->getCondition()->hasOneUse())
9457         return false;
9458 
9459     ReductionRoot = Inst;
9460 
9461     // The opcode for leaf values that we perform a reduction on.
9462     // For example: load(x) + load(y) + load(z) + fptoui(w)
9463     // The leaf opcode for 'w' does not match, so we don't include it as a
9464     // potential candidate for the reduction.
9465     unsigned LeafOpcode = 0;
9466 
9467     // Post-order traverse the reduction tree starting at Inst. We only handle
9468     // true trees containing binary operators or selects.
9469     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9470     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9471     initReductionOps(Inst);
9472     while (!Stack.empty()) {
9473       Instruction *TreeN = Stack.back().first;
9474       unsigned EdgeToVisit = Stack.back().second++;
9475       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9476       bool IsReducedValue = TreeRdxKind != RdxKind;
9477 
9478       // Postorder visit.
9479       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9480         if (IsReducedValue)
9481           ReducedVals.push_back(TreeN);
9482         else {
9483           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9484           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9485             // Check if TreeN is an extra argument of its parent operation.
9486             if (Stack.size() <= 1) {
9487               // TreeN can't be an extra argument as it is a root reduction
9488               // operation.
9489               return false;
9490             }
9491             // Yes, TreeN is an extra argument, do not add it to a list of
9492             // reduction operations.
9493             // Stack[Stack.size() - 2] always points to the parent operation.
9494             markExtraArg(Stack[Stack.size() - 2], TreeN);
9495             ExtraArgs.erase(TreeN);
9496           } else
9497             addReductionOps(TreeN);
9498         }
9499         // Retract.
9500         Stack.pop_back();
9501         continue;
9502       }
9503 
9504       // Visit operands.
9505       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9506       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9507       if (!EdgeInst) {
9508         // Edge value is not a reduction instruction or a leaf instruction.
9509         // (It may be a constant, function argument, or something else.)
9510         markExtraArg(Stack.back(), EdgeVal);
9511         continue;
9512       }
9513       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9514       // Continue analysis if the next operand is a reduction operation or
9515       // (possibly) a leaf value. If the leaf value opcode is not set,
9516       // the first met operation != reduction operation is considered as the
9517       // leaf opcode.
9518       // Only handle trees in the current basic block.
9519       // Each tree node needs to have minimal number of users except for the
9520       // ultimate reduction.
9521       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9522       if (EdgeInst != Phi && EdgeInst != Inst &&
9523           hasSameParent(EdgeInst, Inst->getParent()) &&
9524           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9525           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9526         if (IsRdxInst) {
9527           // We need to be able to reassociate the reduction operations.
9528           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9529             // I is an extra argument for TreeN (its parent operation).
9530             markExtraArg(Stack.back(), EdgeInst);
9531             continue;
9532           }
9533         } else if (!LeafOpcode) {
9534           LeafOpcode = EdgeInst->getOpcode();
9535         }
9536         Stack.push_back(
9537             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9538         continue;
9539       }
9540       // I is an extra argument for TreeN (its parent operation).
9541       markExtraArg(Stack.back(), EdgeInst);
9542     }
9543     return true;
9544   }
9545 
9546   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9547   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9548     // If there are a sufficient number of reduction values, reduce
9549     // to a nearby power-of-2. We can safely generate oversized
9550     // vectors and rely on the backend to split them to legal sizes.
9551     unsigned NumReducedVals = ReducedVals.size();
9552     if (NumReducedVals < 4)
9553       return nullptr;
9554 
9555     // Intersect the fast-math-flags from all reduction operations.
9556     FastMathFlags RdxFMF;
9557     RdxFMF.set();
9558     for (ReductionOpsType &RdxOp : ReductionOps) {
9559       for (Value *RdxVal : RdxOp) {
9560         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9561           RdxFMF &= FPMO->getFastMathFlags();
9562       }
9563     }
9564 
9565     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9566     Builder.setFastMathFlags(RdxFMF);
9567 
9568     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9569     // The same extra argument may be used several times, so log each attempt
9570     // to use it.
9571     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9572       assert(Pair.first && "DebugLoc must be set.");
9573       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9574     }
9575 
9576     // The compare instruction of a min/max is the insertion point for new
9577     // instructions and may be replaced with a new compare instruction.
9578     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9579       assert(isa<SelectInst>(RdxRootInst) &&
9580              "Expected min/max reduction to have select root instruction");
9581       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9582       assert(isa<Instruction>(ScalarCond) &&
9583              "Expected min/max reduction to have compare condition");
9584       return cast<Instruction>(ScalarCond);
9585     };
9586 
9587     // The reduction root is used as the insertion point for new instructions,
9588     // so set it as externally used to prevent it from being deleted.
9589     ExternallyUsedValues[ReductionRoot];
9590     SmallVector<Value *, 16> IgnoreList;
9591     for (ReductionOpsType &RdxOp : ReductionOps)
9592       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9593 
9594     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9595     if (NumReducedVals > ReduxWidth) {
9596       // In the loop below, we are building a tree based on a window of
9597       // 'ReduxWidth' values.
9598       // If the operands of those values have common traits (compare predicate,
9599       // constant operand, etc), then we want to group those together to
9600       // minimize the cost of the reduction.
9601 
9602       // TODO: This should be extended to count common operands for
9603       //       compares and binops.
9604 
9605       // Step 1: Count the number of times each compare predicate occurs.
9606       SmallDenseMap<unsigned, unsigned> PredCountMap;
9607       for (Value *RdxVal : ReducedVals) {
9608         CmpInst::Predicate Pred;
9609         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9610           ++PredCountMap[Pred];
9611       }
9612       // Step 2: Sort the values so the most common predicates come first.
9613       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9614         CmpInst::Predicate PredA, PredB;
9615         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9616             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9617           return PredCountMap[PredA] > PredCountMap[PredB];
9618         }
9619         return false;
9620       });
9621     }
9622 
9623     Value *VectorizedTree = nullptr;
9624     unsigned i = 0;
9625     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9626       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9627       V.buildTree(VL, IgnoreList);
9628       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9629         break;
9630       if (V.isLoadCombineReductionCandidate(RdxKind))
9631         break;
9632       V.reorderTopToBottom();
9633       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9634       V.buildExternalUses(ExternallyUsedValues);
9635 
9636       // For a poison-safe boolean logic reduction, do not replace select
9637       // instructions with logic ops. All reduced values will be frozen (see
9638       // below) to prevent leaking poison.
9639       if (isa<SelectInst>(ReductionRoot) &&
9640           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9641           NumReducedVals != ReduxWidth)
9642         break;
9643 
9644       V.computeMinimumValueSizes();
9645 
9646       // Estimate cost.
9647       InstructionCost TreeCost =
9648           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9649       InstructionCost ReductionCost =
9650           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9651       InstructionCost Cost = TreeCost + ReductionCost;
9652       if (!Cost.isValid()) {
9653         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9654         return nullptr;
9655       }
9656       if (Cost >= -SLPCostThreshold) {
9657         V.getORE()->emit([&]() {
9658           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9659                                           cast<Instruction>(VL[0]))
9660                  << "Vectorizing horizontal reduction is possible"
9661                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9662                  << " and threshold "
9663                  << ore::NV("Threshold", -SLPCostThreshold);
9664         });
9665         break;
9666       }
9667 
9668       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9669                         << Cost << ". (HorRdx)\n");
9670       V.getORE()->emit([&]() {
9671         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9672                                   cast<Instruction>(VL[0]))
9673                << "Vectorized horizontal reduction with cost "
9674                << ore::NV("Cost", Cost) << " and with tree size "
9675                << ore::NV("TreeSize", V.getTreeSize());
9676       });
9677 
9678       // Vectorize a tree.
9679       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9680       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9681 
9682       // Emit a reduction. If the root is a select (min/max idiom), the insert
9683       // point is the compare condition of that select.
9684       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9685       if (isCmpSelMinMax(RdxRootInst))
9686         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9687       else
9688         Builder.SetInsertPoint(RdxRootInst);
9689 
9690       // To prevent poison from leaking across what used to be sequential, safe,
9691       // scalar boolean logic operations, the reduction operand must be frozen.
9692       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9693         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9694 
9695       Value *ReducedSubTree =
9696           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9697 
9698       if (!VectorizedTree) {
9699         // Initialize the final value in the reduction.
9700         VectorizedTree = ReducedSubTree;
9701       } else {
9702         // Update the final value in the reduction.
9703         Builder.SetCurrentDebugLocation(Loc);
9704         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9705                                   ReducedSubTree, "op.rdx", ReductionOps);
9706       }
9707       i += ReduxWidth;
9708       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9709     }
9710 
9711     if (VectorizedTree) {
9712       // Finish the reduction.
9713       for (; i < NumReducedVals; ++i) {
9714         auto *I = cast<Instruction>(ReducedVals[i]);
9715         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9716         VectorizedTree =
9717             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9718       }
9719       for (auto &Pair : ExternallyUsedValues) {
9720         // Add each externally used value to the final reduction.
9721         for (auto *I : Pair.second) {
9722           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9723           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9724                                     Pair.first, "op.extra", I);
9725         }
9726       }
9727 
9728       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9729 
9730       // Mark all scalar reduction ops for deletion, they are replaced by the
9731       // vector reductions.
9732       V.eraseInstructions(IgnoreList);
9733     }
9734     return VectorizedTree;
9735   }
9736 
9737   unsigned numReductionValues() const { return ReducedVals.size(); }
9738 
9739 private:
9740   /// Calculate the cost of a reduction.
9741   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9742                                    Value *FirstReducedVal, unsigned ReduxWidth,
9743                                    FastMathFlags FMF) {
9744     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9745     Type *ScalarTy = FirstReducedVal->getType();
9746     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9747     InstructionCost VectorCost, ScalarCost;
9748     switch (RdxKind) {
9749     case RecurKind::Add:
9750     case RecurKind::Mul:
9751     case RecurKind::Or:
9752     case RecurKind::And:
9753     case RecurKind::Xor:
9754     case RecurKind::FAdd:
9755     case RecurKind::FMul: {
9756       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9757       VectorCost =
9758           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9759       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9760       break;
9761     }
9762     case RecurKind::FMax:
9763     case RecurKind::FMin: {
9764       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9765       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9766       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9767                                                /*IsUnsigned=*/false, CostKind);
9768       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9769       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9770                                            SclCondTy, RdxPred, CostKind) +
9771                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9772                                            SclCondTy, RdxPred, CostKind);
9773       break;
9774     }
9775     case RecurKind::SMax:
9776     case RecurKind::SMin:
9777     case RecurKind::UMax:
9778     case RecurKind::UMin: {
9779       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9780       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9781       bool IsUnsigned =
9782           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9783       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9784                                                CostKind);
9785       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9786       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9787                                            SclCondTy, RdxPred, CostKind) +
9788                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9789                                            SclCondTy, RdxPred, CostKind);
9790       break;
9791     }
9792     default:
9793       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9794     }
9795 
9796     // Scalar cost is repeated for N-1 elements.
9797     ScalarCost *= (ReduxWidth - 1);
9798     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9799                       << " for reduction that starts with " << *FirstReducedVal
9800                       << " (It is a splitting reduction)\n");
9801     return VectorCost - ScalarCost;
9802   }
9803 
9804   /// Emit a horizontal reduction of the vectorized value.
9805   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9806                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9807     assert(VectorizedValue && "Need to have a vectorized tree node");
9808     assert(isPowerOf2_32(ReduxWidth) &&
9809            "We only handle power-of-two reductions for now");
9810     assert(RdxKind != RecurKind::FMulAdd &&
9811            "A call to the llvm.fmuladd intrinsic is not handled yet");
9812 
9813     ++NumVectorInstructions;
9814     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9815   }
9816 };
9817 
9818 } // end anonymous namespace
9819 
9820 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9821   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9822     return cast<FixedVectorType>(IE->getType())->getNumElements();
9823 
9824   unsigned AggregateSize = 1;
9825   auto *IV = cast<InsertValueInst>(InsertInst);
9826   Type *CurrentType = IV->getType();
9827   do {
9828     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9829       for (auto *Elt : ST->elements())
9830         if (Elt != ST->getElementType(0)) // check homogeneity
9831           return None;
9832       AggregateSize *= ST->getNumElements();
9833       CurrentType = ST->getElementType(0);
9834     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9835       AggregateSize *= AT->getNumElements();
9836       CurrentType = AT->getElementType();
9837     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9838       AggregateSize *= VT->getNumElements();
9839       return AggregateSize;
9840     } else if (CurrentType->isSingleValueType()) {
9841       return AggregateSize;
9842     } else {
9843       return None;
9844     }
9845   } while (true);
9846 }
9847 
9848 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9849                                    TargetTransformInfo *TTI,
9850                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9851                                    SmallVectorImpl<Value *> &InsertElts,
9852                                    unsigned OperandOffset) {
9853   do {
9854     Value *InsertedOperand = LastInsertInst->getOperand(1);
9855     Optional<unsigned> OperandIndex =
9856         getInsertIndex(LastInsertInst, OperandOffset);
9857     if (!OperandIndex)
9858       return;
9859     if (isa<InsertElementInst>(InsertedOperand) ||
9860         isa<InsertValueInst>(InsertedOperand)) {
9861       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9862                              BuildVectorOpds, InsertElts, *OperandIndex);
9863 
9864     } else {
9865       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9866       InsertElts[*OperandIndex] = LastInsertInst;
9867     }
9868     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9869   } while (LastInsertInst != nullptr &&
9870            (isa<InsertValueInst>(LastInsertInst) ||
9871             isa<InsertElementInst>(LastInsertInst)) &&
9872            LastInsertInst->hasOneUse());
9873 }
9874 
9875 /// Recognize construction of vectors like
9876 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9877 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9878 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9879 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9880 ///  starting from the last insertelement or insertvalue instruction.
9881 ///
9882 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9883 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9884 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9885 ///
9886 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9887 ///
9888 /// \return true if it matches.
9889 static bool findBuildAggregate(Instruction *LastInsertInst,
9890                                TargetTransformInfo *TTI,
9891                                SmallVectorImpl<Value *> &BuildVectorOpds,
9892                                SmallVectorImpl<Value *> &InsertElts) {
9893 
9894   assert((isa<InsertElementInst>(LastInsertInst) ||
9895           isa<InsertValueInst>(LastInsertInst)) &&
9896          "Expected insertelement or insertvalue instruction!");
9897 
9898   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9899          "Expected empty result vectors!");
9900 
9901   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9902   if (!AggregateSize)
9903     return false;
9904   BuildVectorOpds.resize(*AggregateSize);
9905   InsertElts.resize(*AggregateSize);
9906 
9907   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9908   llvm::erase_value(BuildVectorOpds, nullptr);
9909   llvm::erase_value(InsertElts, nullptr);
9910   if (BuildVectorOpds.size() >= 2)
9911     return true;
9912 
9913   return false;
9914 }
9915 
9916 /// Try and get a reduction value from a phi node.
9917 ///
9918 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9919 /// if they come from either \p ParentBB or a containing loop latch.
9920 ///
9921 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9922 /// if not possible.
9923 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9924                                 BasicBlock *ParentBB, LoopInfo *LI) {
9925   // There are situations where the reduction value is not dominated by the
9926   // reduction phi. Vectorizing such cases has been reported to cause
9927   // miscompiles. See PR25787.
9928   auto DominatedReduxValue = [&](Value *R) {
9929     return isa<Instruction>(R) &&
9930            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9931   };
9932 
9933   Value *Rdx = nullptr;
9934 
9935   // Return the incoming value if it comes from the same BB as the phi node.
9936   if (P->getIncomingBlock(0) == ParentBB) {
9937     Rdx = P->getIncomingValue(0);
9938   } else if (P->getIncomingBlock(1) == ParentBB) {
9939     Rdx = P->getIncomingValue(1);
9940   }
9941 
9942   if (Rdx && DominatedReduxValue(Rdx))
9943     return Rdx;
9944 
9945   // Otherwise, check whether we have a loop latch to look at.
9946   Loop *BBL = LI->getLoopFor(ParentBB);
9947   if (!BBL)
9948     return nullptr;
9949   BasicBlock *BBLatch = BBL->getLoopLatch();
9950   if (!BBLatch)
9951     return nullptr;
9952 
9953   // There is a loop latch, return the incoming value if it comes from
9954   // that. This reduction pattern occasionally turns up.
9955   if (P->getIncomingBlock(0) == BBLatch) {
9956     Rdx = P->getIncomingValue(0);
9957   } else if (P->getIncomingBlock(1) == BBLatch) {
9958     Rdx = P->getIncomingValue(1);
9959   }
9960 
9961   if (Rdx && DominatedReduxValue(Rdx))
9962     return Rdx;
9963 
9964   return nullptr;
9965 }
9966 
9967 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9968   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9969     return true;
9970   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9971     return true;
9972   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9973     return true;
9974   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9975     return true;
9976   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9977     return true;
9978   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9979     return true;
9980   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9981     return true;
9982   return false;
9983 }
9984 
9985 /// Attempt to reduce a horizontal reduction.
9986 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9987 /// with reduction operators \a Root (or one of its operands) in a basic block
9988 /// \a BB, then check if it can be done. If horizontal reduction is not found
9989 /// and root instruction is a binary operation, vectorization of the operands is
9990 /// attempted.
9991 /// \returns true if a horizontal reduction was matched and reduced or operands
9992 /// of one of the binary instruction were vectorized.
9993 /// \returns false if a horizontal reduction was not matched (or not possible)
9994 /// or no vectorization of any binary operation feeding \a Root instruction was
9995 /// performed.
9996 static bool tryToVectorizeHorReductionOrInstOperands(
9997     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9998     TargetTransformInfo *TTI,
9999     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10000   if (!ShouldVectorizeHor)
10001     return false;
10002 
10003   if (!Root)
10004     return false;
10005 
10006   if (Root->getParent() != BB || isa<PHINode>(Root))
10007     return false;
10008   // Start analysis starting from Root instruction. If horizontal reduction is
10009   // found, try to vectorize it. If it is not a horizontal reduction or
10010   // vectorization is not possible or not effective, and currently analyzed
10011   // instruction is a binary operation, try to vectorize the operands, using
10012   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10013   // the same procedure considering each operand as a possible root of the
10014   // horizontal reduction.
10015   // Interrupt the process if the Root instruction itself was vectorized or all
10016   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10017   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10018   // CmpInsts so we can skip extra attempts in
10019   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10020   std::queue<std::pair<Instruction *, unsigned>> Stack;
10021   Stack.emplace(Root, 0);
10022   SmallPtrSet<Value *, 8> VisitedInstrs;
10023   SmallVector<WeakTrackingVH> PostponedInsts;
10024   bool Res = false;
10025   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10026                                      Value *&B1) -> Value * {
10027     bool IsBinop = matchRdxBop(Inst, B0, B1);
10028     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10029     if (IsBinop || IsSelect) {
10030       HorizontalReduction HorRdx;
10031       if (HorRdx.matchAssociativeReduction(P, Inst))
10032         return HorRdx.tryToReduce(R, TTI);
10033     }
10034     return nullptr;
10035   };
10036   while (!Stack.empty()) {
10037     Instruction *Inst;
10038     unsigned Level;
10039     std::tie(Inst, Level) = Stack.front();
10040     Stack.pop();
10041     // Do not try to analyze instruction that has already been vectorized.
10042     // This may happen when we vectorize instruction operands on a previous
10043     // iteration while stack was populated before that happened.
10044     if (R.isDeleted(Inst))
10045       continue;
10046     Value *B0 = nullptr, *B1 = nullptr;
10047     if (Value *V = TryToReduce(Inst, B0, B1)) {
10048       Res = true;
10049       // Set P to nullptr to avoid re-analysis of phi node in
10050       // matchAssociativeReduction function unless this is the root node.
10051       P = nullptr;
10052       if (auto *I = dyn_cast<Instruction>(V)) {
10053         // Try to find another reduction.
10054         Stack.emplace(I, Level);
10055         continue;
10056       }
10057     } else {
10058       bool IsBinop = B0 && B1;
10059       if (P && IsBinop) {
10060         Inst = dyn_cast<Instruction>(B0);
10061         if (Inst == P)
10062           Inst = dyn_cast<Instruction>(B1);
10063         if (!Inst) {
10064           // Set P to nullptr to avoid re-analysis of phi node in
10065           // matchAssociativeReduction function unless this is the root node.
10066           P = nullptr;
10067           continue;
10068         }
10069       }
10070       // Set P to nullptr to avoid re-analysis of phi node in
10071       // matchAssociativeReduction function unless this is the root node.
10072       P = nullptr;
10073       // Do not try to vectorize CmpInst operands, this is done separately.
10074       // Final attempt for binop args vectorization should happen after the loop
10075       // to try to find reductions.
10076       if (!isa<CmpInst>(Inst))
10077         PostponedInsts.push_back(Inst);
10078     }
10079 
10080     // Try to vectorize operands.
10081     // Continue analysis for the instruction from the same basic block only to
10082     // save compile time.
10083     if (++Level < RecursionMaxDepth)
10084       for (auto *Op : Inst->operand_values())
10085         if (VisitedInstrs.insert(Op).second)
10086           if (auto *I = dyn_cast<Instruction>(Op))
10087             // Do not try to vectorize CmpInst operands,  this is done
10088             // separately.
10089             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10090                 I->getParent() == BB)
10091               Stack.emplace(I, Level);
10092   }
10093   // Try to vectorized binops where reductions were not found.
10094   for (Value *V : PostponedInsts)
10095     if (auto *Inst = dyn_cast<Instruction>(V))
10096       if (!R.isDeleted(Inst))
10097         Res |= Vectorize(Inst, R);
10098   return Res;
10099 }
10100 
10101 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10102                                                  BasicBlock *BB, BoUpSLP &R,
10103                                                  TargetTransformInfo *TTI) {
10104   auto *I = dyn_cast_or_null<Instruction>(V);
10105   if (!I)
10106     return false;
10107 
10108   if (!isa<BinaryOperator>(I))
10109     P = nullptr;
10110   // Try to match and vectorize a horizontal reduction.
10111   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10112     return tryToVectorize(I, R);
10113   };
10114   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10115                                                   ExtraVectorization);
10116 }
10117 
10118 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10119                                                  BasicBlock *BB, BoUpSLP &R) {
10120   const DataLayout &DL = BB->getModule()->getDataLayout();
10121   if (!R.canMapToVector(IVI->getType(), DL))
10122     return false;
10123 
10124   SmallVector<Value *, 16> BuildVectorOpds;
10125   SmallVector<Value *, 16> BuildVectorInsts;
10126   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10127     return false;
10128 
10129   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10130   // Aggregate value is unlikely to be processed in vector register.
10131   return tryToVectorizeList(BuildVectorOpds, R);
10132 }
10133 
10134 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10135                                                    BasicBlock *BB, BoUpSLP &R) {
10136   SmallVector<Value *, 16> BuildVectorInsts;
10137   SmallVector<Value *, 16> BuildVectorOpds;
10138   SmallVector<int> Mask;
10139   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10140       (llvm::all_of(
10141            BuildVectorOpds,
10142            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10143        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10144     return false;
10145 
10146   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10147   return tryToVectorizeList(BuildVectorInsts, R);
10148 }
10149 
10150 template <typename T>
10151 static bool
10152 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10153                        function_ref<unsigned(T *)> Limit,
10154                        function_ref<bool(T *, T *)> Comparator,
10155                        function_ref<bool(T *, T *)> AreCompatible,
10156                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10157                        bool LimitForRegisterSize) {
10158   bool Changed = false;
10159   // Sort by type, parent, operands.
10160   stable_sort(Incoming, Comparator);
10161 
10162   // Try to vectorize elements base on their type.
10163   SmallVector<T *> Candidates;
10164   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10165     // Look for the next elements with the same type, parent and operand
10166     // kinds.
10167     auto *SameTypeIt = IncIt;
10168     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10169       ++SameTypeIt;
10170 
10171     // Try to vectorize them.
10172     unsigned NumElts = (SameTypeIt - IncIt);
10173     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10174                       << NumElts << ")\n");
10175     // The vectorization is a 3-state attempt:
10176     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10177     // size of maximal register at first.
10178     // 2. Try to vectorize remaining instructions with the same type, if
10179     // possible. This may result in the better vectorization results rather than
10180     // if we try just to vectorize instructions with the same/alternate opcodes.
10181     // 3. Final attempt to try to vectorize all instructions with the
10182     // same/alternate ops only, this may result in some extra final
10183     // vectorization.
10184     if (NumElts > 1 &&
10185         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10186       // Success start over because instructions might have been changed.
10187       Changed = true;
10188     } else if (NumElts < Limit(*IncIt) &&
10189                (Candidates.empty() ||
10190                 Candidates.front()->getType() == (*IncIt)->getType())) {
10191       Candidates.append(IncIt, std::next(IncIt, NumElts));
10192     }
10193     // Final attempt to vectorize instructions with the same types.
10194     if (Candidates.size() > 1 &&
10195         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10196       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10197         // Success start over because instructions might have been changed.
10198         Changed = true;
10199       } else if (LimitForRegisterSize) {
10200         // Try to vectorize using small vectors.
10201         for (auto *It = Candidates.begin(), *End = Candidates.end();
10202              It != End;) {
10203           auto *SameTypeIt = It;
10204           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10205             ++SameTypeIt;
10206           unsigned NumElts = (SameTypeIt - It);
10207           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10208                                             /*LimitForRegisterSize=*/false))
10209             Changed = true;
10210           It = SameTypeIt;
10211         }
10212       }
10213       Candidates.clear();
10214     }
10215 
10216     // Start over at the next instruction of a different type (or the end).
10217     IncIt = SameTypeIt;
10218   }
10219   return Changed;
10220 }
10221 
10222 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10223 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10224 /// operands. If IsCompatibility is false, function implements strict weak
10225 /// ordering relation between two cmp instructions, returning true if the first
10226 /// instruction is "less" than the second, i.e. its predicate is less than the
10227 /// predicate of the second or the operands IDs are less than the operands IDs
10228 /// of the second cmp instruction.
10229 template <bool IsCompatibility>
10230 static bool compareCmp(Value *V, Value *V2,
10231                        function_ref<bool(Instruction *)> IsDeleted) {
10232   auto *CI1 = cast<CmpInst>(V);
10233   auto *CI2 = cast<CmpInst>(V2);
10234   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10235     return false;
10236   if (CI1->getOperand(0)->getType()->getTypeID() <
10237       CI2->getOperand(0)->getType()->getTypeID())
10238     return !IsCompatibility;
10239   if (CI1->getOperand(0)->getType()->getTypeID() >
10240       CI2->getOperand(0)->getType()->getTypeID())
10241     return false;
10242   CmpInst::Predicate Pred1 = CI1->getPredicate();
10243   CmpInst::Predicate Pred2 = CI2->getPredicate();
10244   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10245   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10246   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10247   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10248   if (BasePred1 < BasePred2)
10249     return !IsCompatibility;
10250   if (BasePred1 > BasePred2)
10251     return false;
10252   // Compare operands.
10253   bool LEPreds = Pred1 <= Pred2;
10254   bool GEPreds = Pred1 >= Pred2;
10255   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10256     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10257     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10258     if (Op1->getValueID() < Op2->getValueID())
10259       return !IsCompatibility;
10260     if (Op1->getValueID() > Op2->getValueID())
10261       return false;
10262     if (auto *I1 = dyn_cast<Instruction>(Op1))
10263       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10264         if (I1->getParent() != I2->getParent())
10265           return false;
10266         InstructionsState S = getSameOpcode({I1, I2});
10267         if (S.getOpcode())
10268           continue;
10269         return false;
10270       }
10271   }
10272   return IsCompatibility;
10273 }
10274 
10275 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10276     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10277     bool AtTerminator) {
10278   bool OpsChanged = false;
10279   SmallVector<Instruction *, 4> PostponedCmps;
10280   for (auto *I : reverse(Instructions)) {
10281     if (R.isDeleted(I))
10282       continue;
10283     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10284       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10285     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10286       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10287     else if (isa<CmpInst>(I))
10288       PostponedCmps.push_back(I);
10289   }
10290   if (AtTerminator) {
10291     // Try to find reductions first.
10292     for (Instruction *I : PostponedCmps) {
10293       if (R.isDeleted(I))
10294         continue;
10295       for (Value *Op : I->operands())
10296         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10297     }
10298     // Try to vectorize operands as vector bundles.
10299     for (Instruction *I : PostponedCmps) {
10300       if (R.isDeleted(I))
10301         continue;
10302       OpsChanged |= tryToVectorize(I, R);
10303     }
10304     // Try to vectorize list of compares.
10305     // Sort by type, compare predicate, etc.
10306     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10307       return compareCmp<false>(V, V2,
10308                                [&R](Instruction *I) { return R.isDeleted(I); });
10309     };
10310 
10311     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10312       if (V1 == V2)
10313         return true;
10314       return compareCmp<true>(V1, V2,
10315                               [&R](Instruction *I) { return R.isDeleted(I); });
10316     };
10317     auto Limit = [&R](Value *V) {
10318       unsigned EltSize = R.getVectorElementSize(V);
10319       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10320     };
10321 
10322     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10323     OpsChanged |= tryToVectorizeSequence<Value>(
10324         Vals, Limit, CompareSorter, AreCompatibleCompares,
10325         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10326           // Exclude possible reductions from other blocks.
10327           bool ArePossiblyReducedInOtherBlock =
10328               any_of(Candidates, [](Value *V) {
10329                 return any_of(V->users(), [V](User *U) {
10330                   return isa<SelectInst>(U) &&
10331                          cast<SelectInst>(U)->getParent() !=
10332                              cast<Instruction>(V)->getParent();
10333                 });
10334               });
10335           if (ArePossiblyReducedInOtherBlock)
10336             return false;
10337           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10338         },
10339         /*LimitForRegisterSize=*/true);
10340     Instructions.clear();
10341   } else {
10342     // Insert in reverse order since the PostponedCmps vector was filled in
10343     // reverse order.
10344     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10345   }
10346   return OpsChanged;
10347 }
10348 
10349 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10350   bool Changed = false;
10351   SmallVector<Value *, 4> Incoming;
10352   SmallPtrSet<Value *, 16> VisitedInstrs;
10353   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10354   // node. Allows better to identify the chains that can be vectorized in the
10355   // better way.
10356   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10357   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10358     assert(isValidElementType(V1->getType()) &&
10359            isValidElementType(V2->getType()) &&
10360            "Expected vectorizable types only.");
10361     // It is fine to compare type IDs here, since we expect only vectorizable
10362     // types, like ints, floats and pointers, we don't care about other type.
10363     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10364       return true;
10365     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10366       return false;
10367     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10368     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10369     if (Opcodes1.size() < Opcodes2.size())
10370       return true;
10371     if (Opcodes1.size() > Opcodes2.size())
10372       return false;
10373     Optional<bool> ConstOrder;
10374     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10375       // Undefs are compatible with any other value.
10376       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10377         if (!ConstOrder)
10378           ConstOrder =
10379               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10380         continue;
10381       }
10382       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10383         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10384           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10385           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10386           if (!NodeI1)
10387             return NodeI2 != nullptr;
10388           if (!NodeI2)
10389             return false;
10390           assert((NodeI1 == NodeI2) ==
10391                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10392                  "Different nodes should have different DFS numbers");
10393           if (NodeI1 != NodeI2)
10394             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10395           InstructionsState S = getSameOpcode({I1, I2});
10396           if (S.getOpcode())
10397             continue;
10398           return I1->getOpcode() < I2->getOpcode();
10399         }
10400       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10401         if (!ConstOrder)
10402           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10403         continue;
10404       }
10405       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10406         return true;
10407       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10408         return false;
10409     }
10410     return ConstOrder && *ConstOrder;
10411   };
10412   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10413     if (V1 == V2)
10414       return true;
10415     if (V1->getType() != V2->getType())
10416       return false;
10417     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10418     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10419     if (Opcodes1.size() != Opcodes2.size())
10420       return false;
10421     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10422       // Undefs are compatible with any other value.
10423       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10424         continue;
10425       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10426         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10427           if (I1->getParent() != I2->getParent())
10428             return false;
10429           InstructionsState S = getSameOpcode({I1, I2});
10430           if (S.getOpcode())
10431             continue;
10432           return false;
10433         }
10434       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10435         continue;
10436       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10437         return false;
10438     }
10439     return true;
10440   };
10441   auto Limit = [&R](Value *V) {
10442     unsigned EltSize = R.getVectorElementSize(V);
10443     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10444   };
10445 
10446   bool HaveVectorizedPhiNodes = false;
10447   do {
10448     // Collect the incoming values from the PHIs.
10449     Incoming.clear();
10450     for (Instruction &I : *BB) {
10451       PHINode *P = dyn_cast<PHINode>(&I);
10452       if (!P)
10453         break;
10454 
10455       // No need to analyze deleted, vectorized and non-vectorizable
10456       // instructions.
10457       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10458           isValidElementType(P->getType()))
10459         Incoming.push_back(P);
10460     }
10461 
10462     // Find the corresponding non-phi nodes for better matching when trying to
10463     // build the tree.
10464     for (Value *V : Incoming) {
10465       SmallVectorImpl<Value *> &Opcodes =
10466           PHIToOpcodes.try_emplace(V).first->getSecond();
10467       if (!Opcodes.empty())
10468         continue;
10469       SmallVector<Value *, 4> Nodes(1, V);
10470       SmallPtrSet<Value *, 4> Visited;
10471       while (!Nodes.empty()) {
10472         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10473         if (!Visited.insert(PHI).second)
10474           continue;
10475         for (Value *V : PHI->incoming_values()) {
10476           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10477             Nodes.push_back(PHI1);
10478             continue;
10479           }
10480           Opcodes.emplace_back(V);
10481         }
10482       }
10483     }
10484 
10485     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10486         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10487         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10488           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10489         },
10490         /*LimitForRegisterSize=*/true);
10491     Changed |= HaveVectorizedPhiNodes;
10492     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10493   } while (HaveVectorizedPhiNodes);
10494 
10495   VisitedInstrs.clear();
10496 
10497   SmallVector<Instruction *, 8> PostProcessInstructions;
10498   SmallDenseSet<Instruction *, 4> KeyNodes;
10499   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10500     // Skip instructions with scalable type. The num of elements is unknown at
10501     // compile-time for scalable type.
10502     if (isa<ScalableVectorType>(it->getType()))
10503       continue;
10504 
10505     // Skip instructions marked for the deletion.
10506     if (R.isDeleted(&*it))
10507       continue;
10508     // We may go through BB multiple times so skip the one we have checked.
10509     if (!VisitedInstrs.insert(&*it).second) {
10510       if (it->use_empty() && KeyNodes.contains(&*it) &&
10511           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10512                                       it->isTerminator())) {
10513         // We would like to start over since some instructions are deleted
10514         // and the iterator may become invalid value.
10515         Changed = true;
10516         it = BB->begin();
10517         e = BB->end();
10518       }
10519       continue;
10520     }
10521 
10522     if (isa<DbgInfoIntrinsic>(it))
10523       continue;
10524 
10525     // Try to vectorize reductions that use PHINodes.
10526     if (PHINode *P = dyn_cast<PHINode>(it)) {
10527       // Check that the PHI is a reduction PHI.
10528       if (P->getNumIncomingValues() == 2) {
10529         // Try to match and vectorize a horizontal reduction.
10530         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10531                                      TTI)) {
10532           Changed = true;
10533           it = BB->begin();
10534           e = BB->end();
10535           continue;
10536         }
10537       }
10538       // Try to vectorize the incoming values of the PHI, to catch reductions
10539       // that feed into PHIs.
10540       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10541         // Skip if the incoming block is the current BB for now. Also, bypass
10542         // unreachable IR for efficiency and to avoid crashing.
10543         // TODO: Collect the skipped incoming values and try to vectorize them
10544         // after processing BB.
10545         if (BB == P->getIncomingBlock(I) ||
10546             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10547           continue;
10548 
10549         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10550                                             P->getIncomingBlock(I), R, TTI);
10551       }
10552       continue;
10553     }
10554 
10555     // Ran into an instruction without users, like terminator, or function call
10556     // with ignored return value, store. Ignore unused instructions (basing on
10557     // instruction type, except for CallInst and InvokeInst).
10558     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10559                             isa<InvokeInst>(it))) {
10560       KeyNodes.insert(&*it);
10561       bool OpsChanged = false;
10562       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10563         for (auto *V : it->operand_values()) {
10564           // Try to match and vectorize a horizontal reduction.
10565           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10566         }
10567       }
10568       // Start vectorization of post-process list of instructions from the
10569       // top-tree instructions to try to vectorize as many instructions as
10570       // possible.
10571       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10572                                                 it->isTerminator());
10573       if (OpsChanged) {
10574         // We would like to start over since some instructions are deleted
10575         // and the iterator may become invalid value.
10576         Changed = true;
10577         it = BB->begin();
10578         e = BB->end();
10579         continue;
10580       }
10581     }
10582 
10583     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10584         isa<InsertValueInst>(it))
10585       PostProcessInstructions.push_back(&*it);
10586   }
10587 
10588   return Changed;
10589 }
10590 
10591 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10592   auto Changed = false;
10593   for (auto &Entry : GEPs) {
10594     // If the getelementptr list has fewer than two elements, there's nothing
10595     // to do.
10596     if (Entry.second.size() < 2)
10597       continue;
10598 
10599     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10600                       << Entry.second.size() << ".\n");
10601 
10602     // Process the GEP list in chunks suitable for the target's supported
10603     // vector size. If a vector register can't hold 1 element, we are done. We
10604     // are trying to vectorize the index computations, so the maximum number of
10605     // elements is based on the size of the index expression, rather than the
10606     // size of the GEP itself (the target's pointer size).
10607     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10608     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10609     if (MaxVecRegSize < EltSize)
10610       continue;
10611 
10612     unsigned MaxElts = MaxVecRegSize / EltSize;
10613     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10614       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10615       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10616 
10617       // Initialize a set a candidate getelementptrs. Note that we use a
10618       // SetVector here to preserve program order. If the index computations
10619       // are vectorizable and begin with loads, we want to minimize the chance
10620       // of having to reorder them later.
10621       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10622 
10623       // Some of the candidates may have already been vectorized after we
10624       // initially collected them. If so, they are marked as deleted, so remove
10625       // them from the set of candidates.
10626       Candidates.remove_if(
10627           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10628 
10629       // Remove from the set of candidates all pairs of getelementptrs with
10630       // constant differences. Such getelementptrs are likely not good
10631       // candidates for vectorization in a bottom-up phase since one can be
10632       // computed from the other. We also ensure all candidate getelementptr
10633       // indices are unique.
10634       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10635         auto *GEPI = GEPList[I];
10636         if (!Candidates.count(GEPI))
10637           continue;
10638         auto *SCEVI = SE->getSCEV(GEPList[I]);
10639         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10640           auto *GEPJ = GEPList[J];
10641           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10642           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10643             Candidates.remove(GEPI);
10644             Candidates.remove(GEPJ);
10645           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10646             Candidates.remove(GEPJ);
10647           }
10648         }
10649       }
10650 
10651       // We break out of the above computation as soon as we know there are
10652       // fewer than two candidates remaining.
10653       if (Candidates.size() < 2)
10654         continue;
10655 
10656       // Add the single, non-constant index of each candidate to the bundle. We
10657       // ensured the indices met these constraints when we originally collected
10658       // the getelementptrs.
10659       SmallVector<Value *, 16> Bundle(Candidates.size());
10660       auto BundleIndex = 0u;
10661       for (auto *V : Candidates) {
10662         auto *GEP = cast<GetElementPtrInst>(V);
10663         auto *GEPIdx = GEP->idx_begin()->get();
10664         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10665         Bundle[BundleIndex++] = GEPIdx;
10666       }
10667 
10668       // Try and vectorize the indices. We are currently only interested in
10669       // gather-like cases of the form:
10670       //
10671       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10672       //
10673       // where the loads of "a", the loads of "b", and the subtractions can be
10674       // performed in parallel. It's likely that detecting this pattern in a
10675       // bottom-up phase will be simpler and less costly than building a
10676       // full-blown top-down phase beginning at the consecutive loads.
10677       Changed |= tryToVectorizeList(Bundle, R);
10678     }
10679   }
10680   return Changed;
10681 }
10682 
10683 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10684   bool Changed = false;
10685   // Sort by type, base pointers and values operand. Value operands must be
10686   // compatible (have the same opcode, same parent), otherwise it is
10687   // definitely not profitable to try to vectorize them.
10688   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10689     if (V->getPointerOperandType()->getTypeID() <
10690         V2->getPointerOperandType()->getTypeID())
10691       return true;
10692     if (V->getPointerOperandType()->getTypeID() >
10693         V2->getPointerOperandType()->getTypeID())
10694       return false;
10695     // UndefValues are compatible with all other values.
10696     if (isa<UndefValue>(V->getValueOperand()) ||
10697         isa<UndefValue>(V2->getValueOperand()))
10698       return false;
10699     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10700       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10701         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10702             DT->getNode(I1->getParent());
10703         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10704             DT->getNode(I2->getParent());
10705         assert(NodeI1 && "Should only process reachable instructions");
10706         assert(NodeI1 && "Should only process reachable instructions");
10707         assert((NodeI1 == NodeI2) ==
10708                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10709                "Different nodes should have different DFS numbers");
10710         if (NodeI1 != NodeI2)
10711           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10712         InstructionsState S = getSameOpcode({I1, I2});
10713         if (S.getOpcode())
10714           return false;
10715         return I1->getOpcode() < I2->getOpcode();
10716       }
10717     if (isa<Constant>(V->getValueOperand()) &&
10718         isa<Constant>(V2->getValueOperand()))
10719       return false;
10720     return V->getValueOperand()->getValueID() <
10721            V2->getValueOperand()->getValueID();
10722   };
10723 
10724   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10725     if (V1 == V2)
10726       return true;
10727     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10728       return false;
10729     // Undefs are compatible with any other value.
10730     if (isa<UndefValue>(V1->getValueOperand()) ||
10731         isa<UndefValue>(V2->getValueOperand()))
10732       return true;
10733     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10734       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10735         if (I1->getParent() != I2->getParent())
10736           return false;
10737         InstructionsState S = getSameOpcode({I1, I2});
10738         return S.getOpcode() > 0;
10739       }
10740     if (isa<Constant>(V1->getValueOperand()) &&
10741         isa<Constant>(V2->getValueOperand()))
10742       return true;
10743     return V1->getValueOperand()->getValueID() ==
10744            V2->getValueOperand()->getValueID();
10745   };
10746   auto Limit = [&R, this](StoreInst *SI) {
10747     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10748     return R.getMinVF(EltSize);
10749   };
10750 
10751   // Attempt to sort and vectorize each of the store-groups.
10752   for (auto &Pair : Stores) {
10753     if (Pair.second.size() < 2)
10754       continue;
10755 
10756     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10757                       << Pair.second.size() << ".\n");
10758 
10759     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10760       continue;
10761 
10762     Changed |= tryToVectorizeSequence<StoreInst>(
10763         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10764         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10765           return vectorizeStores(Candidates, R);
10766         },
10767         /*LimitForRegisterSize=*/false);
10768   }
10769   return Changed;
10770 }
10771 
10772 char SLPVectorizer::ID = 0;
10773 
10774 static const char lv_name[] = "SLP Vectorizer";
10775 
10776 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10777 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10778 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10779 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10780 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10781 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10782 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10783 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10784 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10785 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10786 
10787 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10788