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