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