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/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
732   int Index = Offset;
733   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
734     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
735       auto *VT = cast<FixedVectorType>(IE->getType());
736       if (CI->getValue().uge(VT->getNumElements()))
737         return UndefMaskElem;
738       Index *= VT->getNumElements();
739       Index += CI->getZExtValue();
740       return Index;
741     }
742     if (isa<UndefValue>(IE->getOperand(2)))
743       return UndefMaskElem;
744     return None;
745   }
746 
747   auto *IV = cast<InsertValueInst>(InsertInst);
748   Type *CurrentType = IV->getType();
749   for (unsigned I : IV->indices()) {
750     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
751       Index *= ST->getNumElements();
752       CurrentType = ST->getElementType(I);
753     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
754       Index *= AT->getNumElements();
755       CurrentType = AT->getElementType();
756     } else {
757       return None;
758     }
759     Index += I;
760   }
761   return Index;
762 }
763 
764 /// Reorders the list of scalars in accordance with the given \p Order and then
765 /// the \p Mask. \p Order - is the original order of the scalars, need to
766 /// reorder scalars into an unordered state at first according to the given
767 /// order. Then the ordered scalars are shuffled once again in accordance with
768 /// the provided mask.
769 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
770                            ArrayRef<int> Mask) {
771   assert(!Mask.empty() && "Expected non-empty mask.");
772   SmallVector<Value *> Prev(Scalars.size(),
773                             UndefValue::get(Scalars.front()->getType()));
774   Prev.swap(Scalars);
775   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
776     if (Mask[I] != UndefMaskElem)
777       Scalars[Mask[I]] = Prev[I];
778 }
779 
780 namespace slpvectorizer {
781 
782 /// Bottom Up SLP Vectorizer.
783 class BoUpSLP {
784   struct TreeEntry;
785   struct ScheduleData;
786 
787 public:
788   using ValueList = SmallVector<Value *, 8>;
789   using InstrList = SmallVector<Instruction *, 16>;
790   using ValueSet = SmallPtrSet<Value *, 16>;
791   using StoreList = SmallVector<StoreInst *, 8>;
792   using ExtraValueToDebugLocsMap =
793       MapVector<Value *, SmallVector<Instruction *, 2>>;
794   using OrdersType = SmallVector<unsigned, 4>;
795 
796   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
797           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
798           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
799           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
800       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
801         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
802     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
803     // Use the vector register size specified by the target unless overridden
804     // by a command-line option.
805     // TODO: It would be better to limit the vectorization factor based on
806     //       data type rather than just register size. For example, x86 AVX has
807     //       256-bit registers, but it does not support integer operations
808     //       at that width (that requires AVX2).
809     if (MaxVectorRegSizeOption.getNumOccurrences())
810       MaxVecRegSize = MaxVectorRegSizeOption;
811     else
812       MaxVecRegSize =
813           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
814               .getFixedSize();
815 
816     if (MinVectorRegSizeOption.getNumOccurrences())
817       MinVecRegSize = MinVectorRegSizeOption;
818     else
819       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
820   }
821 
822   /// Vectorize the tree that starts with the elements in \p VL.
823   /// Returns the vectorized root.
824   Value *vectorizeTree();
825 
826   /// Vectorize the tree but with the list of externally used values \p
827   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
828   /// generated extractvalue instructions.
829   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
830 
831   /// \returns the cost incurred by unwanted spills and fills, caused by
832   /// holding live values over call sites.
833   InstructionCost getSpillCost() const;
834 
835   /// \returns the vectorization cost of the subtree that starts at \p VL.
836   /// A negative number means that this is profitable.
837   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
838 
839   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
840   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
841   void buildTree(ArrayRef<Value *> Roots,
842                  ArrayRef<Value *> UserIgnoreLst = None);
843 
844   /// Builds external uses of the vectorized scalars, i.e. the list of
845   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
846   /// ExternallyUsedValues contains additional list of external uses to handle
847   /// vectorization of reductions.
848   void
849   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
850 
851   /// Clear the internal data structures that are created by 'buildTree'.
852   void deleteTree() {
853     VectorizableTree.clear();
854     ScalarToTreeEntry.clear();
855     MustGather.clear();
856     ExternalUses.clear();
857     for (auto &Iter : BlocksSchedules) {
858       BlockScheduling *BS = Iter.second.get();
859       BS->clear();
860     }
861     MinBWs.clear();
862     InstrElementSize.clear();
863   }
864 
865   unsigned getTreeSize() const { return VectorizableTree.size(); }
866 
867   /// Perform LICM and CSE on the newly generated gather sequences.
868   void optimizeGatherSequence();
869 
870   /// Checks if the specified gather tree entry \p TE can be represented as a
871   /// shuffled vector entry + (possibly) permutation with other gathers. It
872   /// implements the checks only for possibly ordered scalars (Loads,
873   /// ExtractElement, ExtractValue), which can be part of the graph.
874   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
875 
876   /// Gets reordering data for the given tree entry. If the entry is vectorized
877   /// - just return ReorderIndices, otherwise check if the scalars can be
878   /// reordered and return the most optimal order.
879   /// \param TopToBottom If true, include the order of vectorized stores and
880   /// insertelement nodes, otherwise skip them.
881   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
882 
883   /// Reorders the current graph to the most profitable order starting from the
884   /// root node to the leaf nodes. The best order is chosen only from the nodes
885   /// of the same size (vectorization factor). Smaller nodes are considered
886   /// parts of subgraph with smaller VF and they are reordered independently. We
887   /// can make it because we still need to extend smaller nodes to the wider VF
888   /// and we can merge reordering shuffles with the widening shuffles.
889   void reorderTopToBottom();
890 
891   /// Reorders the current graph to the most profitable order starting from
892   /// leaves to the root. It allows to rotate small subgraphs and reduce the
893   /// number of reshuffles if the leaf nodes use the same order. In this case we
894   /// can merge the orders and just shuffle user node instead of shuffling its
895   /// operands. Plus, even the leaf nodes have different orders, it allows to
896   /// sink reordering in the graph closer to the root node and merge it later
897   /// during analysis.
898   void reorderBottomToTop(bool IgnoreReorder = false);
899 
900   /// \return The vector element size in bits to use when vectorizing the
901   /// expression tree ending at \p V. If V is a store, the size is the width of
902   /// the stored value. Otherwise, the size is the width of the largest loaded
903   /// value reaching V. This method is used by the vectorizer to calculate
904   /// vectorization factors.
905   unsigned getVectorElementSize(Value *V);
906 
907   /// Compute the minimum type sizes required to represent the entries in a
908   /// vectorizable tree.
909   void computeMinimumValueSizes();
910 
911   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
912   unsigned getMaxVecRegSize() const {
913     return MaxVecRegSize;
914   }
915 
916   // \returns minimum vector register size as set by cl::opt.
917   unsigned getMinVecRegSize() const {
918     return MinVecRegSize;
919   }
920 
921   unsigned getMinVF(unsigned Sz) const {
922     return std::max(2U, getMinVecRegSize() / Sz);
923   }
924 
925   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
926     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
927       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
928     return MaxVF ? MaxVF : UINT_MAX;
929   }
930 
931   /// Check if homogeneous aggregate is isomorphic to some VectorType.
932   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
933   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
934   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
935   ///
936   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
937   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
938 
939   /// \returns True if the VectorizableTree is both tiny and not fully
940   /// vectorizable. We do not vectorize such trees.
941   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
942 
943   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
944   /// can be load combined in the backend. Load combining may not be allowed in
945   /// the IR optimizer, so we do not want to alter the pattern. For example,
946   /// partially transforming a scalar bswap() pattern into vector code is
947   /// effectively impossible for the backend to undo.
948   /// TODO: If load combining is allowed in the IR optimizer, this analysis
949   ///       may not be necessary.
950   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
951 
952   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
953   /// can be load combined in the backend. Load combining may not be allowed in
954   /// the IR optimizer, so we do not want to alter the pattern. For example,
955   /// partially transforming a scalar bswap() pattern into vector code is
956   /// effectively impossible for the backend to undo.
957   /// TODO: If load combining is allowed in the IR optimizer, this analysis
958   ///       may not be necessary.
959   bool isLoadCombineCandidate() const;
960 
961   OptimizationRemarkEmitter *getORE() { return ORE; }
962 
963   /// This structure holds any data we need about the edges being traversed
964   /// during buildTree_rec(). We keep track of:
965   /// (i) the user TreeEntry index, and
966   /// (ii) the index of the edge.
967   struct EdgeInfo {
968     EdgeInfo() = default;
969     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
970         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
971     /// The user TreeEntry.
972     TreeEntry *UserTE = nullptr;
973     /// The operand index of the use.
974     unsigned EdgeIdx = UINT_MAX;
975 #ifndef NDEBUG
976     friend inline raw_ostream &operator<<(raw_ostream &OS,
977                                           const BoUpSLP::EdgeInfo &EI) {
978       EI.dump(OS);
979       return OS;
980     }
981     /// Debug print.
982     void dump(raw_ostream &OS) const {
983       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
984          << " EdgeIdx:" << EdgeIdx << "}";
985     }
986     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
987 #endif
988   };
989 
990   /// A helper data structure to hold the operands of a vector of instructions.
991   /// This supports a fixed vector length for all operand vectors.
992   class VLOperands {
993     /// For each operand we need (i) the value, and (ii) the opcode that it
994     /// would be attached to if the expression was in a left-linearized form.
995     /// This is required to avoid illegal operand reordering.
996     /// For example:
997     /// \verbatim
998     ///                         0 Op1
999     ///                         |/
1000     /// Op1 Op2   Linearized    + Op2
1001     ///   \ /     ---------->   |/
1002     ///    -                    -
1003     ///
1004     /// Op1 - Op2            (0 + Op1) - Op2
1005     /// \endverbatim
1006     ///
1007     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1008     ///
1009     /// Another way to think of this is to track all the operations across the
1010     /// path from the operand all the way to the root of the tree and to
1011     /// calculate the operation that corresponds to this path. For example, the
1012     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1013     /// corresponding operation is a '-' (which matches the one in the
1014     /// linearized tree, as shown above).
1015     ///
1016     /// For lack of a better term, we refer to this operation as Accumulated
1017     /// Path Operation (APO).
1018     struct OperandData {
1019       OperandData() = default;
1020       OperandData(Value *V, bool APO, bool IsUsed)
1021           : V(V), APO(APO), IsUsed(IsUsed) {}
1022       /// The operand value.
1023       Value *V = nullptr;
1024       /// TreeEntries only allow a single opcode, or an alternate sequence of
1025       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1026       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1027       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1028       /// (e.g., Add/Mul)
1029       bool APO = false;
1030       /// Helper data for the reordering function.
1031       bool IsUsed = false;
1032     };
1033 
1034     /// During operand reordering, we are trying to select the operand at lane
1035     /// that matches best with the operand at the neighboring lane. Our
1036     /// selection is based on the type of value we are looking for. For example,
1037     /// if the neighboring lane has a load, we need to look for a load that is
1038     /// accessing a consecutive address. These strategies are summarized in the
1039     /// 'ReorderingMode' enumerator.
1040     enum class ReorderingMode {
1041       Load,     ///< Matching loads to consecutive memory addresses
1042       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1043       Constant, ///< Matching constants
1044       Splat,    ///< Matching the same instruction multiple times (broadcast)
1045       Failed,   ///< We failed to create a vectorizable group
1046     };
1047 
1048     using OperandDataVec = SmallVector<OperandData, 2>;
1049 
1050     /// A vector of operand vectors.
1051     SmallVector<OperandDataVec, 4> OpsVec;
1052 
1053     const DataLayout &DL;
1054     ScalarEvolution &SE;
1055     const BoUpSLP &R;
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane.
1058     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1063     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1064       return OpsVec[OpIdx][Lane];
1065     }
1066 
1067     /// Clears the used flag for all entries.
1068     void clearUsed() {
1069       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1070            OpIdx != NumOperands; ++OpIdx)
1071         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1072              ++Lane)
1073           OpsVec[OpIdx][Lane].IsUsed = false;
1074     }
1075 
1076     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1077     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1078       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1079     }
1080 
1081     // The hard-coded scores listed here are not very important, though it shall
1082     // be higher for better matches to improve the resulting cost. When
1083     // computing the scores of matching one sub-tree with another, we are
1084     // basically counting the number of values that are matching. So even if all
1085     // scores are set to 1, we would still get a decent matching result.
1086     // However, sometimes we have to break ties. For example we may have to
1087     // choose between matching loads vs matching opcodes. This is what these
1088     // scores are helping us with: they provide the order of preference. Also,
1089     // this is important if the scalar is externally used or used in another
1090     // tree entry node in the different lane.
1091 
1092     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1093     static const int ScoreConsecutiveLoads = 4;
1094     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1095     static const int ScoreReversedLoads = 3;
1096     /// ExtractElementInst from same vector and consecutive indexes.
1097     static const int ScoreConsecutiveExtracts = 4;
1098     /// ExtractElementInst from same vector and reversed indices.
1099     static const int ScoreReversedExtracts = 3;
1100     /// Constants.
1101     static const int ScoreConstants = 2;
1102     /// Instructions with the same opcode.
1103     static const int ScoreSameOpcode = 2;
1104     /// Instructions with alt opcodes (e.g, add + sub).
1105     static const int ScoreAltOpcodes = 1;
1106     /// Identical instructions (a.k.a. splat or broadcast).
1107     static const int ScoreSplat = 1;
1108     /// Matching with an undef is preferable to failing.
1109     static const int ScoreUndef = 1;
1110     /// Score for failing to find a decent match.
1111     static const int ScoreFail = 0;
1112     /// Score if all users are vectorized.
1113     static const int ScoreAllUserVectorized = 1;
1114 
1115     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1116     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1117     /// MainAltOps.
1118     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1119                                ScalarEvolution &SE, int NumLanes,
1120                                ArrayRef<Value *> MainAltOps) {
1121       if (V1 == V2)
1122         return VLOperands::ScoreSplat;
1123 
1124       auto *LI1 = dyn_cast<LoadInst>(V1);
1125       auto *LI2 = dyn_cast<LoadInst>(V2);
1126       if (LI1 && LI2) {
1127         if (LI1->getParent() != LI2->getParent())
1128           return VLOperands::ScoreFail;
1129 
1130         Optional<int> Dist = getPointersDiff(
1131             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1132             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1133         if (!Dist || *Dist == 0)
1134           return VLOperands::ScoreFail;
1135         // The distance is too large - still may be profitable to use masked
1136         // loads/gathers.
1137         if (std::abs(*Dist) > NumLanes / 2)
1138           return VLOperands::ScoreAltOpcodes;
1139         // This still will detect consecutive loads, but we might have "holes"
1140         // in some cases. It is ok for non-power-2 vectorization and may produce
1141         // better results. It should not affect current vectorization.
1142         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1143                            : VLOperands::ScoreReversedLoads;
1144       }
1145 
1146       auto *C1 = dyn_cast<Constant>(V1);
1147       auto *C2 = dyn_cast<Constant>(V2);
1148       if (C1 && C2)
1149         return VLOperands::ScoreConstants;
1150 
1151       // Extracts from consecutive indexes of the same vector better score as
1152       // the extracts could be optimized away.
1153       Value *EV1;
1154       ConstantInt *Ex1Idx;
1155       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1156         // Undefs are always profitable for extractelements.
1157         if (isa<UndefValue>(V2))
1158           return VLOperands::ScoreConsecutiveExtracts;
1159         Value *EV2 = nullptr;
1160         ConstantInt *Ex2Idx = nullptr;
1161         if (match(V2,
1162                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1163                                                          m_Undef())))) {
1164           // Undefs are always profitable for extractelements.
1165           if (!Ex2Idx)
1166             return VLOperands::ScoreConsecutiveExtracts;
1167           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1168             return VLOperands::ScoreConsecutiveExtracts;
1169           if (EV2 == EV1) {
1170             int Idx1 = Ex1Idx->getZExtValue();
1171             int Idx2 = Ex2Idx->getZExtValue();
1172             int Dist = Idx2 - Idx1;
1173             // The distance is too large - still may be profitable to use
1174             // shuffles.
1175             if (std::abs(Dist) == 0)
1176               return VLOperands::ScoreSplat;
1177             if (std::abs(Dist) > NumLanes / 2)
1178               return VLOperands::ScoreSameOpcode;
1179             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1180                               : VLOperands::ScoreReversedExtracts;
1181           }
1182           return VLOperands::ScoreAltOpcodes;
1183         }
1184         return VLOperands::ScoreFail;
1185       }
1186 
1187       auto *I1 = dyn_cast<Instruction>(V1);
1188       auto *I2 = dyn_cast<Instruction>(V2);
1189       if (I1 && I2) {
1190         if (I1->getParent() != I2->getParent())
1191           return VLOperands::ScoreFail;
1192         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1193         Ops.push_back(I1);
1194         Ops.push_back(I2);
1195         InstructionsState S = getSameOpcode(Ops);
1196         // Note: Only consider instructions with <= 2 operands to avoid
1197         // complexity explosion.
1198         if (S.getOpcode() &&
1199             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1200              !S.isAltShuffle()) &&
1201             all_of(Ops, [&S](Value *V) {
1202               return cast<Instruction>(V)->getNumOperands() ==
1203                      S.MainOp->getNumOperands();
1204             }))
1205           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1206                                   : VLOperands::ScoreSameOpcode;
1207       }
1208 
1209       if (isa<UndefValue>(V2))
1210         return VLOperands::ScoreUndef;
1211 
1212       return VLOperands::ScoreFail;
1213     }
1214 
1215     /// \param Lane lane of the operands under analysis.
1216     /// \param OpIdx operand index in \p Lane lane we're looking the best
1217     /// candidate for.
1218     /// \param Idx operand index of the current candidate value.
1219     /// \returns The additional score due to possible broadcasting of the
1220     /// elements in the lane. It is more profitable to have power-of-2 unique
1221     /// elements in the lane, it will be vectorized with higher probability
1222     /// after removing duplicates. Currently the SLP vectorizer supports only
1223     /// vectorization of the power-of-2 number of unique scalars.
1224     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1225       Value *IdxLaneV = getData(Idx, Lane).V;
1226       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1227         return 0;
1228       SmallPtrSet<Value *, 4> Uniques;
1229       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1230         if (Ln == Lane)
1231           continue;
1232         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1233         if (!isa<Instruction>(OpIdxLnV))
1234           return 0;
1235         Uniques.insert(OpIdxLnV);
1236       }
1237       int UniquesCount = Uniques.size();
1238       int UniquesCntWithIdxLaneV =
1239           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1240       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1241       int UniquesCntWithOpIdxLaneV =
1242           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1243       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1244         return 0;
1245       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1246               UniquesCntWithOpIdxLaneV) -
1247              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1248     }
1249 
1250     /// \param Lane lane of the operands under analysis.
1251     /// \param OpIdx operand index in \p Lane lane we're looking the best
1252     /// candidate for.
1253     /// \param Idx operand index of the current candidate value.
1254     /// \returns The additional score for the scalar which users are all
1255     /// vectorized.
1256     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1257       Value *IdxLaneV = getData(Idx, Lane).V;
1258       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1259       // Do not care about number of uses for vector-like instructions
1260       // (extractelement/extractvalue with constant indices), they are extracts
1261       // themselves and already externally used. Vectorization of such
1262       // instructions does not add extra extractelement instruction, just may
1263       // remove it.
1264       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1265           isVectorLikeInstWithConstOps(OpIdxLaneV))
1266         return VLOperands::ScoreAllUserVectorized;
1267       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1268       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1269         return 0;
1270       return R.areAllUsersVectorized(IdxLaneI, None)
1271                  ? VLOperands::ScoreAllUserVectorized
1272                  : 0;
1273     }
1274 
1275     /// Go through the operands of \p LHS and \p RHS recursively until \p
1276     /// MaxLevel, and return the cummulative score. For example:
1277     /// \verbatim
1278     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1279     ///     \ /         \ /         \ /        \ /
1280     ///      +           +           +          +
1281     ///     G1          G2          G3         G4
1282     /// \endverbatim
1283     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1284     /// each level recursively, accumulating the score. It starts from matching
1285     /// the additions at level 0, then moves on to the loads (level 1). The
1286     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1287     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1288     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1289     /// Please note that the order of the operands does not matter, as we
1290     /// evaluate the score of all profitable combinations of operands. In
1291     /// other words the score of G1 and G4 is the same as G1 and G2. This
1292     /// heuristic is based on ideas described in:
1293     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1294     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1295     ///   Luís F. W. Góes
1296     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1297                            ArrayRef<Value *> MainAltOps) {
1298 
1299       // Get the shallow score of V1 and V2.
1300       int ShallowScoreAtThisLevel =
1301           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1302 
1303       // If reached MaxLevel,
1304       //  or if V1 and V2 are not instructions,
1305       //  or if they are SPLAT,
1306       //  or if they are not consecutive,
1307       //  or if profitable to vectorize loads or extractelements, early return
1308       //  the current cost.
1309       auto *I1 = dyn_cast<Instruction>(LHS);
1310       auto *I2 = dyn_cast<Instruction>(RHS);
1311       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1312           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1313           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1314             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1315             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1316            ShallowScoreAtThisLevel))
1317         return ShallowScoreAtThisLevel;
1318       assert(I1 && I2 && "Should have early exited.");
1319 
1320       // Contains the I2 operand indexes that got matched with I1 operands.
1321       SmallSet<unsigned, 4> Op2Used;
1322 
1323       // Recursion towards the operands of I1 and I2. We are trying all possible
1324       // operand pairs, and keeping track of the best score.
1325       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1326            OpIdx1 != NumOperands1; ++OpIdx1) {
1327         // Try to pair op1I with the best operand of I2.
1328         int MaxTmpScore = 0;
1329         unsigned MaxOpIdx2 = 0;
1330         bool FoundBest = false;
1331         // If I2 is commutative try all combinations.
1332         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1333         unsigned ToIdx = isCommutative(I2)
1334                              ? I2->getNumOperands()
1335                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1336         assert(FromIdx <= ToIdx && "Bad index");
1337         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1338           // Skip operands already paired with OpIdx1.
1339           if (Op2Used.count(OpIdx2))
1340             continue;
1341           // Recursively calculate the cost at each level
1342           int TmpScore =
1343               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1344                                  CurrLevel + 1, MaxLevel, None);
1345           // Look for the best score.
1346           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1347             MaxTmpScore = TmpScore;
1348             MaxOpIdx2 = OpIdx2;
1349             FoundBest = true;
1350           }
1351         }
1352         if (FoundBest) {
1353           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1354           Op2Used.insert(MaxOpIdx2);
1355           ShallowScoreAtThisLevel += MaxTmpScore;
1356         }
1357       }
1358       return ShallowScoreAtThisLevel;
1359     }
1360 
1361     /// Score scaling factor for fully compatible instructions but with
1362     /// different number of external uses. Allows better selection of the
1363     /// instructions with less external uses.
1364     static const int ScoreScaleFactor = 10;
1365 
1366     /// \Returns the look-ahead score, which tells us how much the sub-trees
1367     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1368     /// score. This helps break ties in an informed way when we cannot decide on
1369     /// the order of the operands by just considering the immediate
1370     /// predecessors.
1371     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1372                           int Lane, unsigned OpIdx, unsigned Idx,
1373                           bool &IsUsed) {
1374       int Score =
1375           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1376       if (Score) {
1377         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1378         if (Score <= -SplatScore) {
1379           // Set the minimum score for splat-like sequence to avoid setting
1380           // failed state.
1381           Score = 1;
1382         } else {
1383           Score += SplatScore;
1384           // Scale score to see the difference between different operands
1385           // and similar operands but all vectorized/not all vectorized
1386           // uses. It does not affect actual selection of the best
1387           // compatible operand in general, just allows to select the
1388           // operand with all vectorized uses.
1389           Score *= ScoreScaleFactor;
1390           Score += getExternalUseScore(Lane, OpIdx, Idx);
1391           IsUsed = true;
1392         }
1393       }
1394       return Score;
1395     }
1396 
1397     /// Best defined scores per lanes between the passes. Used to choose the
1398     /// best operand (with the highest score) between the passes.
1399     /// The key - {Operand Index, Lane}.
1400     /// The value - the best score between the passes for the lane and the
1401     /// operand.
1402     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1403         BestScoresPerLanes;
1404 
1405     // Search all operands in Ops[*][Lane] for the one that matches best
1406     // Ops[OpIdx][LastLane] and return its opreand index.
1407     // If no good match can be found, return None.
1408     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1409                                       ArrayRef<ReorderingMode> ReorderingModes,
1410                                       ArrayRef<Value *> MainAltOps) {
1411       unsigned NumOperands = getNumOperands();
1412 
1413       // The operand of the previous lane at OpIdx.
1414       Value *OpLastLane = getData(OpIdx, LastLane).V;
1415 
1416       // Our strategy mode for OpIdx.
1417       ReorderingMode RMode = ReorderingModes[OpIdx];
1418       if (RMode == ReorderingMode::Failed)
1419         return None;
1420 
1421       // The linearized opcode of the operand at OpIdx, Lane.
1422       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1423 
1424       // The best operand index and its score.
1425       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1426       // are using the score to differentiate between the two.
1427       struct BestOpData {
1428         Optional<unsigned> Idx = None;
1429         unsigned Score = 0;
1430       } BestOp;
1431       BestOp.Score =
1432           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1433               .first->second;
1434 
1435       // Track if the operand must be marked as used. If the operand is set to
1436       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1437       // want to reestimate the operands again on the following iterations).
1438       bool IsUsed =
1439           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1440       // Iterate through all unused operands and look for the best.
1441       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1442         // Get the operand at Idx and Lane.
1443         OperandData &OpData = getData(Idx, Lane);
1444         Value *Op = OpData.V;
1445         bool OpAPO = OpData.APO;
1446 
1447         // Skip already selected operands.
1448         if (OpData.IsUsed)
1449           continue;
1450 
1451         // Skip if we are trying to move the operand to a position with a
1452         // different opcode in the linearized tree form. This would break the
1453         // semantics.
1454         if (OpAPO != OpIdxAPO)
1455           continue;
1456 
1457         // Look for an operand that matches the current mode.
1458         switch (RMode) {
1459         case ReorderingMode::Load:
1460         case ReorderingMode::Constant:
1461         case ReorderingMode::Opcode: {
1462           bool LeftToRight = Lane > LastLane;
1463           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1464           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1465           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1466                                         OpIdx, Idx, IsUsed);
1467           if (Score > static_cast<int>(BestOp.Score)) {
1468             BestOp.Idx = Idx;
1469             BestOp.Score = Score;
1470             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1471           }
1472           break;
1473         }
1474         case ReorderingMode::Splat:
1475           if (Op == OpLastLane)
1476             BestOp.Idx = Idx;
1477           break;
1478         case ReorderingMode::Failed:
1479           llvm_unreachable("Not expected Failed reordering mode.");
1480         }
1481       }
1482 
1483       if (BestOp.Idx) {
1484         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1485         return BestOp.Idx;
1486       }
1487       // If we could not find a good match return None.
1488       return None;
1489     }
1490 
1491     /// Helper for reorderOperandVecs.
1492     /// \returns the lane that we should start reordering from. This is the one
1493     /// which has the least number of operands that can freely move about or
1494     /// less profitable because it already has the most optimal set of operands.
1495     unsigned getBestLaneToStartReordering() const {
1496       unsigned Min = UINT_MAX;
1497       unsigned SameOpNumber = 0;
1498       // std::pair<unsigned, unsigned> is used to implement a simple voting
1499       // algorithm and choose the lane with the least number of operands that
1500       // can freely move about or less profitable because it already has the
1501       // most optimal set of operands. The first unsigned is a counter for
1502       // voting, the second unsigned is the counter of lanes with instructions
1503       // with same/alternate opcodes and same parent basic block.
1504       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1505       // Try to be closer to the original results, if we have multiple lanes
1506       // with same cost. If 2 lanes have the same cost, use the one with the
1507       // lowest index.
1508       for (int I = getNumLanes(); I > 0; --I) {
1509         unsigned Lane = I - 1;
1510         OperandsOrderData NumFreeOpsHash =
1511             getMaxNumOperandsThatCanBeReordered(Lane);
1512         // Compare the number of operands that can move and choose the one with
1513         // the least number.
1514         if (NumFreeOpsHash.NumOfAPOs < Min) {
1515           Min = NumFreeOpsHash.NumOfAPOs;
1516           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1517           HashMap.clear();
1518           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1519         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1520                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1521           // Select the most optimal lane in terms of number of operands that
1522           // should be moved around.
1523           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1524           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1526                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1527           auto It = HashMap.find(NumFreeOpsHash.Hash);
1528           if (It == HashMap.end())
1529             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1530           else
1531             ++It->second.first;
1532         }
1533       }
1534       // Select the lane with the minimum counter.
1535       unsigned BestLane = 0;
1536       unsigned CntMin = UINT_MAX;
1537       for (const auto &Data : reverse(HashMap)) {
1538         if (Data.second.first < CntMin) {
1539           CntMin = Data.second.first;
1540           BestLane = Data.second.second;
1541         }
1542       }
1543       return BestLane;
1544     }
1545 
1546     /// Data structure that helps to reorder operands.
1547     struct OperandsOrderData {
1548       /// The best number of operands with the same APOs, which can be
1549       /// reordered.
1550       unsigned NumOfAPOs = UINT_MAX;
1551       /// Number of operands with the same/alternate instruction opcode and
1552       /// parent.
1553       unsigned NumOpsWithSameOpcodeParent = 0;
1554       /// Hash for the actual operands ordering.
1555       /// Used to count operands, actually their position id and opcode
1556       /// value. It is used in the voting mechanism to find the lane with the
1557       /// least number of operands that can freely move about or less profitable
1558       /// because it already has the most optimal set of operands. Can be
1559       /// replaced with SmallVector<unsigned> instead but hash code is faster
1560       /// and requires less memory.
1561       unsigned Hash = 0;
1562     };
1563     /// \returns the maximum number of operands that are allowed to be reordered
1564     /// for \p Lane and the number of compatible instructions(with the same
1565     /// parent/opcode). This is used as a heuristic for selecting the first lane
1566     /// to start operand reordering.
1567     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1568       unsigned CntTrue = 0;
1569       unsigned NumOperands = getNumOperands();
1570       // Operands with the same APO can be reordered. We therefore need to count
1571       // how many of them we have for each APO, like this: Cnt[APO] = x.
1572       // Since we only have two APOs, namely true and false, we can avoid using
1573       // a map. Instead we can simply count the number of operands that
1574       // correspond to one of them (in this case the 'true' APO), and calculate
1575       // the other by subtracting it from the total number of operands.
1576       // Operands with the same instruction opcode and parent are more
1577       // profitable since we don't need to move them in many cases, with a high
1578       // probability such lane already can be vectorized effectively.
1579       bool AllUndefs = true;
1580       unsigned NumOpsWithSameOpcodeParent = 0;
1581       Instruction *OpcodeI = nullptr;
1582       BasicBlock *Parent = nullptr;
1583       unsigned Hash = 0;
1584       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1585         const OperandData &OpData = getData(OpIdx, Lane);
1586         if (OpData.APO)
1587           ++CntTrue;
1588         // Use Boyer-Moore majority voting for finding the majority opcode and
1589         // the number of times it occurs.
1590         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1591           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1592               I->getParent() != Parent) {
1593             if (NumOpsWithSameOpcodeParent == 0) {
1594               NumOpsWithSameOpcodeParent = 1;
1595               OpcodeI = I;
1596               Parent = I->getParent();
1597             } else {
1598               --NumOpsWithSameOpcodeParent;
1599             }
1600           } else {
1601             ++NumOpsWithSameOpcodeParent;
1602           }
1603         }
1604         Hash = hash_combine(
1605             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1606         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1607       }
1608       if (AllUndefs)
1609         return {};
1610       OperandsOrderData Data;
1611       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1612       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1613       Data.Hash = Hash;
1614       return Data;
1615     }
1616 
1617     /// Go through the instructions in VL and append their operands.
1618     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1619       assert(!VL.empty() && "Bad VL");
1620       assert((empty() || VL.size() == getNumLanes()) &&
1621              "Expected same number of lanes");
1622       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1623       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1624       OpsVec.resize(NumOperands);
1625       unsigned NumLanes = VL.size();
1626       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1627         OpsVec[OpIdx].resize(NumLanes);
1628         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1629           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1630           // Our tree has just 3 nodes: the root and two operands.
1631           // It is therefore trivial to get the APO. We only need to check the
1632           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1633           // RHS operand. The LHS operand of both add and sub is never attached
1634           // to an inversese operation in the linearized form, therefore its APO
1635           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1636 
1637           // Since operand reordering is performed on groups of commutative
1638           // operations or alternating sequences (e.g., +, -), we can safely
1639           // tell the inverse operations by checking commutativity.
1640           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1641           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1642           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1643                                  APO, false};
1644         }
1645       }
1646     }
1647 
1648     /// \returns the number of operands.
1649     unsigned getNumOperands() const { return OpsVec.size(); }
1650 
1651     /// \returns the number of lanes.
1652     unsigned getNumLanes() const { return OpsVec[0].size(); }
1653 
1654     /// \returns the operand value at \p OpIdx and \p Lane.
1655     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1656       return getData(OpIdx, Lane).V;
1657     }
1658 
1659     /// \returns true if the data structure is empty.
1660     bool empty() const { return OpsVec.empty(); }
1661 
1662     /// Clears the data.
1663     void clear() { OpsVec.clear(); }
1664 
1665     /// \Returns true if there are enough operands identical to \p Op to fill
1666     /// the whole vector.
1667     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1668     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1669       bool OpAPO = getData(OpIdx, Lane).APO;
1670       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1671         if (Ln == Lane)
1672           continue;
1673         // This is set to true if we found a candidate for broadcast at Lane.
1674         bool FoundCandidate = false;
1675         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1676           OperandData &Data = getData(OpI, Ln);
1677           if (Data.APO != OpAPO || Data.IsUsed)
1678             continue;
1679           if (Data.V == Op) {
1680             FoundCandidate = true;
1681             Data.IsUsed = true;
1682             break;
1683           }
1684         }
1685         if (!FoundCandidate)
1686           return false;
1687       }
1688       return true;
1689     }
1690 
1691   public:
1692     /// Initialize with all the operands of the instruction vector \p RootVL.
1693     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1694                ScalarEvolution &SE, const BoUpSLP &R)
1695         : DL(DL), SE(SE), R(R) {
1696       // Append all the operands of RootVL.
1697       appendOperandsOfVL(RootVL);
1698     }
1699 
1700     /// \Returns a value vector with the operands across all lanes for the
1701     /// opearnd at \p OpIdx.
1702     ValueList getVL(unsigned OpIdx) const {
1703       ValueList OpVL(OpsVec[OpIdx].size());
1704       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1705              "Expected same num of lanes across all operands");
1706       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1707         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1708       return OpVL;
1709     }
1710 
1711     // Performs operand reordering for 2 or more operands.
1712     // The original operands are in OrigOps[OpIdx][Lane].
1713     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1714     void reorder() {
1715       unsigned NumOperands = getNumOperands();
1716       unsigned NumLanes = getNumLanes();
1717       // Each operand has its own mode. We are using this mode to help us select
1718       // the instructions for each lane, so that they match best with the ones
1719       // we have selected so far.
1720       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1721 
1722       // This is a greedy single-pass algorithm. We are going over each lane
1723       // once and deciding on the best order right away with no back-tracking.
1724       // However, in order to increase its effectiveness, we start with the lane
1725       // that has operands that can move the least. For example, given the
1726       // following lanes:
1727       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1728       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1729       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1730       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1731       // we will start at Lane 1, since the operands of the subtraction cannot
1732       // be reordered. Then we will visit the rest of the lanes in a circular
1733       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1734 
1735       // Find the first lane that we will start our search from.
1736       unsigned FirstLane = getBestLaneToStartReordering();
1737 
1738       // Initialize the modes.
1739       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1740         Value *OpLane0 = getValue(OpIdx, FirstLane);
1741         // Keep track if we have instructions with all the same opcode on one
1742         // side.
1743         if (isa<LoadInst>(OpLane0))
1744           ReorderingModes[OpIdx] = ReorderingMode::Load;
1745         else if (isa<Instruction>(OpLane0)) {
1746           // Check if OpLane0 should be broadcast.
1747           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1748             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1749           else
1750             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1751         }
1752         else if (isa<Constant>(OpLane0))
1753           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1754         else if (isa<Argument>(OpLane0))
1755           // Our best hope is a Splat. It may save some cost in some cases.
1756           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1757         else
1758           // NOTE: This should be unreachable.
1759           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1760       }
1761 
1762       // Check that we don't have same operands. No need to reorder if operands
1763       // are just perfect diamond or shuffled diamond match. Do not do it only
1764       // for possible broadcasts or non-power of 2 number of scalars (just for
1765       // now).
1766       auto &&SkipReordering = [this]() {
1767         SmallPtrSet<Value *, 4> UniqueValues;
1768         ArrayRef<OperandData> Op0 = OpsVec.front();
1769         for (const OperandData &Data : Op0)
1770           UniqueValues.insert(Data.V);
1771         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1772           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1773                 return !UniqueValues.contains(Data.V);
1774               }))
1775             return false;
1776         }
1777         // TODO: Check if we can remove a check for non-power-2 number of
1778         // scalars after full support of non-power-2 vectorization.
1779         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1780       };
1781 
1782       // If the initial strategy fails for any of the operand indexes, then we
1783       // perform reordering again in a second pass. This helps avoid assigning
1784       // high priority to the failed strategy, and should improve reordering for
1785       // the non-failed operand indexes.
1786       for (int Pass = 0; Pass != 2; ++Pass) {
1787         // Check if no need to reorder operands since they're are perfect or
1788         // shuffled diamond match.
1789         // Need to to do it to avoid extra external use cost counting for
1790         // shuffled matches, which may cause regressions.
1791         if (SkipReordering())
1792           break;
1793         // Skip the second pass if the first pass did not fail.
1794         bool StrategyFailed = false;
1795         // Mark all operand data as free to use.
1796         clearUsed();
1797         // We keep the original operand order for the FirstLane, so reorder the
1798         // rest of the lanes. We are visiting the nodes in a circular fashion,
1799         // using FirstLane as the center point and increasing the radius
1800         // distance.
1801         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1802         for (unsigned I = 0; I < NumOperands; ++I)
1803           MainAltOps[I].push_back(getData(I, FirstLane).V);
1804 
1805         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1806           // Visit the lane on the right and then the lane on the left.
1807           for (int Direction : {+1, -1}) {
1808             int Lane = FirstLane + Direction * Distance;
1809             if (Lane < 0 || Lane >= (int)NumLanes)
1810               continue;
1811             int LastLane = Lane - Direction;
1812             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1813                    "Out of bounds");
1814             // Look for a good match for each operand.
1815             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1816               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1817               Optional<unsigned> BestIdx = getBestOperand(
1818                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1819               // By not selecting a value, we allow the operands that follow to
1820               // select a better matching value. We will get a non-null value in
1821               // the next run of getBestOperand().
1822               if (BestIdx) {
1823                 // Swap the current operand with the one returned by
1824                 // getBestOperand().
1825                 swap(OpIdx, BestIdx.getValue(), Lane);
1826               } else {
1827                 // We failed to find a best operand, set mode to 'Failed'.
1828                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1829                 // Enable the second pass.
1830                 StrategyFailed = true;
1831               }
1832               // Try to get the alternate opcode and follow it during analysis.
1833               if (MainAltOps[OpIdx].size() != 2) {
1834                 OperandData &AltOp = getData(OpIdx, Lane);
1835                 InstructionsState OpS =
1836                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1837                 if (OpS.getOpcode() && OpS.isAltShuffle())
1838                   MainAltOps[OpIdx].push_back(AltOp.V);
1839               }
1840             }
1841           }
1842         }
1843         // Skip second pass if the strategy did not fail.
1844         if (!StrategyFailed)
1845           break;
1846       }
1847     }
1848 
1849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1850     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1851       switch (RMode) {
1852       case ReorderingMode::Load:
1853         return "Load";
1854       case ReorderingMode::Opcode:
1855         return "Opcode";
1856       case ReorderingMode::Constant:
1857         return "Constant";
1858       case ReorderingMode::Splat:
1859         return "Splat";
1860       case ReorderingMode::Failed:
1861         return "Failed";
1862       }
1863       llvm_unreachable("Unimplemented Reordering Type");
1864     }
1865 
1866     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1867                                                    raw_ostream &OS) {
1868       return OS << getModeStr(RMode);
1869     }
1870 
1871     /// Debug print.
1872     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1873       printMode(RMode, dbgs());
1874     }
1875 
1876     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1877       return printMode(RMode, OS);
1878     }
1879 
1880     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1881       const unsigned Indent = 2;
1882       unsigned Cnt = 0;
1883       for (const OperandDataVec &OpDataVec : OpsVec) {
1884         OS << "Operand " << Cnt++ << "\n";
1885         for (const OperandData &OpData : OpDataVec) {
1886           OS.indent(Indent) << "{";
1887           if (Value *V = OpData.V)
1888             OS << *V;
1889           else
1890             OS << "null";
1891           OS << ", APO:" << OpData.APO << "}\n";
1892         }
1893         OS << "\n";
1894       }
1895       return OS;
1896     }
1897 
1898     /// Debug print.
1899     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1900 #endif
1901   };
1902 
1903   /// Checks if the instruction is marked for deletion.
1904   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1905 
1906   /// Marks values operands for later deletion by replacing them with Undefs.
1907   void eraseInstructions(ArrayRef<Value *> AV);
1908 
1909   ~BoUpSLP();
1910 
1911 private:
1912   /// Checks if all users of \p I are the part of the vectorization tree.
1913   bool areAllUsersVectorized(Instruction *I,
1914                              ArrayRef<Value *> VectorizedVals) const;
1915 
1916   /// \returns the cost of the vectorizable entry.
1917   InstructionCost getEntryCost(const TreeEntry *E,
1918                                ArrayRef<Value *> VectorizedVals);
1919 
1920   /// This is the recursive part of buildTree.
1921   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1922                      const EdgeInfo &EI);
1923 
1924   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1925   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1926   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1927   /// returns false, setting \p CurrentOrder to either an empty vector or a
1928   /// non-identity permutation that allows to reuse extract instructions.
1929   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1930                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1931 
1932   /// Vectorize a single entry in the tree.
1933   Value *vectorizeTree(TreeEntry *E);
1934 
1935   /// Vectorize a single entry in the tree, starting in \p VL.
1936   Value *vectorizeTree(ArrayRef<Value *> VL);
1937 
1938   /// \returns the scalarization cost for this type. Scalarization in this
1939   /// context means the creation of vectors from a group of scalars. If \p
1940   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1941   /// vector elements.
1942   InstructionCost getGatherCost(FixedVectorType *Ty,
1943                                 const DenseSet<unsigned> &ShuffledIndices,
1944                                 bool NeedToShuffle) const;
1945 
1946   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1947   /// tree entries.
1948   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1949   /// previous tree entries. \p Mask is filled with the shuffle mask.
1950   Optional<TargetTransformInfo::ShuffleKind>
1951   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1952                         SmallVectorImpl<const TreeEntry *> &Entries);
1953 
1954   /// \returns the scalarization cost for this list of values. Assuming that
1955   /// this subtree gets vectorized, we may need to extract the values from the
1956   /// roots. This method calculates the cost of extracting the values.
1957   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1958 
1959   /// Set the Builder insert point to one after the last instruction in
1960   /// the bundle
1961   void setInsertPointAfterBundle(const TreeEntry *E);
1962 
1963   /// \returns a vector from a collection of scalars in \p VL.
1964   Value *gather(ArrayRef<Value *> VL);
1965 
1966   /// \returns whether the VectorizableTree is fully vectorizable and will
1967   /// be beneficial even the tree height is tiny.
1968   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1969 
1970   /// Reorder commutative or alt operands to get better probability of
1971   /// generating vectorized code.
1972   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1973                                              SmallVectorImpl<Value *> &Left,
1974                                              SmallVectorImpl<Value *> &Right,
1975                                              const DataLayout &DL,
1976                                              ScalarEvolution &SE,
1977                                              const BoUpSLP &R);
1978   struct TreeEntry {
1979     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1980     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1981 
1982     /// \returns true if the scalars in VL are equal to this entry.
1983     bool isSame(ArrayRef<Value *> VL) const {
1984       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1985         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1986           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1987         return VL.size() == Mask.size() &&
1988                std::equal(VL.begin(), VL.end(), Mask.begin(),
1989                           [Scalars](Value *V, int Idx) {
1990                             return (isa<UndefValue>(V) &&
1991                                     Idx == UndefMaskElem) ||
1992                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1993                           });
1994       };
1995       if (!ReorderIndices.empty()) {
1996         // TODO: implement matching if the nodes are just reordered, still can
1997         // treat the vector as the same if the list of scalars matches VL
1998         // directly, without reordering.
1999         SmallVector<int> Mask;
2000         inversePermutation(ReorderIndices, Mask);
2001         if (VL.size() == Scalars.size())
2002           return IsSame(Scalars, Mask);
2003         if (VL.size() == ReuseShuffleIndices.size()) {
2004           ::addMask(Mask, ReuseShuffleIndices);
2005           return IsSame(Scalars, Mask);
2006         }
2007         return false;
2008       }
2009       return IsSame(Scalars, ReuseShuffleIndices);
2010     }
2011 
2012     /// \returns true if current entry has same operands as \p TE.
2013     bool hasEqualOperands(const TreeEntry &TE) const {
2014       if (TE.getNumOperands() != getNumOperands())
2015         return false;
2016       SmallBitVector Used(getNumOperands());
2017       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2018         unsigned PrevCount = Used.count();
2019         for (unsigned K = 0; K < E; ++K) {
2020           if (Used.test(K))
2021             continue;
2022           if (getOperand(K) == TE.getOperand(I)) {
2023             Used.set(K);
2024             break;
2025           }
2026         }
2027         // Check if we actually found the matching operand.
2028         if (PrevCount == Used.count())
2029           return false;
2030       }
2031       return true;
2032     }
2033 
2034     /// \return Final vectorization factor for the node. Defined by the total
2035     /// number of vectorized scalars, including those, used several times in the
2036     /// entry and counted in the \a ReuseShuffleIndices, if any.
2037     unsigned getVectorFactor() const {
2038       if (!ReuseShuffleIndices.empty())
2039         return ReuseShuffleIndices.size();
2040       return Scalars.size();
2041     };
2042 
2043     /// A vector of scalars.
2044     ValueList Scalars;
2045 
2046     /// The Scalars are vectorized into this value. It is initialized to Null.
2047     Value *VectorizedValue = nullptr;
2048 
2049     /// Do we need to gather this sequence or vectorize it
2050     /// (either with vector instruction or with scatter/gather
2051     /// intrinsics for store/load)?
2052     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2053     EntryState State;
2054 
2055     /// Does this sequence require some shuffling?
2056     SmallVector<int, 4> ReuseShuffleIndices;
2057 
2058     /// Does this entry require reordering?
2059     SmallVector<unsigned, 4> ReorderIndices;
2060 
2061     /// Points back to the VectorizableTree.
2062     ///
2063     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2064     /// to be a pointer and needs to be able to initialize the child iterator.
2065     /// Thus we need a reference back to the container to translate the indices
2066     /// to entries.
2067     VecTreeTy &Container;
2068 
2069     /// The TreeEntry index containing the user of this entry.  We can actually
2070     /// have multiple users so the data structure is not truly a tree.
2071     SmallVector<EdgeInfo, 1> UserTreeIndices;
2072 
2073     /// The index of this treeEntry in VectorizableTree.
2074     int Idx = -1;
2075 
2076   private:
2077     /// The operands of each instruction in each lane Operands[op_index][lane].
2078     /// Note: This helps avoid the replication of the code that performs the
2079     /// reordering of operands during buildTree_rec() and vectorizeTree().
2080     SmallVector<ValueList, 2> Operands;
2081 
2082     /// The main/alternate instruction.
2083     Instruction *MainOp = nullptr;
2084     Instruction *AltOp = nullptr;
2085 
2086   public:
2087     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2088     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2089       if (Operands.size() < OpIdx + 1)
2090         Operands.resize(OpIdx + 1);
2091       assert(Operands[OpIdx].empty() && "Already resized?");
2092       assert(OpVL.size() <= Scalars.size() &&
2093              "Number of operands is greater than the number of scalars.");
2094       Operands[OpIdx].resize(OpVL.size());
2095       copy(OpVL, Operands[OpIdx].begin());
2096     }
2097 
2098     /// Set the operands of this bundle in their original order.
2099     void setOperandsInOrder() {
2100       assert(Operands.empty() && "Already initialized?");
2101       auto *I0 = cast<Instruction>(Scalars[0]);
2102       Operands.resize(I0->getNumOperands());
2103       unsigned NumLanes = Scalars.size();
2104       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2105            OpIdx != NumOperands; ++OpIdx) {
2106         Operands[OpIdx].resize(NumLanes);
2107         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2108           auto *I = cast<Instruction>(Scalars[Lane]);
2109           assert(I->getNumOperands() == NumOperands &&
2110                  "Expected same number of operands");
2111           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2112         }
2113       }
2114     }
2115 
2116     /// Reorders operands of the node to the given mask \p Mask.
2117     void reorderOperands(ArrayRef<int> Mask) {
2118       for (ValueList &Operand : Operands)
2119         reorderScalars(Operand, Mask);
2120     }
2121 
2122     /// \returns the \p OpIdx operand of this TreeEntry.
2123     ValueList &getOperand(unsigned OpIdx) {
2124       assert(OpIdx < Operands.size() && "Off bounds");
2125       return Operands[OpIdx];
2126     }
2127 
2128     /// \returns the \p OpIdx operand of this TreeEntry.
2129     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2130       assert(OpIdx < Operands.size() && "Off bounds");
2131       return Operands[OpIdx];
2132     }
2133 
2134     /// \returns the number of operands.
2135     unsigned getNumOperands() const { return Operands.size(); }
2136 
2137     /// \return the single \p OpIdx operand.
2138     Value *getSingleOperand(unsigned OpIdx) const {
2139       assert(OpIdx < Operands.size() && "Off bounds");
2140       assert(!Operands[OpIdx].empty() && "No operand available");
2141       return Operands[OpIdx][0];
2142     }
2143 
2144     /// Some of the instructions in the list have alternate opcodes.
2145     bool isAltShuffle() const { return MainOp != AltOp; }
2146 
2147     bool isOpcodeOrAlt(Instruction *I) const {
2148       unsigned CheckedOpcode = I->getOpcode();
2149       return (getOpcode() == CheckedOpcode ||
2150               getAltOpcode() == CheckedOpcode);
2151     }
2152 
2153     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2154     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2155     /// \p OpValue.
2156     Value *isOneOf(Value *Op) const {
2157       auto *I = dyn_cast<Instruction>(Op);
2158       if (I && isOpcodeOrAlt(I))
2159         return Op;
2160       return MainOp;
2161     }
2162 
2163     void setOperations(const InstructionsState &S) {
2164       MainOp = S.MainOp;
2165       AltOp = S.AltOp;
2166     }
2167 
2168     Instruction *getMainOp() const {
2169       return MainOp;
2170     }
2171 
2172     Instruction *getAltOp() const {
2173       return AltOp;
2174     }
2175 
2176     /// The main/alternate opcodes for the list of instructions.
2177     unsigned getOpcode() const {
2178       return MainOp ? MainOp->getOpcode() : 0;
2179     }
2180 
2181     unsigned getAltOpcode() const {
2182       return AltOp ? AltOp->getOpcode() : 0;
2183     }
2184 
2185     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2186     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2187     int findLaneForValue(Value *V) const {
2188       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2189       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2190       if (!ReorderIndices.empty())
2191         FoundLane = ReorderIndices[FoundLane];
2192       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2193       if (!ReuseShuffleIndices.empty()) {
2194         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2195                                   find(ReuseShuffleIndices, FoundLane));
2196       }
2197       return FoundLane;
2198     }
2199 
2200 #ifndef NDEBUG
2201     /// Debug printer.
2202     LLVM_DUMP_METHOD void dump() const {
2203       dbgs() << Idx << ".\n";
2204       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2205         dbgs() << "Operand " << OpI << ":\n";
2206         for (const Value *V : Operands[OpI])
2207           dbgs().indent(2) << *V << "\n";
2208       }
2209       dbgs() << "Scalars: \n";
2210       for (Value *V : Scalars)
2211         dbgs().indent(2) << *V << "\n";
2212       dbgs() << "State: ";
2213       switch (State) {
2214       case Vectorize:
2215         dbgs() << "Vectorize\n";
2216         break;
2217       case ScatterVectorize:
2218         dbgs() << "ScatterVectorize\n";
2219         break;
2220       case NeedToGather:
2221         dbgs() << "NeedToGather\n";
2222         break;
2223       }
2224       dbgs() << "MainOp: ";
2225       if (MainOp)
2226         dbgs() << *MainOp << "\n";
2227       else
2228         dbgs() << "NULL\n";
2229       dbgs() << "AltOp: ";
2230       if (AltOp)
2231         dbgs() << *AltOp << "\n";
2232       else
2233         dbgs() << "NULL\n";
2234       dbgs() << "VectorizedValue: ";
2235       if (VectorizedValue)
2236         dbgs() << *VectorizedValue << "\n";
2237       else
2238         dbgs() << "NULL\n";
2239       dbgs() << "ReuseShuffleIndices: ";
2240       if (ReuseShuffleIndices.empty())
2241         dbgs() << "Empty";
2242       else
2243         for (int ReuseIdx : ReuseShuffleIndices)
2244           dbgs() << ReuseIdx << ", ";
2245       dbgs() << "\n";
2246       dbgs() << "ReorderIndices: ";
2247       for (unsigned ReorderIdx : ReorderIndices)
2248         dbgs() << ReorderIdx << ", ";
2249       dbgs() << "\n";
2250       dbgs() << "UserTreeIndices: ";
2251       for (const auto &EInfo : UserTreeIndices)
2252         dbgs() << EInfo << ", ";
2253       dbgs() << "\n";
2254     }
2255 #endif
2256   };
2257 
2258 #ifndef NDEBUG
2259   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2260                      InstructionCost VecCost,
2261                      InstructionCost ScalarCost) const {
2262     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2263     dbgs() << "SLP: Costs:\n";
2264     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2265     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2266     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2267     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2268                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2269   }
2270 #endif
2271 
2272   /// Create a new VectorizableTree entry.
2273   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2274                           const InstructionsState &S,
2275                           const EdgeInfo &UserTreeIdx,
2276                           ArrayRef<int> ReuseShuffleIndices = None,
2277                           ArrayRef<unsigned> ReorderIndices = None) {
2278     TreeEntry::EntryState EntryState =
2279         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2280     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2281                         ReuseShuffleIndices, ReorderIndices);
2282   }
2283 
2284   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2285                           TreeEntry::EntryState EntryState,
2286                           Optional<ScheduleData *> Bundle,
2287                           const InstructionsState &S,
2288                           const EdgeInfo &UserTreeIdx,
2289                           ArrayRef<int> ReuseShuffleIndices = None,
2290                           ArrayRef<unsigned> ReorderIndices = None) {
2291     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2292             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2293            "Need to vectorize gather entry?");
2294     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2295     TreeEntry *Last = VectorizableTree.back().get();
2296     Last->Idx = VectorizableTree.size() - 1;
2297     Last->State = EntryState;
2298     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2299                                      ReuseShuffleIndices.end());
2300     if (ReorderIndices.empty()) {
2301       Last->Scalars.assign(VL.begin(), VL.end());
2302       Last->setOperations(S);
2303     } else {
2304       // Reorder scalars and build final mask.
2305       Last->Scalars.assign(VL.size(), nullptr);
2306       transform(ReorderIndices, Last->Scalars.begin(),
2307                 [VL](unsigned Idx) -> Value * {
2308                   if (Idx >= VL.size())
2309                     return UndefValue::get(VL.front()->getType());
2310                   return VL[Idx];
2311                 });
2312       InstructionsState S = getSameOpcode(Last->Scalars);
2313       Last->setOperations(S);
2314       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2315     }
2316     if (Last->State != TreeEntry::NeedToGather) {
2317       for (Value *V : VL) {
2318         assert(!getTreeEntry(V) && "Scalar already in tree!");
2319         ScalarToTreeEntry[V] = Last;
2320       }
2321       // Update the scheduler bundle to point to this TreeEntry.
2322       unsigned Lane = 0;
2323       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2324            BundleMember = BundleMember->NextInBundle) {
2325         BundleMember->TE = Last;
2326         BundleMember->Lane = Lane;
2327         ++Lane;
2328       }
2329       assert((!Bundle.getValue() || Lane == VL.size()) &&
2330              "Bundle and VL out of sync");
2331     } else {
2332       MustGather.insert(VL.begin(), VL.end());
2333     }
2334 
2335     if (UserTreeIdx.UserTE)
2336       Last->UserTreeIndices.push_back(UserTreeIdx);
2337 
2338     return Last;
2339   }
2340 
2341   /// -- Vectorization State --
2342   /// Holds all of the tree entries.
2343   TreeEntry::VecTreeTy VectorizableTree;
2344 
2345 #ifndef NDEBUG
2346   /// Debug printer.
2347   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2348     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2349       VectorizableTree[Id]->dump();
2350       dbgs() << "\n";
2351     }
2352   }
2353 #endif
2354 
2355   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2356 
2357   const TreeEntry *getTreeEntry(Value *V) const {
2358     return ScalarToTreeEntry.lookup(V);
2359   }
2360 
2361   /// Maps a specific scalar to its tree entry.
2362   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2363 
2364   /// Maps a value to the proposed vectorizable size.
2365   SmallDenseMap<Value *, unsigned> InstrElementSize;
2366 
2367   /// A list of scalars that we found that we need to keep as scalars.
2368   ValueSet MustGather;
2369 
2370   /// This POD struct describes one external user in the vectorized tree.
2371   struct ExternalUser {
2372     ExternalUser(Value *S, llvm::User *U, int L)
2373         : Scalar(S), User(U), Lane(L) {}
2374 
2375     // Which scalar in our function.
2376     Value *Scalar;
2377 
2378     // Which user that uses the scalar.
2379     llvm::User *User;
2380 
2381     // Which lane does the scalar belong to.
2382     int Lane;
2383   };
2384   using UserList = SmallVector<ExternalUser, 16>;
2385 
2386   /// Checks if two instructions may access the same memory.
2387   ///
2388   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2389   /// is invariant in the calling loop.
2390   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2391                  Instruction *Inst2) {
2392     // First check if the result is already in the cache.
2393     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2394     Optional<bool> &result = AliasCache[key];
2395     if (result.hasValue()) {
2396       return result.getValue();
2397     }
2398     bool aliased = true;
2399     if (Loc1.Ptr && isSimple(Inst1))
2400       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2401     // Store the result in the cache.
2402     result = aliased;
2403     return aliased;
2404   }
2405 
2406   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2407 
2408   /// Cache for alias results.
2409   /// TODO: consider moving this to the AliasAnalysis itself.
2410   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2411 
2412   /// Removes an instruction from its block and eventually deletes it.
2413   /// It's like Instruction::eraseFromParent() except that the actual deletion
2414   /// is delayed until BoUpSLP is destructed.
2415   /// This is required to ensure that there are no incorrect collisions in the
2416   /// AliasCache, which can happen if a new instruction is allocated at the
2417   /// same address as a previously deleted instruction.
2418   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2419     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2420     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2421   }
2422 
2423   /// Temporary store for deleted instructions. Instructions will be deleted
2424   /// eventually when the BoUpSLP is destructed.
2425   DenseMap<Instruction *, bool> DeletedInstructions;
2426 
2427   /// A list of values that need to extracted out of the tree.
2428   /// This list holds pairs of (Internal Scalar : External User). External User
2429   /// can be nullptr, it means that this Internal Scalar will be used later,
2430   /// after vectorization.
2431   UserList ExternalUses;
2432 
2433   /// Values used only by @llvm.assume calls.
2434   SmallPtrSet<const Value *, 32> EphValues;
2435 
2436   /// Holds all of the instructions that we gathered.
2437   SetVector<Instruction *> GatherShuffleSeq;
2438 
2439   /// A list of blocks that we are going to CSE.
2440   SetVector<BasicBlock *> CSEBlocks;
2441 
2442   /// Contains all scheduling relevant data for an instruction.
2443   /// A ScheduleData either represents a single instruction or a member of an
2444   /// instruction bundle (= a group of instructions which is combined into a
2445   /// vector instruction).
2446   struct ScheduleData {
2447     // The initial value for the dependency counters. It means that the
2448     // dependencies are not calculated yet.
2449     enum { InvalidDeps = -1 };
2450 
2451     ScheduleData() = default;
2452 
2453     void init(int BlockSchedulingRegionID, Value *OpVal) {
2454       FirstInBundle = this;
2455       NextInBundle = nullptr;
2456       NextLoadStore = nullptr;
2457       IsScheduled = false;
2458       SchedulingRegionID = BlockSchedulingRegionID;
2459       UnscheduledDepsInBundle = UnscheduledDeps;
2460       clearDependencies();
2461       OpValue = OpVal;
2462       TE = nullptr;
2463       Lane = -1;
2464     }
2465 
2466     /// Verify basic self consistency properties
2467     void verify() {
2468       if (hasValidDependencies()) {
2469         assert(UnscheduledDeps <= Dependencies && "invariant");
2470         assert(UnscheduledDeps <= FirstInBundle->UnscheduledDepsInBundle &&
2471                "bundle must have at least as many dependencies as member");
2472       }
2473 
2474       if (IsScheduled) {
2475         assert(isSchedulingEntity() && hasValidDependencies() &&
2476                UnscheduledDeps == 0 &&
2477                "unexpected scheduled state");
2478       }
2479     }
2480 
2481     /// Returns true if the dependency information has been calculated.
2482     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2483 
2484     /// Returns true for single instructions and for bundle representatives
2485     /// (= the head of a bundle).
2486     bool isSchedulingEntity() const { return FirstInBundle == this; }
2487 
2488     /// Returns true if it represents an instruction bundle and not only a
2489     /// single instruction.
2490     bool isPartOfBundle() const {
2491       return NextInBundle != nullptr || FirstInBundle != this;
2492     }
2493 
2494     /// Returns true if it is ready for scheduling, i.e. it has no more
2495     /// unscheduled depending instructions/bundles.
2496     bool isReady() const {
2497       assert(isSchedulingEntity() &&
2498              "can't consider non-scheduling entity for ready list");
2499       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2500     }
2501 
2502     /// Modifies the number of unscheduled dependencies, also updating it for
2503     /// the whole bundle.
2504     int incrementUnscheduledDeps(int Incr) {
2505       UnscheduledDeps += Incr;
2506       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2507     }
2508 
2509     /// Sets the number of unscheduled dependencies to the number of
2510     /// dependencies.
2511     void resetUnscheduledDeps() {
2512       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2513     }
2514 
2515     /// Clears all dependency information.
2516     void clearDependencies() {
2517       Dependencies = InvalidDeps;
2518       resetUnscheduledDeps();
2519       MemoryDependencies.clear();
2520     }
2521 
2522     void dump(raw_ostream &os) const {
2523       if (!isSchedulingEntity()) {
2524         os << "/ " << *Inst;
2525       } else if (NextInBundle) {
2526         os << '[' << *Inst;
2527         ScheduleData *SD = NextInBundle;
2528         while (SD) {
2529           os << ';' << *SD->Inst;
2530           SD = SD->NextInBundle;
2531         }
2532         os << ']';
2533       } else {
2534         os << *Inst;
2535       }
2536     }
2537 
2538     Instruction *Inst = nullptr;
2539 
2540     /// Points to the head in an instruction bundle (and always to this for
2541     /// single instructions).
2542     ScheduleData *FirstInBundle = nullptr;
2543 
2544     /// Single linked list of all instructions in a bundle. Null if it is a
2545     /// single instruction.
2546     ScheduleData *NextInBundle = nullptr;
2547 
2548     /// Single linked list of all memory instructions (e.g. load, store, call)
2549     /// in the block - until the end of the scheduling region.
2550     ScheduleData *NextLoadStore = nullptr;
2551 
2552     /// The dependent memory instructions.
2553     /// This list is derived on demand in calculateDependencies().
2554     SmallVector<ScheduleData *, 4> MemoryDependencies;
2555 
2556     /// This ScheduleData is in the current scheduling region if this matches
2557     /// the current SchedulingRegionID of BlockScheduling.
2558     int SchedulingRegionID = 0;
2559 
2560     /// Used for getting a "good" final ordering of instructions.
2561     int SchedulingPriority = 0;
2562 
2563     /// The number of dependencies. Constitutes of the number of users of the
2564     /// instruction plus the number of dependent memory instructions (if any).
2565     /// This value is calculated on demand.
2566     /// If InvalidDeps, the number of dependencies is not calculated yet.
2567     int Dependencies = InvalidDeps;
2568 
2569     /// The number of dependencies minus the number of dependencies of scheduled
2570     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2571     /// for scheduling.
2572     /// Note that this is negative as long as Dependencies is not calculated.
2573     int UnscheduledDeps = InvalidDeps;
2574 
2575     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2576     /// single instructions.
2577     int UnscheduledDepsInBundle = InvalidDeps;
2578 
2579     /// True if this instruction is scheduled (or considered as scheduled in the
2580     /// dry-run).
2581     bool IsScheduled = false;
2582 
2583     /// Opcode of the current instruction in the schedule data.
2584     Value *OpValue = nullptr;
2585 
2586     /// The TreeEntry that this instruction corresponds to.
2587     TreeEntry *TE = nullptr;
2588 
2589     /// The lane of this node in the TreeEntry.
2590     int Lane = -1;
2591   };
2592 
2593 #ifndef NDEBUG
2594   friend inline raw_ostream &operator<<(raw_ostream &os,
2595                                         const BoUpSLP::ScheduleData &SD) {
2596     SD.dump(os);
2597     return os;
2598   }
2599 #endif
2600 
2601   friend struct GraphTraits<BoUpSLP *>;
2602   friend struct DOTGraphTraits<BoUpSLP *>;
2603 
2604   /// Contains all scheduling data for a basic block.
2605   struct BlockScheduling {
2606     BlockScheduling(BasicBlock *BB)
2607         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2608 
2609     void clear() {
2610       ReadyInsts.clear();
2611       ScheduleStart = nullptr;
2612       ScheduleEnd = nullptr;
2613       FirstLoadStoreInRegion = nullptr;
2614       LastLoadStoreInRegion = nullptr;
2615 
2616       // Reduce the maximum schedule region size by the size of the
2617       // previous scheduling run.
2618       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2619       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2620         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2621       ScheduleRegionSize = 0;
2622 
2623       // Make a new scheduling region, i.e. all existing ScheduleData is not
2624       // in the new region yet.
2625       ++SchedulingRegionID;
2626     }
2627 
2628     ScheduleData *getScheduleData(Value *V) {
2629       ScheduleData *SD = ScheduleDataMap[V];
2630       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2631         return SD;
2632       return nullptr;
2633     }
2634 
2635     ScheduleData *getScheduleData(Value *V, Value *Key) {
2636       if (V == Key)
2637         return getScheduleData(V);
2638       auto I = ExtraScheduleDataMap.find(V);
2639       if (I != ExtraScheduleDataMap.end()) {
2640         ScheduleData *SD = I->second[Key];
2641         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2642           return SD;
2643       }
2644       return nullptr;
2645     }
2646 
2647     bool isInSchedulingRegion(ScheduleData *SD) const {
2648       return SD->SchedulingRegionID == SchedulingRegionID;
2649     }
2650 
2651     /// Marks an instruction as scheduled and puts all dependent ready
2652     /// instructions into the ready-list.
2653     template <typename ReadyListType>
2654     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2655       SD->IsScheduled = true;
2656       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2657 
2658       for (ScheduleData *BundleMember = SD; BundleMember;
2659            BundleMember = BundleMember->NextInBundle) {
2660         if (BundleMember->Inst != BundleMember->OpValue)
2661           continue;
2662 
2663         // Handle the def-use chain dependencies.
2664 
2665         // Decrement the unscheduled counter and insert to ready list if ready.
2666         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2667           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2668             if (OpDef && OpDef->hasValidDependencies() &&
2669                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2670               // There are no more unscheduled dependencies after
2671               // decrementing, so we can put the dependent instruction
2672               // into the ready list.
2673               ScheduleData *DepBundle = OpDef->FirstInBundle;
2674               assert(!DepBundle->IsScheduled &&
2675                      "already scheduled bundle gets ready");
2676               ReadyList.insert(DepBundle);
2677               LLVM_DEBUG(dbgs()
2678                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2679             }
2680           });
2681         };
2682 
2683         // If BundleMember is a vector bundle, its operands may have been
2684         // reordered during buildTree(). We therefore need to get its operands
2685         // through the TreeEntry.
2686         if (TreeEntry *TE = BundleMember->TE) {
2687           int Lane = BundleMember->Lane;
2688           assert(Lane >= 0 && "Lane not set");
2689 
2690           // Since vectorization tree is being built recursively this assertion
2691           // ensures that the tree entry has all operands set before reaching
2692           // this code. Couple of exceptions known at the moment are extracts
2693           // where their second (immediate) operand is not added. Since
2694           // immediates do not affect scheduler behavior this is considered
2695           // okay.
2696           auto *In = TE->getMainOp();
2697           assert(In &&
2698                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2699                   In->getNumOperands() == TE->getNumOperands()) &&
2700                  "Missed TreeEntry operands?");
2701           (void)In; // fake use to avoid build failure when assertions disabled
2702 
2703           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2704                OpIdx != NumOperands; ++OpIdx)
2705             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2706               DecrUnsched(I);
2707         } else {
2708           // If BundleMember is a stand-alone instruction, no operand reordering
2709           // has taken place, so we directly access its operands.
2710           for (Use &U : BundleMember->Inst->operands())
2711             if (auto *I = dyn_cast<Instruction>(U.get()))
2712               DecrUnsched(I);
2713         }
2714         // Handle the memory dependencies.
2715         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2716           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2717             // There are no more unscheduled dependencies after decrementing,
2718             // so we can put the dependent instruction into the ready list.
2719             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2720             assert(!DepBundle->IsScheduled &&
2721                    "already scheduled bundle gets ready");
2722             ReadyList.insert(DepBundle);
2723             LLVM_DEBUG(dbgs()
2724                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2725           }
2726         }
2727       }
2728     }
2729 
2730     /// Verify basic self consistency properties of the data structure.
2731     void verify() {
2732       if (!ScheduleStart)
2733         return;
2734 
2735       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2736              ScheduleStart->comesBefore(ScheduleEnd) &&
2737              "Not a valid scheduling region?");
2738 
2739       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2740         auto *SD = getScheduleData(I);
2741         assert(SD && "primary scheduledata must exist in window");
2742         assert(isInSchedulingRegion(SD) &&
2743                "primary schedule data not in window?");
2744         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2745       }
2746 
2747       for (auto *SD : ReadyInsts) {
2748         assert(SD->isSchedulingEntity() && SD->isReady() &&
2749                "item in ready list not ready?");
2750       }
2751     }
2752 
2753     void doForAllOpcodes(Value *V,
2754                          function_ref<void(ScheduleData *SD)> Action) {
2755       if (ScheduleData *SD = getScheduleData(V))
2756         Action(SD);
2757       auto I = ExtraScheduleDataMap.find(V);
2758       if (I != ExtraScheduleDataMap.end())
2759         for (auto &P : I->second)
2760           if (P.second->SchedulingRegionID == SchedulingRegionID)
2761             Action(P.second);
2762     }
2763 
2764     /// Put all instructions into the ReadyList which are ready for scheduling.
2765     template <typename ReadyListType>
2766     void initialFillReadyList(ReadyListType &ReadyList) {
2767       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2768         doForAllOpcodes(I, [&](ScheduleData *SD) {
2769           if (SD->isSchedulingEntity() && SD->isReady()) {
2770             ReadyList.insert(SD);
2771             LLVM_DEBUG(dbgs()
2772                        << "SLP:    initially in ready list: " << *SD << "\n");
2773           }
2774         });
2775       }
2776     }
2777 
2778     /// Build a bundle from the ScheduleData nodes corresponding to the
2779     /// scalar instruction for each lane.
2780     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2781 
2782     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2783     /// cyclic dependencies. This is only a dry-run, no instructions are
2784     /// actually moved at this stage.
2785     /// \returns the scheduling bundle. The returned Optional value is non-None
2786     /// if \p VL is allowed to be scheduled.
2787     Optional<ScheduleData *>
2788     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2789                       const InstructionsState &S);
2790 
2791     /// Un-bundles a group of instructions.
2792     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2793 
2794     /// Allocates schedule data chunk.
2795     ScheduleData *allocateScheduleDataChunks();
2796 
2797     /// Extends the scheduling region so that V is inside the region.
2798     /// \returns true if the region size is within the limit.
2799     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2800 
2801     /// Initialize the ScheduleData structures for new instructions in the
2802     /// scheduling region.
2803     void initScheduleData(Instruction *FromI, Instruction *ToI,
2804                           ScheduleData *PrevLoadStore,
2805                           ScheduleData *NextLoadStore);
2806 
2807     /// Updates the dependency information of a bundle and of all instructions/
2808     /// bundles which depend on the original bundle.
2809     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2810                                BoUpSLP *SLP);
2811 
2812     /// Sets all instruction in the scheduling region to un-scheduled.
2813     void resetSchedule();
2814 
2815     BasicBlock *BB;
2816 
2817     /// Simple memory allocation for ScheduleData.
2818     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2819 
2820     /// The size of a ScheduleData array in ScheduleDataChunks.
2821     int ChunkSize;
2822 
2823     /// The allocator position in the current chunk, which is the last entry
2824     /// of ScheduleDataChunks.
2825     int ChunkPos;
2826 
2827     /// Attaches ScheduleData to Instruction.
2828     /// Note that the mapping survives during all vectorization iterations, i.e.
2829     /// ScheduleData structures are recycled.
2830     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2831 
2832     /// Attaches ScheduleData to Instruction with the leading key.
2833     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2834         ExtraScheduleDataMap;
2835 
2836     /// The ready-list for scheduling (only used for the dry-run).
2837     SetVector<ScheduleData *> ReadyInsts;
2838 
2839     /// The first instruction of the scheduling region.
2840     Instruction *ScheduleStart = nullptr;
2841 
2842     /// The first instruction _after_ the scheduling region.
2843     Instruction *ScheduleEnd = nullptr;
2844 
2845     /// The first memory accessing instruction in the scheduling region
2846     /// (can be null).
2847     ScheduleData *FirstLoadStoreInRegion = nullptr;
2848 
2849     /// The last memory accessing instruction in the scheduling region
2850     /// (can be null).
2851     ScheduleData *LastLoadStoreInRegion = nullptr;
2852 
2853     /// The current size of the scheduling region.
2854     int ScheduleRegionSize = 0;
2855 
2856     /// The maximum size allowed for the scheduling region.
2857     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2858 
2859     /// The ID of the scheduling region. For a new vectorization iteration this
2860     /// is incremented which "removes" all ScheduleData from the region.
2861     // Make sure that the initial SchedulingRegionID is greater than the
2862     // initial SchedulingRegionID in ScheduleData (which is 0).
2863     int SchedulingRegionID = 1;
2864   };
2865 
2866   /// Attaches the BlockScheduling structures to basic blocks.
2867   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2868 
2869   /// Performs the "real" scheduling. Done before vectorization is actually
2870   /// performed in a basic block.
2871   void scheduleBlock(BlockScheduling *BS);
2872 
2873   /// List of users to ignore during scheduling and that don't need extracting.
2874   ArrayRef<Value *> UserIgnoreList;
2875 
2876   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2877   /// sorted SmallVectors of unsigned.
2878   struct OrdersTypeDenseMapInfo {
2879     static OrdersType getEmptyKey() {
2880       OrdersType V;
2881       V.push_back(~1U);
2882       return V;
2883     }
2884 
2885     static OrdersType getTombstoneKey() {
2886       OrdersType V;
2887       V.push_back(~2U);
2888       return V;
2889     }
2890 
2891     static unsigned getHashValue(const OrdersType &V) {
2892       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2893     }
2894 
2895     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2896       return LHS == RHS;
2897     }
2898   };
2899 
2900   // Analysis and block reference.
2901   Function *F;
2902   ScalarEvolution *SE;
2903   TargetTransformInfo *TTI;
2904   TargetLibraryInfo *TLI;
2905   AAResults *AA;
2906   LoopInfo *LI;
2907   DominatorTree *DT;
2908   AssumptionCache *AC;
2909   DemandedBits *DB;
2910   const DataLayout *DL;
2911   OptimizationRemarkEmitter *ORE;
2912 
2913   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2914   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2915 
2916   /// Instruction builder to construct the vectorized tree.
2917   IRBuilder<> Builder;
2918 
2919   /// A map of scalar integer values to the smallest bit width with which they
2920   /// can legally be represented. The values map to (width, signed) pairs,
2921   /// where "width" indicates the minimum bit width and "signed" is True if the
2922   /// value must be signed-extended, rather than zero-extended, back to its
2923   /// original width.
2924   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2925 };
2926 
2927 } // end namespace slpvectorizer
2928 
2929 template <> struct GraphTraits<BoUpSLP *> {
2930   using TreeEntry = BoUpSLP::TreeEntry;
2931 
2932   /// NodeRef has to be a pointer per the GraphWriter.
2933   using NodeRef = TreeEntry *;
2934 
2935   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2936 
2937   /// Add the VectorizableTree to the index iterator to be able to return
2938   /// TreeEntry pointers.
2939   struct ChildIteratorType
2940       : public iterator_adaptor_base<
2941             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2942     ContainerTy &VectorizableTree;
2943 
2944     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2945                       ContainerTy &VT)
2946         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2947 
2948     NodeRef operator*() { return I->UserTE; }
2949   };
2950 
2951   static NodeRef getEntryNode(BoUpSLP &R) {
2952     return R.VectorizableTree[0].get();
2953   }
2954 
2955   static ChildIteratorType child_begin(NodeRef N) {
2956     return {N->UserTreeIndices.begin(), N->Container};
2957   }
2958 
2959   static ChildIteratorType child_end(NodeRef N) {
2960     return {N->UserTreeIndices.end(), N->Container};
2961   }
2962 
2963   /// For the node iterator we just need to turn the TreeEntry iterator into a
2964   /// TreeEntry* iterator so that it dereferences to NodeRef.
2965   class nodes_iterator {
2966     using ItTy = ContainerTy::iterator;
2967     ItTy It;
2968 
2969   public:
2970     nodes_iterator(const ItTy &It2) : It(It2) {}
2971     NodeRef operator*() { return It->get(); }
2972     nodes_iterator operator++() {
2973       ++It;
2974       return *this;
2975     }
2976     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2977   };
2978 
2979   static nodes_iterator nodes_begin(BoUpSLP *R) {
2980     return nodes_iterator(R->VectorizableTree.begin());
2981   }
2982 
2983   static nodes_iterator nodes_end(BoUpSLP *R) {
2984     return nodes_iterator(R->VectorizableTree.end());
2985   }
2986 
2987   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2988 };
2989 
2990 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2991   using TreeEntry = BoUpSLP::TreeEntry;
2992 
2993   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2994 
2995   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2996     std::string Str;
2997     raw_string_ostream OS(Str);
2998     if (isSplat(Entry->Scalars))
2999       OS << "<splat> ";
3000     for (auto V : Entry->Scalars) {
3001       OS << *V;
3002       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3003             return EU.Scalar == V;
3004           }))
3005         OS << " <extract>";
3006       OS << "\n";
3007     }
3008     return Str;
3009   }
3010 
3011   static std::string getNodeAttributes(const TreeEntry *Entry,
3012                                        const BoUpSLP *) {
3013     if (Entry->State == TreeEntry::NeedToGather)
3014       return "color=red";
3015     return "";
3016   }
3017 };
3018 
3019 } // end namespace llvm
3020 
3021 BoUpSLP::~BoUpSLP() {
3022   for (const auto &Pair : DeletedInstructions) {
3023     // Replace operands of ignored instructions with Undefs in case if they were
3024     // marked for deletion.
3025     if (Pair.getSecond()) {
3026       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3027       Pair.getFirst()->replaceAllUsesWith(Undef);
3028     }
3029     Pair.getFirst()->dropAllReferences();
3030   }
3031   for (const auto &Pair : DeletedInstructions) {
3032     assert(Pair.getFirst()->use_empty() &&
3033            "trying to erase instruction with users.");
3034     Pair.getFirst()->eraseFromParent();
3035   }
3036 #ifdef EXPENSIVE_CHECKS
3037   // If we could guarantee that this call is not extremely slow, we could
3038   // remove the ifdef limitation (see PR47712).
3039   assert(!verifyFunction(*F, &dbgs()));
3040 #endif
3041 }
3042 
3043 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3044   for (auto *V : AV) {
3045     if (auto *I = dyn_cast<Instruction>(V))
3046       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3047   };
3048 }
3049 
3050 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3051 /// contains original mask for the scalars reused in the node. Procedure
3052 /// transform this mask in accordance with the given \p Mask.
3053 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3054   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3055          "Expected non-empty mask.");
3056   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3057   Prev.swap(Reuses);
3058   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3059     if (Mask[I] != UndefMaskElem)
3060       Reuses[Mask[I]] = Prev[I];
3061 }
3062 
3063 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3064 /// the original order of the scalars. Procedure transforms the provided order
3065 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3066 /// identity order, \p Order is cleared.
3067 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3068   assert(!Mask.empty() && "Expected non-empty mask.");
3069   SmallVector<int> MaskOrder;
3070   if (Order.empty()) {
3071     MaskOrder.resize(Mask.size());
3072     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3073   } else {
3074     inversePermutation(Order, MaskOrder);
3075   }
3076   reorderReuses(MaskOrder, Mask);
3077   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3078     Order.clear();
3079     return;
3080   }
3081   Order.assign(Mask.size(), Mask.size());
3082   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3083     if (MaskOrder[I] != UndefMaskElem)
3084       Order[MaskOrder[I]] = I;
3085   fixupOrderingIndices(Order);
3086 }
3087 
3088 Optional<BoUpSLP::OrdersType>
3089 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3090   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3091   unsigned NumScalars = TE.Scalars.size();
3092   OrdersType CurrentOrder(NumScalars, NumScalars);
3093   SmallVector<int> Positions;
3094   SmallBitVector UsedPositions(NumScalars);
3095   const TreeEntry *STE = nullptr;
3096   // Try to find all gathered scalars that are gets vectorized in other
3097   // vectorize node. Here we can have only one single tree vector node to
3098   // correctly identify order of the gathered scalars.
3099   for (unsigned I = 0; I < NumScalars; ++I) {
3100     Value *V = TE.Scalars[I];
3101     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3102       continue;
3103     if (const auto *LocalSTE = getTreeEntry(V)) {
3104       if (!STE)
3105         STE = LocalSTE;
3106       else if (STE != LocalSTE)
3107         // Take the order only from the single vector node.
3108         return None;
3109       unsigned Lane =
3110           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3111       if (Lane >= NumScalars)
3112         return None;
3113       if (CurrentOrder[Lane] != NumScalars) {
3114         if (Lane != I)
3115           continue;
3116         UsedPositions.reset(CurrentOrder[Lane]);
3117       }
3118       // The partial identity (where only some elements of the gather node are
3119       // in the identity order) is good.
3120       CurrentOrder[Lane] = I;
3121       UsedPositions.set(I);
3122     }
3123   }
3124   // Need to keep the order if we have a vector entry and at least 2 scalars or
3125   // the vectorized entry has just 2 scalars.
3126   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3127     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3128       for (unsigned I = 0; I < NumScalars; ++I)
3129         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3130           return false;
3131       return true;
3132     };
3133     if (IsIdentityOrder(CurrentOrder)) {
3134       CurrentOrder.clear();
3135       return CurrentOrder;
3136     }
3137     auto *It = CurrentOrder.begin();
3138     for (unsigned I = 0; I < NumScalars;) {
3139       if (UsedPositions.test(I)) {
3140         ++I;
3141         continue;
3142       }
3143       if (*It == NumScalars) {
3144         *It = I;
3145         ++I;
3146       }
3147       ++It;
3148     }
3149     return CurrentOrder;
3150   }
3151   return None;
3152 }
3153 
3154 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3155                                                          bool TopToBottom) {
3156   // No need to reorder if need to shuffle reuses, still need to shuffle the
3157   // node.
3158   if (!TE.ReuseShuffleIndices.empty())
3159     return None;
3160   if (TE.State == TreeEntry::Vectorize &&
3161       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3162        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3163       !TE.isAltShuffle())
3164     return TE.ReorderIndices;
3165   if (TE.State == TreeEntry::NeedToGather) {
3166     // TODO: add analysis of other gather nodes with extractelement
3167     // instructions and other values/instructions, not only undefs.
3168     if (((TE.getOpcode() == Instruction::ExtractElement &&
3169           !TE.isAltShuffle()) ||
3170          (all_of(TE.Scalars,
3171                  [](Value *V) {
3172                    return isa<UndefValue, ExtractElementInst>(V);
3173                  }) &&
3174           any_of(TE.Scalars,
3175                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3176         all_of(TE.Scalars,
3177                [](Value *V) {
3178                  auto *EE = dyn_cast<ExtractElementInst>(V);
3179                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3180                }) &&
3181         allSameType(TE.Scalars)) {
3182       // Check that gather of extractelements can be represented as
3183       // just a shuffle of a single vector.
3184       OrdersType CurrentOrder;
3185       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3186       if (Reuse || !CurrentOrder.empty()) {
3187         if (!CurrentOrder.empty())
3188           fixupOrderingIndices(CurrentOrder);
3189         return CurrentOrder;
3190       }
3191     }
3192     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3193       return CurrentOrder;
3194   }
3195   return None;
3196 }
3197 
3198 void BoUpSLP::reorderTopToBottom() {
3199   // Maps VF to the graph nodes.
3200   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3201   // ExtractElement gather nodes which can be vectorized and need to handle
3202   // their ordering.
3203   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3204   // Find all reorderable nodes with the given VF.
3205   // Currently the are vectorized stores,loads,extracts + some gathering of
3206   // extracts.
3207   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3208                                  const std::unique_ptr<TreeEntry> &TE) {
3209     if (Optional<OrdersType> CurrentOrder =
3210             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3211       // Do not include ordering for nodes used in the alt opcode vectorization,
3212       // better to reorder them during bottom-to-top stage. If follow the order
3213       // here, it causes reordering of the whole graph though actually it is
3214       // profitable just to reorder the subgraph that starts from the alternate
3215       // opcode vectorization node. Such nodes already end-up with the shuffle
3216       // instruction and it is just enough to change this shuffle rather than
3217       // rotate the scalars for the whole graph.
3218       unsigned Cnt = 0;
3219       const TreeEntry *UserTE = TE.get();
3220       while (UserTE && Cnt < RecursionMaxDepth) {
3221         if (UserTE->UserTreeIndices.size() != 1)
3222           break;
3223         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3224               return EI.UserTE->State == TreeEntry::Vectorize &&
3225                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3226             }))
3227           return;
3228         if (UserTE->UserTreeIndices.empty())
3229           UserTE = nullptr;
3230         else
3231           UserTE = UserTE->UserTreeIndices.back().UserTE;
3232         ++Cnt;
3233       }
3234       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3235       if (TE->State != TreeEntry::Vectorize)
3236         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3237     }
3238   });
3239 
3240   // Reorder the graph nodes according to their vectorization factor.
3241   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3242        VF /= 2) {
3243     auto It = VFToOrderedEntries.find(VF);
3244     if (It == VFToOrderedEntries.end())
3245       continue;
3246     // Try to find the most profitable order. We just are looking for the most
3247     // used order and reorder scalar elements in the nodes according to this
3248     // mostly used order.
3249     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3250     // All operands are reordered and used only in this node - propagate the
3251     // most used order to the user node.
3252     MapVector<OrdersType, unsigned,
3253               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3254         OrdersUses;
3255     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3256     for (const TreeEntry *OpTE : OrderedEntries) {
3257       // No need to reorder this nodes, still need to extend and to use shuffle,
3258       // just need to merge reordering shuffle and the reuse shuffle.
3259       if (!OpTE->ReuseShuffleIndices.empty())
3260         continue;
3261       // Count number of orders uses.
3262       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3263         if (OpTE->State == TreeEntry::NeedToGather)
3264           return GathersToOrders.find(OpTE)->second;
3265         return OpTE->ReorderIndices;
3266       }();
3267       // Stores actually store the mask, not the order, need to invert.
3268       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3269           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3270         SmallVector<int> Mask;
3271         inversePermutation(Order, Mask);
3272         unsigned E = Order.size();
3273         OrdersType CurrentOrder(E, E);
3274         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3275           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3276         });
3277         fixupOrderingIndices(CurrentOrder);
3278         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3279       } else {
3280         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3281       }
3282     }
3283     // Set order of the user node.
3284     if (OrdersUses.empty())
3285       continue;
3286     // Choose the most used order.
3287     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3288     unsigned Cnt = OrdersUses.front().second;
3289     for (const auto &Pair : drop_begin(OrdersUses)) {
3290       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3291         BestOrder = Pair.first;
3292         Cnt = Pair.second;
3293       }
3294     }
3295     // Set order of the user node.
3296     if (BestOrder.empty())
3297       continue;
3298     SmallVector<int> Mask;
3299     inversePermutation(BestOrder, Mask);
3300     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3301     unsigned E = BestOrder.size();
3302     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3303       return I < E ? static_cast<int>(I) : UndefMaskElem;
3304     });
3305     // Do an actual reordering, if profitable.
3306     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3307       // Just do the reordering for the nodes with the given VF.
3308       if (TE->Scalars.size() != VF) {
3309         if (TE->ReuseShuffleIndices.size() == VF) {
3310           // Need to reorder the reuses masks of the operands with smaller VF to
3311           // be able to find the match between the graph nodes and scalar
3312           // operands of the given node during vectorization/cost estimation.
3313           assert(all_of(TE->UserTreeIndices,
3314                         [VF, &TE](const EdgeInfo &EI) {
3315                           return EI.UserTE->Scalars.size() == VF ||
3316                                  EI.UserTE->Scalars.size() ==
3317                                      TE->Scalars.size();
3318                         }) &&
3319                  "All users must be of VF size.");
3320           // Update ordering of the operands with the smaller VF than the given
3321           // one.
3322           reorderReuses(TE->ReuseShuffleIndices, Mask);
3323         }
3324         continue;
3325       }
3326       if (TE->State == TreeEntry::Vectorize &&
3327           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3328               InsertElementInst>(TE->getMainOp()) &&
3329           !TE->isAltShuffle()) {
3330         // Build correct orders for extract{element,value}, loads and
3331         // stores.
3332         reorderOrder(TE->ReorderIndices, Mask);
3333         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3334           TE->reorderOperands(Mask);
3335       } else {
3336         // Reorder the node and its operands.
3337         TE->reorderOperands(Mask);
3338         assert(TE->ReorderIndices.empty() &&
3339                "Expected empty reorder sequence.");
3340         reorderScalars(TE->Scalars, Mask);
3341       }
3342       if (!TE->ReuseShuffleIndices.empty()) {
3343         // Apply reversed order to keep the original ordering of the reused
3344         // elements to avoid extra reorder indices shuffling.
3345         OrdersType CurrentOrder;
3346         reorderOrder(CurrentOrder, MaskOrder);
3347         SmallVector<int> NewReuses;
3348         inversePermutation(CurrentOrder, NewReuses);
3349         addMask(NewReuses, TE->ReuseShuffleIndices);
3350         TE->ReuseShuffleIndices.swap(NewReuses);
3351       }
3352     }
3353   }
3354 }
3355 
3356 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3357   SetVector<TreeEntry *> OrderedEntries;
3358   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3359   // Find all reorderable leaf nodes with the given VF.
3360   // Currently the are vectorized loads,extracts without alternate operands +
3361   // some gathering of extracts.
3362   SmallVector<TreeEntry *> NonVectorized;
3363   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3364                               &NonVectorized](
3365                                  const std::unique_ptr<TreeEntry> &TE) {
3366     if (TE->State != TreeEntry::Vectorize)
3367       NonVectorized.push_back(TE.get());
3368     if (Optional<OrdersType> CurrentOrder =
3369             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3370       OrderedEntries.insert(TE.get());
3371       if (TE->State != TreeEntry::Vectorize)
3372         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3373     }
3374   });
3375 
3376   // Checks if the operands of the users are reordarable and have only single
3377   // use.
3378   auto &&CheckOperands =
3379       [this, &NonVectorized](const auto &Data,
3380                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3381         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3382           if (any_of(Data.second,
3383                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3384                        return OpData.first == I &&
3385                               OpData.second->State == TreeEntry::Vectorize;
3386                      }))
3387             continue;
3388           ArrayRef<Value *> VL = Data.first->getOperand(I);
3389           const TreeEntry *TE = nullptr;
3390           const auto *It = find_if(VL, [this, &TE](Value *V) {
3391             TE = getTreeEntry(V);
3392             return TE;
3393           });
3394           if (It != VL.end() && TE->isSame(VL))
3395             return false;
3396           TreeEntry *Gather = nullptr;
3397           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3398                 assert(TE->State != TreeEntry::Vectorize &&
3399                        "Only non-vectorized nodes are expected.");
3400                 if (TE->isSame(VL)) {
3401                   Gather = TE;
3402                   return true;
3403                 }
3404                 return false;
3405               }) > 1)
3406             return false;
3407           if (Gather)
3408             GatherOps.push_back(Gather);
3409         }
3410         return true;
3411       };
3412   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3413   // I.e., if the node has operands, that are reordered, try to make at least
3414   // one operand order in the natural order and reorder others + reorder the
3415   // user node itself.
3416   SmallPtrSet<const TreeEntry *, 4> Visited;
3417   while (!OrderedEntries.empty()) {
3418     // 1. Filter out only reordered nodes.
3419     // 2. If the entry has multiple uses - skip it and jump to the next node.
3420     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3421     SmallVector<TreeEntry *> Filtered;
3422     for (TreeEntry *TE : OrderedEntries) {
3423       if (!(TE->State == TreeEntry::Vectorize ||
3424             (TE->State == TreeEntry::NeedToGather &&
3425              GathersToOrders.count(TE))) ||
3426           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3427           !all_of(drop_begin(TE->UserTreeIndices),
3428                   [TE](const EdgeInfo &EI) {
3429                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3430                   }) ||
3431           !Visited.insert(TE).second) {
3432         Filtered.push_back(TE);
3433         continue;
3434       }
3435       // Build a map between user nodes and their operands order to speedup
3436       // search. The graph currently does not provide this dependency directly.
3437       for (EdgeInfo &EI : TE->UserTreeIndices) {
3438         TreeEntry *UserTE = EI.UserTE;
3439         auto It = Users.find(UserTE);
3440         if (It == Users.end())
3441           It = Users.insert({UserTE, {}}).first;
3442         It->second.emplace_back(EI.EdgeIdx, TE);
3443       }
3444     }
3445     // Erase filtered entries.
3446     for_each(Filtered,
3447              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3448     for (const auto &Data : Users) {
3449       // Check that operands are used only in the User node.
3450       SmallVector<TreeEntry *> GatherOps;
3451       if (!CheckOperands(Data, GatherOps)) {
3452         for_each(Data.second,
3453                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3454                    OrderedEntries.remove(Op.second);
3455                  });
3456         continue;
3457       }
3458       // All operands are reordered and used only in this node - propagate the
3459       // most used order to the user node.
3460       MapVector<OrdersType, unsigned,
3461                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3462           OrdersUses;
3463       // Do the analysis for each tree entry only once, otherwise the order of
3464       // the same node my be considered several times, though might be not
3465       // profitable.
3466       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3467       for (const auto &Op : Data.second) {
3468         TreeEntry *OpTE = Op.second;
3469         if (!VisitedOps.insert(OpTE).second)
3470           continue;
3471         if (!OpTE->ReuseShuffleIndices.empty() ||
3472             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3473           continue;
3474         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3475           if (OpTE->State == TreeEntry::NeedToGather)
3476             return GathersToOrders.find(OpTE)->second;
3477           return OpTE->ReorderIndices;
3478         }();
3479         // Stores actually store the mask, not the order, need to invert.
3480         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3481             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3482           SmallVector<int> Mask;
3483           inversePermutation(Order, Mask);
3484           unsigned E = Order.size();
3485           OrdersType CurrentOrder(E, E);
3486           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3487             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3488           });
3489           fixupOrderingIndices(CurrentOrder);
3490           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3491         } else {
3492           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3493         }
3494         OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3495             OpTE->UserTreeIndices.size();
3496         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3497         --OrdersUses[{}];
3498       }
3499       // If no orders - skip current nodes and jump to the next one, if any.
3500       if (OrdersUses.empty()) {
3501         for_each(Data.second,
3502                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3503                    OrderedEntries.remove(Op.second);
3504                  });
3505         continue;
3506       }
3507       // Choose the best order.
3508       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3509       unsigned Cnt = OrdersUses.front().second;
3510       for (const auto &Pair : drop_begin(OrdersUses)) {
3511         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3512           BestOrder = Pair.first;
3513           Cnt = Pair.second;
3514         }
3515       }
3516       // Set order of the user node (reordering of operands and user nodes).
3517       if (BestOrder.empty()) {
3518         for_each(Data.second,
3519                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3520                    OrderedEntries.remove(Op.second);
3521                  });
3522         continue;
3523       }
3524       // Erase operands from OrderedEntries list and adjust their orders.
3525       VisitedOps.clear();
3526       SmallVector<int> Mask;
3527       inversePermutation(BestOrder, Mask);
3528       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3529       unsigned E = BestOrder.size();
3530       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3531         return I < E ? static_cast<int>(I) : UndefMaskElem;
3532       });
3533       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3534         TreeEntry *TE = Op.second;
3535         OrderedEntries.remove(TE);
3536         if (!VisitedOps.insert(TE).second)
3537           continue;
3538         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3539           // Just reorder reuses indices.
3540           reorderReuses(TE->ReuseShuffleIndices, Mask);
3541           continue;
3542         }
3543         // Gathers are processed separately.
3544         if (TE->State != TreeEntry::Vectorize)
3545           continue;
3546         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3547                 TE->ReorderIndices.empty()) &&
3548                "Non-matching sizes of user/operand entries.");
3549         reorderOrder(TE->ReorderIndices, Mask);
3550       }
3551       // For gathers just need to reorder its scalars.
3552       for (TreeEntry *Gather : GatherOps) {
3553         assert(Gather->ReorderIndices.empty() &&
3554                "Unexpected reordering of gathers.");
3555         if (!Gather->ReuseShuffleIndices.empty()) {
3556           // Just reorder reuses indices.
3557           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3558           continue;
3559         }
3560         reorderScalars(Gather->Scalars, Mask);
3561         OrderedEntries.remove(Gather);
3562       }
3563       // Reorder operands of the user node and set the ordering for the user
3564       // node itself.
3565       if (Data.first->State != TreeEntry::Vectorize ||
3566           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3567               Data.first->getMainOp()) ||
3568           Data.first->isAltShuffle())
3569         Data.first->reorderOperands(Mask);
3570       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3571           Data.first->isAltShuffle()) {
3572         reorderScalars(Data.first->Scalars, Mask);
3573         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3574         if (Data.first->ReuseShuffleIndices.empty() &&
3575             !Data.first->ReorderIndices.empty() &&
3576             !Data.first->isAltShuffle()) {
3577           // Insert user node to the list to try to sink reordering deeper in
3578           // the graph.
3579           OrderedEntries.insert(Data.first);
3580         }
3581       } else {
3582         reorderOrder(Data.first->ReorderIndices, Mask);
3583       }
3584     }
3585   }
3586   // If the reordering is unnecessary, just remove the reorder.
3587   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3588       VectorizableTree.front()->ReuseShuffleIndices.empty())
3589     VectorizableTree.front()->ReorderIndices.clear();
3590 }
3591 
3592 void BoUpSLP::buildExternalUses(
3593     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3594   // Collect the values that we need to extract from the tree.
3595   for (auto &TEPtr : VectorizableTree) {
3596     TreeEntry *Entry = TEPtr.get();
3597 
3598     // No need to handle users of gathered values.
3599     if (Entry->State == TreeEntry::NeedToGather)
3600       continue;
3601 
3602     // For each lane:
3603     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3604       Value *Scalar = Entry->Scalars[Lane];
3605       int FoundLane = Entry->findLaneForValue(Scalar);
3606 
3607       // Check if the scalar is externally used as an extra arg.
3608       auto ExtI = ExternallyUsedValues.find(Scalar);
3609       if (ExtI != ExternallyUsedValues.end()) {
3610         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3611                           << Lane << " from " << *Scalar << ".\n");
3612         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3613       }
3614       for (User *U : Scalar->users()) {
3615         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3616 
3617         Instruction *UserInst = dyn_cast<Instruction>(U);
3618         if (!UserInst)
3619           continue;
3620 
3621         if (isDeleted(UserInst))
3622           continue;
3623 
3624         // Skip in-tree scalars that become vectors
3625         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3626           Value *UseScalar = UseEntry->Scalars[0];
3627           // Some in-tree scalars will remain as scalar in vectorized
3628           // instructions. If that is the case, the one in Lane 0 will
3629           // be used.
3630           if (UseScalar != U ||
3631               UseEntry->State == TreeEntry::ScatterVectorize ||
3632               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3633             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3634                               << ".\n");
3635             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3636             continue;
3637           }
3638         }
3639 
3640         // Ignore users in the user ignore list.
3641         if (is_contained(UserIgnoreList, UserInst))
3642           continue;
3643 
3644         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3645                           << Lane << " from " << *Scalar << ".\n");
3646         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3647       }
3648     }
3649   }
3650 }
3651 
3652 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3653                         ArrayRef<Value *> UserIgnoreLst) {
3654   deleteTree();
3655   UserIgnoreList = UserIgnoreLst;
3656   if (!allSameType(Roots))
3657     return;
3658   buildTree_rec(Roots, 0, EdgeInfo());
3659 }
3660 
3661 namespace {
3662 /// Tracks the state we can represent the loads in the given sequence.
3663 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3664 } // anonymous namespace
3665 
3666 /// Checks if the given array of loads can be represented as a vectorized,
3667 /// scatter or just simple gather.
3668 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3669                                     const TargetTransformInfo &TTI,
3670                                     const DataLayout &DL, ScalarEvolution &SE,
3671                                     SmallVectorImpl<unsigned> &Order,
3672                                     SmallVectorImpl<Value *> &PointerOps) {
3673   // Check that a vectorized load would load the same memory as a scalar
3674   // load. For example, we don't want to vectorize loads that are smaller
3675   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3676   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3677   // from such a struct, we read/write packed bits disagreeing with the
3678   // unvectorized version.
3679   Type *ScalarTy = VL0->getType();
3680 
3681   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3682     return LoadsState::Gather;
3683 
3684   // Make sure all loads in the bundle are simple - we can't vectorize
3685   // atomic or volatile loads.
3686   PointerOps.clear();
3687   PointerOps.resize(VL.size());
3688   auto *POIter = PointerOps.begin();
3689   for (Value *V : VL) {
3690     auto *L = cast<LoadInst>(V);
3691     if (!L->isSimple())
3692       return LoadsState::Gather;
3693     *POIter = L->getPointerOperand();
3694     ++POIter;
3695   }
3696 
3697   Order.clear();
3698   // Check the order of pointer operands.
3699   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3700     Value *Ptr0;
3701     Value *PtrN;
3702     if (Order.empty()) {
3703       Ptr0 = PointerOps.front();
3704       PtrN = PointerOps.back();
3705     } else {
3706       Ptr0 = PointerOps[Order.front()];
3707       PtrN = PointerOps[Order.back()];
3708     }
3709     Optional<int> Diff =
3710         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3711     // Check that the sorted loads are consecutive.
3712     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3713       return LoadsState::Vectorize;
3714     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3715     for (Value *V : VL)
3716       CommonAlignment =
3717           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3718     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3719                                 CommonAlignment))
3720       return LoadsState::ScatterVectorize;
3721   }
3722 
3723   return LoadsState::Gather;
3724 }
3725 
3726 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3727                             const EdgeInfo &UserTreeIdx) {
3728   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3729 
3730   SmallVector<int> ReuseShuffleIndicies;
3731   SmallVector<Value *> UniqueValues;
3732   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3733                                 &UserTreeIdx,
3734                                 this](const InstructionsState &S) {
3735     // Check that every instruction appears once in this bundle.
3736     DenseMap<Value *, unsigned> UniquePositions;
3737     for (Value *V : VL) {
3738       if (isConstant(V)) {
3739         ReuseShuffleIndicies.emplace_back(
3740             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3741         UniqueValues.emplace_back(V);
3742         continue;
3743       }
3744       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3745       ReuseShuffleIndicies.emplace_back(Res.first->second);
3746       if (Res.second)
3747         UniqueValues.emplace_back(V);
3748     }
3749     size_t NumUniqueScalarValues = UniqueValues.size();
3750     if (NumUniqueScalarValues == VL.size()) {
3751       ReuseShuffleIndicies.clear();
3752     } else {
3753       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3754       if (NumUniqueScalarValues <= 1 ||
3755           (UniquePositions.size() == 1 && all_of(UniqueValues,
3756                                                  [](Value *V) {
3757                                                    return isa<UndefValue>(V) ||
3758                                                           !isConstant(V);
3759                                                  })) ||
3760           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3761         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3762         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3763         return false;
3764       }
3765       VL = UniqueValues;
3766     }
3767     return true;
3768   };
3769 
3770   InstructionsState S = getSameOpcode(VL);
3771   if (Depth == RecursionMaxDepth) {
3772     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3773     if (TryToFindDuplicates(S))
3774       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3775                    ReuseShuffleIndicies);
3776     return;
3777   }
3778 
3779   // Don't handle scalable vectors
3780   if (S.getOpcode() == Instruction::ExtractElement &&
3781       isa<ScalableVectorType>(
3782           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3783     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3784     if (TryToFindDuplicates(S))
3785       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3786                    ReuseShuffleIndicies);
3787     return;
3788   }
3789 
3790   // Don't handle vectors.
3791   if (S.OpValue->getType()->isVectorTy() &&
3792       !isa<InsertElementInst>(S.OpValue)) {
3793     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3794     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3795     return;
3796   }
3797 
3798   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3799     if (SI->getValueOperand()->getType()->isVectorTy()) {
3800       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3801       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3802       return;
3803     }
3804 
3805   // If all of the operands are identical or constant we have a simple solution.
3806   // If we deal with insert/extract instructions, they all must have constant
3807   // indices, otherwise we should gather them, not try to vectorize.
3808   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3809       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3810        !all_of(VL, isVectorLikeInstWithConstOps))) {
3811     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3812     if (TryToFindDuplicates(S))
3813       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3814                    ReuseShuffleIndicies);
3815     return;
3816   }
3817 
3818   // We now know that this is a vector of instructions of the same type from
3819   // the same block.
3820 
3821   // Don't vectorize ephemeral values.
3822   for (Value *V : VL) {
3823     if (EphValues.count(V)) {
3824       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3825                         << ") is ephemeral.\n");
3826       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3827       return;
3828     }
3829   }
3830 
3831   // Check if this is a duplicate of another entry.
3832   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3833     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3834     if (!E->isSame(VL)) {
3835       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3836       if (TryToFindDuplicates(S))
3837         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3838                      ReuseShuffleIndicies);
3839       return;
3840     }
3841     // Record the reuse of the tree node.  FIXME, currently this is only used to
3842     // properly draw the graph rather than for the actual vectorization.
3843     E->UserTreeIndices.push_back(UserTreeIdx);
3844     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3845                       << ".\n");
3846     return;
3847   }
3848 
3849   // Check that none of the instructions in the bundle are already in the tree.
3850   for (Value *V : VL) {
3851     auto *I = dyn_cast<Instruction>(V);
3852     if (!I)
3853       continue;
3854     if (getTreeEntry(I)) {
3855       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3856                         << ") is already in tree.\n");
3857       if (TryToFindDuplicates(S))
3858         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3859                      ReuseShuffleIndicies);
3860       return;
3861     }
3862   }
3863 
3864   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3865   for (Value *V : VL) {
3866     if (is_contained(UserIgnoreList, V)) {
3867       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3868       if (TryToFindDuplicates(S))
3869         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3870                      ReuseShuffleIndicies);
3871       return;
3872     }
3873   }
3874 
3875   // Check that all of the users of the scalars that we want to vectorize are
3876   // schedulable.
3877   auto *VL0 = cast<Instruction>(S.OpValue);
3878   BasicBlock *BB = VL0->getParent();
3879 
3880   if (!DT->isReachableFromEntry(BB)) {
3881     // Don't go into unreachable blocks. They may contain instructions with
3882     // dependency cycles which confuse the final scheduling.
3883     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3884     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3885     return;
3886   }
3887 
3888   // Check that every instruction appears once in this bundle.
3889   if (!TryToFindDuplicates(S))
3890     return;
3891 
3892   auto &BSRef = BlocksSchedules[BB];
3893   if (!BSRef)
3894     BSRef = std::make_unique<BlockScheduling>(BB);
3895 
3896   BlockScheduling &BS = *BSRef.get();
3897 
3898   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3899 #ifdef EXPENSIVE_CHECKS
3900   // Make sure we didn't break any internal invariants
3901   BS.verify();
3902 #endif
3903   if (!Bundle) {
3904     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3905     assert((!BS.getScheduleData(VL0) ||
3906             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3907            "tryScheduleBundle should cancelScheduling on failure");
3908     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3909                  ReuseShuffleIndicies);
3910     return;
3911   }
3912   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3913 
3914   unsigned ShuffleOrOp = S.isAltShuffle() ?
3915                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3916   switch (ShuffleOrOp) {
3917     case Instruction::PHI: {
3918       auto *PH = cast<PHINode>(VL0);
3919 
3920       // Check for terminator values (e.g. invoke).
3921       for (Value *V : VL)
3922         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3923           Instruction *Term = dyn_cast<Instruction>(
3924               cast<PHINode>(V)->getIncomingValueForBlock(
3925                   PH->getIncomingBlock(I)));
3926           if (Term && Term->isTerminator()) {
3927             LLVM_DEBUG(dbgs()
3928                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3929             BS.cancelScheduling(VL, VL0);
3930             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3931                          ReuseShuffleIndicies);
3932             return;
3933           }
3934         }
3935 
3936       TreeEntry *TE =
3937           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3938       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3939 
3940       // Keeps the reordered operands to avoid code duplication.
3941       SmallVector<ValueList, 2> OperandsVec;
3942       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3943         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3944           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3945           TE->setOperand(I, Operands);
3946           OperandsVec.push_back(Operands);
3947           continue;
3948         }
3949         ValueList Operands;
3950         // Prepare the operand vector.
3951         for (Value *V : VL)
3952           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3953               PH->getIncomingBlock(I)));
3954         TE->setOperand(I, Operands);
3955         OperandsVec.push_back(Operands);
3956       }
3957       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3958         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3959       return;
3960     }
3961     case Instruction::ExtractValue:
3962     case Instruction::ExtractElement: {
3963       OrdersType CurrentOrder;
3964       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3965       if (Reuse) {
3966         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3967         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3968                      ReuseShuffleIndicies);
3969         // This is a special case, as it does not gather, but at the same time
3970         // we are not extending buildTree_rec() towards the operands.
3971         ValueList Op0;
3972         Op0.assign(VL.size(), VL0->getOperand(0));
3973         VectorizableTree.back()->setOperand(0, Op0);
3974         return;
3975       }
3976       if (!CurrentOrder.empty()) {
3977         LLVM_DEBUG({
3978           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3979                     "with order";
3980           for (unsigned Idx : CurrentOrder)
3981             dbgs() << " " << Idx;
3982           dbgs() << "\n";
3983         });
3984         fixupOrderingIndices(CurrentOrder);
3985         // Insert new order with initial value 0, if it does not exist,
3986         // otherwise return the iterator to the existing one.
3987         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3988                      ReuseShuffleIndicies, CurrentOrder);
3989         // This is a special case, as it does not gather, but at the same time
3990         // we are not extending buildTree_rec() towards the operands.
3991         ValueList Op0;
3992         Op0.assign(VL.size(), VL0->getOperand(0));
3993         VectorizableTree.back()->setOperand(0, Op0);
3994         return;
3995       }
3996       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3997       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3998                    ReuseShuffleIndicies);
3999       BS.cancelScheduling(VL, VL0);
4000       return;
4001     }
4002     case Instruction::InsertElement: {
4003       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4004 
4005       // Check that we have a buildvector and not a shuffle of 2 or more
4006       // different vectors.
4007       ValueSet SourceVectors;
4008       int MinIdx = std::numeric_limits<int>::max();
4009       for (Value *V : VL) {
4010         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4011         Optional<int> Idx = *getInsertIndex(V, 0);
4012         if (!Idx || *Idx == UndefMaskElem)
4013           continue;
4014         MinIdx = std::min(MinIdx, *Idx);
4015       }
4016 
4017       if (count_if(VL, [&SourceVectors](Value *V) {
4018             return !SourceVectors.contains(V);
4019           }) >= 2) {
4020         // Found 2nd source vector - cancel.
4021         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4022                              "different source vectors.\n");
4023         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4024         BS.cancelScheduling(VL, VL0);
4025         return;
4026       }
4027 
4028       auto OrdCompare = [](const std::pair<int, int> &P1,
4029                            const std::pair<int, int> &P2) {
4030         return P1.first > P2.first;
4031       };
4032       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4033                     decltype(OrdCompare)>
4034           Indices(OrdCompare);
4035       for (int I = 0, E = VL.size(); I < E; ++I) {
4036         Optional<int> Idx = *getInsertIndex(VL[I], 0);
4037         if (!Idx || *Idx == UndefMaskElem)
4038           continue;
4039         Indices.emplace(*Idx, I);
4040       }
4041       OrdersType CurrentOrder(VL.size(), VL.size());
4042       bool IsIdentity = true;
4043       for (int I = 0, E = VL.size(); I < E; ++I) {
4044         CurrentOrder[Indices.top().second] = I;
4045         IsIdentity &= Indices.top().second == I;
4046         Indices.pop();
4047       }
4048       if (IsIdentity)
4049         CurrentOrder.clear();
4050       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4051                                    None, CurrentOrder);
4052       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4053 
4054       constexpr int NumOps = 2;
4055       ValueList VectorOperands[NumOps];
4056       for (int I = 0; I < NumOps; ++I) {
4057         for (Value *V : VL)
4058           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4059 
4060         TE->setOperand(I, VectorOperands[I]);
4061       }
4062       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4063       return;
4064     }
4065     case Instruction::Load: {
4066       // Check that a vectorized load would load the same memory as a scalar
4067       // load. For example, we don't want to vectorize loads that are smaller
4068       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4069       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4070       // from such a struct, we read/write packed bits disagreeing with the
4071       // unvectorized version.
4072       SmallVector<Value *> PointerOps;
4073       OrdersType CurrentOrder;
4074       TreeEntry *TE = nullptr;
4075       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4076                                 PointerOps)) {
4077       case LoadsState::Vectorize:
4078         if (CurrentOrder.empty()) {
4079           // Original loads are consecutive and does not require reordering.
4080           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4081                             ReuseShuffleIndicies);
4082           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4083         } else {
4084           fixupOrderingIndices(CurrentOrder);
4085           // Need to reorder.
4086           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4087                             ReuseShuffleIndicies, CurrentOrder);
4088           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4089         }
4090         TE->setOperandsInOrder();
4091         break;
4092       case LoadsState::ScatterVectorize:
4093         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4094         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4095                           UserTreeIdx, ReuseShuffleIndicies);
4096         TE->setOperandsInOrder();
4097         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4098         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4099         break;
4100       case LoadsState::Gather:
4101         BS.cancelScheduling(VL, VL0);
4102         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4103                      ReuseShuffleIndicies);
4104 #ifndef NDEBUG
4105         Type *ScalarTy = VL0->getType();
4106         if (DL->getTypeSizeInBits(ScalarTy) !=
4107             DL->getTypeAllocSizeInBits(ScalarTy))
4108           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4109         else if (any_of(VL, [](Value *V) {
4110                    return !cast<LoadInst>(V)->isSimple();
4111                  }))
4112           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4113         else
4114           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4115 #endif // NDEBUG
4116         break;
4117       }
4118       return;
4119     }
4120     case Instruction::ZExt:
4121     case Instruction::SExt:
4122     case Instruction::FPToUI:
4123     case Instruction::FPToSI:
4124     case Instruction::FPExt:
4125     case Instruction::PtrToInt:
4126     case Instruction::IntToPtr:
4127     case Instruction::SIToFP:
4128     case Instruction::UIToFP:
4129     case Instruction::Trunc:
4130     case Instruction::FPTrunc:
4131     case Instruction::BitCast: {
4132       Type *SrcTy = VL0->getOperand(0)->getType();
4133       for (Value *V : VL) {
4134         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4135         if (Ty != SrcTy || !isValidElementType(Ty)) {
4136           BS.cancelScheduling(VL, VL0);
4137           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4138                        ReuseShuffleIndicies);
4139           LLVM_DEBUG(dbgs()
4140                      << "SLP: Gathering casts with different src types.\n");
4141           return;
4142         }
4143       }
4144       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4145                                    ReuseShuffleIndicies);
4146       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4147 
4148       TE->setOperandsInOrder();
4149       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4150         ValueList Operands;
4151         // Prepare the operand vector.
4152         for (Value *V : VL)
4153           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4154 
4155         buildTree_rec(Operands, Depth + 1, {TE, i});
4156       }
4157       return;
4158     }
4159     case Instruction::ICmp:
4160     case Instruction::FCmp: {
4161       // Check that all of the compares have the same predicate.
4162       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4163       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4164       Type *ComparedTy = VL0->getOperand(0)->getType();
4165       for (Value *V : VL) {
4166         CmpInst *Cmp = cast<CmpInst>(V);
4167         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4168             Cmp->getOperand(0)->getType() != ComparedTy) {
4169           BS.cancelScheduling(VL, VL0);
4170           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4171                        ReuseShuffleIndicies);
4172           LLVM_DEBUG(dbgs()
4173                      << "SLP: Gathering cmp with different predicate.\n");
4174           return;
4175         }
4176       }
4177 
4178       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4179                                    ReuseShuffleIndicies);
4180       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4181 
4182       ValueList Left, Right;
4183       if (cast<CmpInst>(VL0)->isCommutative()) {
4184         // Commutative predicate - collect + sort operands of the instructions
4185         // so that each side is more likely to have the same opcode.
4186         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4187         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4188       } else {
4189         // Collect operands - commute if it uses the swapped predicate.
4190         for (Value *V : VL) {
4191           auto *Cmp = cast<CmpInst>(V);
4192           Value *LHS = Cmp->getOperand(0);
4193           Value *RHS = Cmp->getOperand(1);
4194           if (Cmp->getPredicate() != P0)
4195             std::swap(LHS, RHS);
4196           Left.push_back(LHS);
4197           Right.push_back(RHS);
4198         }
4199       }
4200       TE->setOperand(0, Left);
4201       TE->setOperand(1, Right);
4202       buildTree_rec(Left, Depth + 1, {TE, 0});
4203       buildTree_rec(Right, Depth + 1, {TE, 1});
4204       return;
4205     }
4206     case Instruction::Select:
4207     case Instruction::FNeg:
4208     case Instruction::Add:
4209     case Instruction::FAdd:
4210     case Instruction::Sub:
4211     case Instruction::FSub:
4212     case Instruction::Mul:
4213     case Instruction::FMul:
4214     case Instruction::UDiv:
4215     case Instruction::SDiv:
4216     case Instruction::FDiv:
4217     case Instruction::URem:
4218     case Instruction::SRem:
4219     case Instruction::FRem:
4220     case Instruction::Shl:
4221     case Instruction::LShr:
4222     case Instruction::AShr:
4223     case Instruction::And:
4224     case Instruction::Or:
4225     case Instruction::Xor: {
4226       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4227                                    ReuseShuffleIndicies);
4228       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4229 
4230       // Sort operands of the instructions so that each side is more likely to
4231       // have the same opcode.
4232       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4233         ValueList Left, Right;
4234         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4235         TE->setOperand(0, Left);
4236         TE->setOperand(1, Right);
4237         buildTree_rec(Left, Depth + 1, {TE, 0});
4238         buildTree_rec(Right, Depth + 1, {TE, 1});
4239         return;
4240       }
4241 
4242       TE->setOperandsInOrder();
4243       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4244         ValueList Operands;
4245         // Prepare the operand vector.
4246         for (Value *V : VL)
4247           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4248 
4249         buildTree_rec(Operands, Depth + 1, {TE, i});
4250       }
4251       return;
4252     }
4253     case Instruction::GetElementPtr: {
4254       // We don't combine GEPs with complicated (nested) indexing.
4255       for (Value *V : VL) {
4256         if (cast<Instruction>(V)->getNumOperands() != 2) {
4257           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4258           BS.cancelScheduling(VL, VL0);
4259           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4260                        ReuseShuffleIndicies);
4261           return;
4262         }
4263       }
4264 
4265       // We can't combine several GEPs into one vector if they operate on
4266       // different types.
4267       Type *Ty0 = VL0->getOperand(0)->getType();
4268       for (Value *V : VL) {
4269         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4270         if (Ty0 != CurTy) {
4271           LLVM_DEBUG(dbgs()
4272                      << "SLP: not-vectorizable GEP (different types).\n");
4273           BS.cancelScheduling(VL, VL0);
4274           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4275                        ReuseShuffleIndicies);
4276           return;
4277         }
4278       }
4279 
4280       // We don't combine GEPs with non-constant indexes.
4281       Type *Ty1 = VL0->getOperand(1)->getType();
4282       for (Value *V : VL) {
4283         auto Op = cast<Instruction>(V)->getOperand(1);
4284         if (!isa<ConstantInt>(Op) ||
4285             (Op->getType() != Ty1 &&
4286              Op->getType()->getScalarSizeInBits() >
4287                  DL->getIndexSizeInBits(
4288                      V->getType()->getPointerAddressSpace()))) {
4289           LLVM_DEBUG(dbgs()
4290                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4291           BS.cancelScheduling(VL, VL0);
4292           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4293                        ReuseShuffleIndicies);
4294           return;
4295         }
4296       }
4297 
4298       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4299                                    ReuseShuffleIndicies);
4300       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4301       SmallVector<ValueList, 2> Operands(2);
4302       // Prepare the operand vector for pointer operands.
4303       for (Value *V : VL)
4304         Operands.front().push_back(
4305             cast<GetElementPtrInst>(V)->getPointerOperand());
4306       TE->setOperand(0, Operands.front());
4307       // Need to cast all indices to the same type before vectorization to
4308       // avoid crash.
4309       // Required to be able to find correct matches between different gather
4310       // nodes and reuse the vectorized values rather than trying to gather them
4311       // again.
4312       int IndexIdx = 1;
4313       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4314       Type *Ty = all_of(VL,
4315                         [VL0Ty, IndexIdx](Value *V) {
4316                           return VL0Ty == cast<GetElementPtrInst>(V)
4317                                               ->getOperand(IndexIdx)
4318                                               ->getType();
4319                         })
4320                      ? VL0Ty
4321                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4322                                             ->getPointerOperandType()
4323                                             ->getScalarType());
4324       // Prepare the operand vector.
4325       for (Value *V : VL) {
4326         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4327         auto *CI = cast<ConstantInt>(Op);
4328         Operands.back().push_back(ConstantExpr::getIntegerCast(
4329             CI, Ty, CI->getValue().isSignBitSet()));
4330       }
4331       TE->setOperand(IndexIdx, Operands.back());
4332 
4333       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4334         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4335       return;
4336     }
4337     case Instruction::Store: {
4338       // Check if the stores are consecutive or if we need to swizzle them.
4339       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4340       // Avoid types that are padded when being allocated as scalars, while
4341       // being packed together in a vector (such as i1).
4342       if (DL->getTypeSizeInBits(ScalarTy) !=
4343           DL->getTypeAllocSizeInBits(ScalarTy)) {
4344         BS.cancelScheduling(VL, VL0);
4345         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4346                      ReuseShuffleIndicies);
4347         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4348         return;
4349       }
4350       // Make sure all stores in the bundle are simple - we can't vectorize
4351       // atomic or volatile stores.
4352       SmallVector<Value *, 4> PointerOps(VL.size());
4353       ValueList Operands(VL.size());
4354       auto POIter = PointerOps.begin();
4355       auto OIter = Operands.begin();
4356       for (Value *V : VL) {
4357         auto *SI = cast<StoreInst>(V);
4358         if (!SI->isSimple()) {
4359           BS.cancelScheduling(VL, VL0);
4360           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4361                        ReuseShuffleIndicies);
4362           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4363           return;
4364         }
4365         *POIter = SI->getPointerOperand();
4366         *OIter = SI->getValueOperand();
4367         ++POIter;
4368         ++OIter;
4369       }
4370 
4371       OrdersType CurrentOrder;
4372       // Check the order of pointer operands.
4373       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4374         Value *Ptr0;
4375         Value *PtrN;
4376         if (CurrentOrder.empty()) {
4377           Ptr0 = PointerOps.front();
4378           PtrN = PointerOps.back();
4379         } else {
4380           Ptr0 = PointerOps[CurrentOrder.front()];
4381           PtrN = PointerOps[CurrentOrder.back()];
4382         }
4383         Optional<int> Dist =
4384             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4385         // Check that the sorted pointer operands are consecutive.
4386         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4387           if (CurrentOrder.empty()) {
4388             // Original stores are consecutive and does not require reordering.
4389             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4390                                          UserTreeIdx, ReuseShuffleIndicies);
4391             TE->setOperandsInOrder();
4392             buildTree_rec(Operands, Depth + 1, {TE, 0});
4393             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4394           } else {
4395             fixupOrderingIndices(CurrentOrder);
4396             TreeEntry *TE =
4397                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4398                              ReuseShuffleIndicies, CurrentOrder);
4399             TE->setOperandsInOrder();
4400             buildTree_rec(Operands, Depth + 1, {TE, 0});
4401             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4402           }
4403           return;
4404         }
4405       }
4406 
4407       BS.cancelScheduling(VL, VL0);
4408       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4409                    ReuseShuffleIndicies);
4410       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4411       return;
4412     }
4413     case Instruction::Call: {
4414       // Check if the calls are all to the same vectorizable intrinsic or
4415       // library function.
4416       CallInst *CI = cast<CallInst>(VL0);
4417       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4418 
4419       VFShape Shape = VFShape::get(
4420           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4421           false /*HasGlobalPred*/);
4422       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4423 
4424       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4425         BS.cancelScheduling(VL, VL0);
4426         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4427                      ReuseShuffleIndicies);
4428         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4429         return;
4430       }
4431       Function *F = CI->getCalledFunction();
4432       unsigned NumArgs = CI->arg_size();
4433       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4434       for (unsigned j = 0; j != NumArgs; ++j)
4435         if (hasVectorInstrinsicScalarOpd(ID, j))
4436           ScalarArgs[j] = CI->getArgOperand(j);
4437       for (Value *V : VL) {
4438         CallInst *CI2 = dyn_cast<CallInst>(V);
4439         if (!CI2 || CI2->getCalledFunction() != F ||
4440             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4441             (VecFunc &&
4442              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4443             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4444           BS.cancelScheduling(VL, VL0);
4445           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4446                        ReuseShuffleIndicies);
4447           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4448                             << "\n");
4449           return;
4450         }
4451         // Some intrinsics have scalar arguments and should be same in order for
4452         // them to be vectorized.
4453         for (unsigned j = 0; j != NumArgs; ++j) {
4454           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4455             Value *A1J = CI2->getArgOperand(j);
4456             if (ScalarArgs[j] != A1J) {
4457               BS.cancelScheduling(VL, VL0);
4458               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4459                            ReuseShuffleIndicies);
4460               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4461                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4462                                 << "\n");
4463               return;
4464             }
4465           }
4466         }
4467         // Verify that the bundle operands are identical between the two calls.
4468         if (CI->hasOperandBundles() &&
4469             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4470                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4471                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4472           BS.cancelScheduling(VL, VL0);
4473           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4474                        ReuseShuffleIndicies);
4475           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4476                             << *CI << "!=" << *V << '\n');
4477           return;
4478         }
4479       }
4480 
4481       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4482                                    ReuseShuffleIndicies);
4483       TE->setOperandsInOrder();
4484       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4485         // For scalar operands no need to to create an entry since no need to
4486         // vectorize it.
4487         if (hasVectorInstrinsicScalarOpd(ID, i))
4488           continue;
4489         ValueList Operands;
4490         // Prepare the operand vector.
4491         for (Value *V : VL) {
4492           auto *CI2 = cast<CallInst>(V);
4493           Operands.push_back(CI2->getArgOperand(i));
4494         }
4495         buildTree_rec(Operands, Depth + 1, {TE, i});
4496       }
4497       return;
4498     }
4499     case Instruction::ShuffleVector: {
4500       // If this is not an alternate sequence of opcode like add-sub
4501       // then do not vectorize this instruction.
4502       if (!S.isAltShuffle()) {
4503         BS.cancelScheduling(VL, VL0);
4504         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4505                      ReuseShuffleIndicies);
4506         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4507         return;
4508       }
4509       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4510                                    ReuseShuffleIndicies);
4511       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4512 
4513       // Reorder operands if reordering would enable vectorization.
4514       auto *CI = dyn_cast<CmpInst>(VL0);
4515       if (isa<BinaryOperator>(VL0) || CI) {
4516         ValueList Left, Right;
4517         if (!CI || all_of(VL, [](Value *V) {
4518               return cast<CmpInst>(V)->isCommutative();
4519             })) {
4520           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4521         } else {
4522           CmpInst::Predicate P0 = CI->getPredicate();
4523           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4524           assert(P0 != AltP0 &&
4525                  "Expected different main/alternate predicates.");
4526           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4527           Value *BaseOp0 = VL0->getOperand(0);
4528           Value *BaseOp1 = VL0->getOperand(1);
4529           // Collect operands - commute if it uses the swapped predicate or
4530           // alternate operation.
4531           for (Value *V : VL) {
4532             auto *Cmp = cast<CmpInst>(V);
4533             Value *LHS = Cmp->getOperand(0);
4534             Value *RHS = Cmp->getOperand(1);
4535             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4536             if (P0 == AltP0Swapped) {
4537               if ((P0 == CurrentPred &&
4538                    !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4539                   (AltP0 == CurrentPred &&
4540                    areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))
4541                 std::swap(LHS, RHS);
4542             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4543               std::swap(LHS, RHS);
4544             }
4545             Left.push_back(LHS);
4546             Right.push_back(RHS);
4547           }
4548         }
4549         TE->setOperand(0, Left);
4550         TE->setOperand(1, Right);
4551         buildTree_rec(Left, Depth + 1, {TE, 0});
4552         buildTree_rec(Right, Depth + 1, {TE, 1});
4553         return;
4554       }
4555 
4556       TE->setOperandsInOrder();
4557       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4558         ValueList Operands;
4559         // Prepare the operand vector.
4560         for (Value *V : VL)
4561           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4562 
4563         buildTree_rec(Operands, Depth + 1, {TE, i});
4564       }
4565       return;
4566     }
4567     default:
4568       BS.cancelScheduling(VL, VL0);
4569       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4570                    ReuseShuffleIndicies);
4571       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4572       return;
4573   }
4574 }
4575 
4576 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4577   unsigned N = 1;
4578   Type *EltTy = T;
4579 
4580   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4581          isa<VectorType>(EltTy)) {
4582     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4583       // Check that struct is homogeneous.
4584       for (const auto *Ty : ST->elements())
4585         if (Ty != *ST->element_begin())
4586           return 0;
4587       N *= ST->getNumElements();
4588       EltTy = *ST->element_begin();
4589     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4590       N *= AT->getNumElements();
4591       EltTy = AT->getElementType();
4592     } else {
4593       auto *VT = cast<FixedVectorType>(EltTy);
4594       N *= VT->getNumElements();
4595       EltTy = VT->getElementType();
4596     }
4597   }
4598 
4599   if (!isValidElementType(EltTy))
4600     return 0;
4601   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4602   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4603     return 0;
4604   return N;
4605 }
4606 
4607 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4608                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4609   const auto *It = find_if(VL, [](Value *V) {
4610     return isa<ExtractElementInst, ExtractValueInst>(V);
4611   });
4612   assert(It != VL.end() && "Expected at least one extract instruction.");
4613   auto *E0 = cast<Instruction>(*It);
4614   assert(all_of(VL,
4615                 [](Value *V) {
4616                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4617                       V);
4618                 }) &&
4619          "Invalid opcode");
4620   // Check if all of the extracts come from the same vector and from the
4621   // correct offset.
4622   Value *Vec = E0->getOperand(0);
4623 
4624   CurrentOrder.clear();
4625 
4626   // We have to extract from a vector/aggregate with the same number of elements.
4627   unsigned NElts;
4628   if (E0->getOpcode() == Instruction::ExtractValue) {
4629     const DataLayout &DL = E0->getModule()->getDataLayout();
4630     NElts = canMapToVector(Vec->getType(), DL);
4631     if (!NElts)
4632       return false;
4633     // Check if load can be rewritten as load of vector.
4634     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4635     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4636       return false;
4637   } else {
4638     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4639   }
4640 
4641   if (NElts != VL.size())
4642     return false;
4643 
4644   // Check that all of the indices extract from the correct offset.
4645   bool ShouldKeepOrder = true;
4646   unsigned E = VL.size();
4647   // Assign to all items the initial value E + 1 so we can check if the extract
4648   // instruction index was used already.
4649   // Also, later we can check that all the indices are used and we have a
4650   // consecutive access in the extract instructions, by checking that no
4651   // element of CurrentOrder still has value E + 1.
4652   CurrentOrder.assign(E, E);
4653   unsigned I = 0;
4654   for (; I < E; ++I) {
4655     auto *Inst = dyn_cast<Instruction>(VL[I]);
4656     if (!Inst)
4657       continue;
4658     if (Inst->getOperand(0) != Vec)
4659       break;
4660     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4661       if (isa<UndefValue>(EE->getIndexOperand()))
4662         continue;
4663     Optional<unsigned> Idx = getExtractIndex(Inst);
4664     if (!Idx)
4665       break;
4666     const unsigned ExtIdx = *Idx;
4667     if (ExtIdx != I) {
4668       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4669         break;
4670       ShouldKeepOrder = false;
4671       CurrentOrder[ExtIdx] = I;
4672     } else {
4673       if (CurrentOrder[I] != E)
4674         break;
4675       CurrentOrder[I] = I;
4676     }
4677   }
4678   if (I < E) {
4679     CurrentOrder.clear();
4680     return false;
4681   }
4682   if (ShouldKeepOrder)
4683     CurrentOrder.clear();
4684 
4685   return ShouldKeepOrder;
4686 }
4687 
4688 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4689                                     ArrayRef<Value *> VectorizedVals) const {
4690   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4691          all_of(I->users(), [this](User *U) {
4692            return ScalarToTreeEntry.count(U) > 0 ||
4693                   isVectorLikeInstWithConstOps(U) ||
4694                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4695          });
4696 }
4697 
4698 static std::pair<InstructionCost, InstructionCost>
4699 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4700                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4701   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4702 
4703   // Calculate the cost of the scalar and vector calls.
4704   SmallVector<Type *, 4> VecTys;
4705   for (Use &Arg : CI->args())
4706     VecTys.push_back(
4707         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4708   FastMathFlags FMF;
4709   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4710     FMF = FPCI->getFastMathFlags();
4711   SmallVector<const Value *> Arguments(CI->args());
4712   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4713                                     dyn_cast<IntrinsicInst>(CI));
4714   auto IntrinsicCost =
4715     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4716 
4717   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4718                                      VecTy->getNumElements())),
4719                             false /*HasGlobalPred*/);
4720   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4721   auto LibCost = IntrinsicCost;
4722   if (!CI->isNoBuiltin() && VecFunc) {
4723     // Calculate the cost of the vector library call.
4724     // If the corresponding vector call is cheaper, return its cost.
4725     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4726                                     TTI::TCK_RecipThroughput);
4727   }
4728   return {IntrinsicCost, LibCost};
4729 }
4730 
4731 /// Compute the cost of creating a vector of type \p VecTy containing the
4732 /// extracted values from \p VL.
4733 static InstructionCost
4734 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4735                    TargetTransformInfo::ShuffleKind ShuffleKind,
4736                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4737   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4738 
4739   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4740       VecTy->getNumElements() < NumOfParts)
4741     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4742 
4743   bool AllConsecutive = true;
4744   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4745   unsigned Idx = -1;
4746   InstructionCost Cost = 0;
4747 
4748   // Process extracts in blocks of EltsPerVector to check if the source vector
4749   // operand can be re-used directly. If not, add the cost of creating a shuffle
4750   // to extract the values into a vector register.
4751   for (auto *V : VL) {
4752     ++Idx;
4753 
4754     // Need to exclude undefs from analysis.
4755     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4756       continue;
4757 
4758     // Reached the start of a new vector registers.
4759     if (Idx % EltsPerVector == 0) {
4760       AllConsecutive = true;
4761       continue;
4762     }
4763 
4764     // Check all extracts for a vector register on the target directly
4765     // extract values in order.
4766     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4767     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4768       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4769       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4770                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4771     }
4772 
4773     if (AllConsecutive)
4774       continue;
4775 
4776     // Skip all indices, except for the last index per vector block.
4777     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4778       continue;
4779 
4780     // If we have a series of extracts which are not consecutive and hence
4781     // cannot re-use the source vector register directly, compute the shuffle
4782     // cost to extract the a vector with EltsPerVector elements.
4783     Cost += TTI.getShuffleCost(
4784         TargetTransformInfo::SK_PermuteSingleSrc,
4785         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4786   }
4787   return Cost;
4788 }
4789 
4790 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4791 /// operations operands.
4792 static void
4793 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4794                      ArrayRef<int> ReusesIndices,
4795                      const function_ref<bool(Instruction *)> IsAltOp,
4796                      SmallVectorImpl<int> &Mask,
4797                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4798                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4799   unsigned Sz = VL.size();
4800   Mask.assign(Sz, UndefMaskElem);
4801   SmallVector<int> OrderMask;
4802   if (!ReorderIndices.empty())
4803     inversePermutation(ReorderIndices, OrderMask);
4804   for (unsigned I = 0; I < Sz; ++I) {
4805     unsigned Idx = I;
4806     if (!ReorderIndices.empty())
4807       Idx = OrderMask[I];
4808     auto *OpInst = cast<Instruction>(VL[Idx]);
4809     if (IsAltOp(OpInst)) {
4810       Mask[I] = Sz + Idx;
4811       if (AltScalars)
4812         AltScalars->push_back(OpInst);
4813     } else {
4814       Mask[I] = Idx;
4815       if (OpScalars)
4816         OpScalars->push_back(OpInst);
4817     }
4818   }
4819   if (!ReusesIndices.empty()) {
4820     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4821     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4822       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4823     });
4824     Mask.swap(NewMask);
4825   }
4826 }
4827 
4828 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4829                                       ArrayRef<Value *> VectorizedVals) {
4830   ArrayRef<Value*> VL = E->Scalars;
4831 
4832   Type *ScalarTy = VL[0]->getType();
4833   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4834     ScalarTy = SI->getValueOperand()->getType();
4835   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4836     ScalarTy = CI->getOperand(0)->getType();
4837   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4838     ScalarTy = IE->getOperand(1)->getType();
4839   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4840   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4841 
4842   // If we have computed a smaller type for the expression, update VecTy so
4843   // that the costs will be accurate.
4844   if (MinBWs.count(VL[0]))
4845     VecTy = FixedVectorType::get(
4846         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4847   unsigned EntryVF = E->getVectorFactor();
4848   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4849 
4850   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4851   // FIXME: it tries to fix a problem with MSVC buildbots.
4852   TargetTransformInfo &TTIRef = *TTI;
4853   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4854                                VectorizedVals, E](InstructionCost &Cost) {
4855     DenseMap<Value *, int> ExtractVectorsTys;
4856     SmallPtrSet<Value *, 4> CheckedExtracts;
4857     for (auto *V : VL) {
4858       if (isa<UndefValue>(V))
4859         continue;
4860       // If all users of instruction are going to be vectorized and this
4861       // instruction itself is not going to be vectorized, consider this
4862       // instruction as dead and remove its cost from the final cost of the
4863       // vectorized tree.
4864       // Also, avoid adjusting the cost for extractelements with multiple uses
4865       // in different graph entries.
4866       const TreeEntry *VE = getTreeEntry(V);
4867       if (!CheckedExtracts.insert(V).second ||
4868           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4869           (VE && VE != E))
4870         continue;
4871       auto *EE = cast<ExtractElementInst>(V);
4872       Optional<unsigned> EEIdx = getExtractIndex(EE);
4873       if (!EEIdx)
4874         continue;
4875       unsigned Idx = *EEIdx;
4876       if (TTIRef.getNumberOfParts(VecTy) !=
4877           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4878         auto It =
4879             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4880         It->getSecond() = std::min<int>(It->second, Idx);
4881       }
4882       // Take credit for instruction that will become dead.
4883       if (EE->hasOneUse()) {
4884         Instruction *Ext = EE->user_back();
4885         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4886             all_of(Ext->users(),
4887                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4888           // Use getExtractWithExtendCost() to calculate the cost of
4889           // extractelement/ext pair.
4890           Cost -=
4891               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4892                                               EE->getVectorOperandType(), Idx);
4893           // Add back the cost of s|zext which is subtracted separately.
4894           Cost += TTIRef.getCastInstrCost(
4895               Ext->getOpcode(), Ext->getType(), EE->getType(),
4896               TTI::getCastContextHint(Ext), CostKind, Ext);
4897           continue;
4898         }
4899       }
4900       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4901                                         EE->getVectorOperandType(), Idx);
4902     }
4903     // Add a cost for subvector extracts/inserts if required.
4904     for (const auto &Data : ExtractVectorsTys) {
4905       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4906       unsigned NumElts = VecTy->getNumElements();
4907       if (Data.second % NumElts == 0)
4908         continue;
4909       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4910         unsigned Idx = (Data.second / NumElts) * NumElts;
4911         unsigned EENumElts = EEVTy->getNumElements();
4912         if (Idx + NumElts <= EENumElts) {
4913           Cost +=
4914               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4915                                     EEVTy, None, Idx, VecTy);
4916         } else {
4917           // Need to round up the subvector type vectorization factor to avoid a
4918           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4919           // <= EENumElts.
4920           auto *SubVT =
4921               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4922           Cost +=
4923               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4924                                     EEVTy, None, Idx, SubVT);
4925         }
4926       } else {
4927         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4928                                       VecTy, None, 0, EEVTy);
4929       }
4930     }
4931   };
4932   if (E->State == TreeEntry::NeedToGather) {
4933     if (allConstant(VL))
4934       return 0;
4935     if (isa<InsertElementInst>(VL[0]))
4936       return InstructionCost::getInvalid();
4937     SmallVector<int> Mask;
4938     SmallVector<const TreeEntry *> Entries;
4939     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4940         isGatherShuffledEntry(E, Mask, Entries);
4941     if (Shuffle.hasValue()) {
4942       InstructionCost GatherCost = 0;
4943       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4944         // Perfect match in the graph, will reuse the previously vectorized
4945         // node. Cost is 0.
4946         LLVM_DEBUG(
4947             dbgs()
4948             << "SLP: perfect diamond match for gather bundle that starts with "
4949             << *VL.front() << ".\n");
4950         if (NeedToShuffleReuses)
4951           GatherCost =
4952               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4953                                   FinalVecTy, E->ReuseShuffleIndices);
4954       } else {
4955         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4956                           << " entries for bundle that starts with "
4957                           << *VL.front() << ".\n");
4958         // Detected that instead of gather we can emit a shuffle of single/two
4959         // previously vectorized nodes. Add the cost of the permutation rather
4960         // than gather.
4961         ::addMask(Mask, E->ReuseShuffleIndices);
4962         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4963       }
4964       return GatherCost;
4965     }
4966     if ((E->getOpcode() == Instruction::ExtractElement ||
4967          all_of(E->Scalars,
4968                 [](Value *V) {
4969                   return isa<ExtractElementInst, UndefValue>(V);
4970                 })) &&
4971         allSameType(VL)) {
4972       // Check that gather of extractelements can be represented as just a
4973       // shuffle of a single/two vectors the scalars are extracted from.
4974       SmallVector<int> Mask;
4975       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4976           isFixedVectorShuffle(VL, Mask);
4977       if (ShuffleKind.hasValue()) {
4978         // Found the bunch of extractelement instructions that must be gathered
4979         // into a vector and can be represented as a permutation elements in a
4980         // single input vector or of 2 input vectors.
4981         InstructionCost Cost =
4982             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4983         AdjustExtractsCost(Cost);
4984         if (NeedToShuffleReuses)
4985           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4986                                       FinalVecTy, E->ReuseShuffleIndices);
4987         return Cost;
4988       }
4989     }
4990     if (isSplat(VL)) {
4991       // Found the broadcasting of the single scalar, calculate the cost as the
4992       // broadcast.
4993       assert(VecTy == FinalVecTy &&
4994              "No reused scalars expected for broadcast.");
4995       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4996     }
4997     InstructionCost ReuseShuffleCost = 0;
4998     if (NeedToShuffleReuses)
4999       ReuseShuffleCost = TTI->getShuffleCost(
5000           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5001     // Improve gather cost for gather of loads, if we can group some of the
5002     // loads into vector loads.
5003     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5004         !E->isAltShuffle()) {
5005       BoUpSLP::ValueSet VectorizedLoads;
5006       unsigned StartIdx = 0;
5007       unsigned VF = VL.size() / 2;
5008       unsigned VectorizedCnt = 0;
5009       unsigned ScatterVectorizeCnt = 0;
5010       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5011       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5012         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5013              Cnt += VF) {
5014           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5015           if (!VectorizedLoads.count(Slice.front()) &&
5016               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5017             SmallVector<Value *> PointerOps;
5018             OrdersType CurrentOrder;
5019             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5020                                               *SE, CurrentOrder, PointerOps);
5021             switch (LS) {
5022             case LoadsState::Vectorize:
5023             case LoadsState::ScatterVectorize:
5024               // Mark the vectorized loads so that we don't vectorize them
5025               // again.
5026               if (LS == LoadsState::Vectorize)
5027                 ++VectorizedCnt;
5028               else
5029                 ++ScatterVectorizeCnt;
5030               VectorizedLoads.insert(Slice.begin(), Slice.end());
5031               // If we vectorized initial block, no need to try to vectorize it
5032               // again.
5033               if (Cnt == StartIdx)
5034                 StartIdx += VF;
5035               break;
5036             case LoadsState::Gather:
5037               break;
5038             }
5039           }
5040         }
5041         // Check if the whole array was vectorized already - exit.
5042         if (StartIdx >= VL.size())
5043           break;
5044         // Found vectorizable parts - exit.
5045         if (!VectorizedLoads.empty())
5046           break;
5047       }
5048       if (!VectorizedLoads.empty()) {
5049         InstructionCost GatherCost = 0;
5050         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5051         bool NeedInsertSubvectorAnalysis =
5052             !NumParts || (VL.size() / VF) > NumParts;
5053         // Get the cost for gathered loads.
5054         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5055           if (VectorizedLoads.contains(VL[I]))
5056             continue;
5057           GatherCost += getGatherCost(VL.slice(I, VF));
5058         }
5059         // The cost for vectorized loads.
5060         InstructionCost ScalarsCost = 0;
5061         for (Value *V : VectorizedLoads) {
5062           auto *LI = cast<LoadInst>(V);
5063           ScalarsCost += TTI->getMemoryOpCost(
5064               Instruction::Load, LI->getType(), LI->getAlign(),
5065               LI->getPointerAddressSpace(), CostKind, LI);
5066         }
5067         auto *LI = cast<LoadInst>(E->getMainOp());
5068         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5069         Align Alignment = LI->getAlign();
5070         GatherCost +=
5071             VectorizedCnt *
5072             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5073                                  LI->getPointerAddressSpace(), CostKind, LI);
5074         GatherCost += ScatterVectorizeCnt *
5075                       TTI->getGatherScatterOpCost(
5076                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5077                           /*VariableMask=*/false, Alignment, CostKind, LI);
5078         if (NeedInsertSubvectorAnalysis) {
5079           // Add the cost for the subvectors insert.
5080           for (int I = VF, E = VL.size(); I < E; I += VF)
5081             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5082                                               None, I, LoadTy);
5083         }
5084         return ReuseShuffleCost + GatherCost - ScalarsCost;
5085       }
5086     }
5087     return ReuseShuffleCost + getGatherCost(VL);
5088   }
5089   InstructionCost CommonCost = 0;
5090   SmallVector<int> Mask;
5091   if (!E->ReorderIndices.empty()) {
5092     SmallVector<int> NewMask;
5093     if (E->getOpcode() == Instruction::Store) {
5094       // For stores the order is actually a mask.
5095       NewMask.resize(E->ReorderIndices.size());
5096       copy(E->ReorderIndices, NewMask.begin());
5097     } else {
5098       inversePermutation(E->ReorderIndices, NewMask);
5099     }
5100     ::addMask(Mask, NewMask);
5101   }
5102   if (NeedToShuffleReuses)
5103     ::addMask(Mask, E->ReuseShuffleIndices);
5104   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5105     CommonCost =
5106         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5107   assert((E->State == TreeEntry::Vectorize ||
5108           E->State == TreeEntry::ScatterVectorize) &&
5109          "Unhandled state");
5110   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5111   Instruction *VL0 = E->getMainOp();
5112   unsigned ShuffleOrOp =
5113       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5114   switch (ShuffleOrOp) {
5115     case Instruction::PHI:
5116       return 0;
5117 
5118     case Instruction::ExtractValue:
5119     case Instruction::ExtractElement: {
5120       // The common cost of removal ExtractElement/ExtractValue instructions +
5121       // the cost of shuffles, if required to resuffle the original vector.
5122       if (NeedToShuffleReuses) {
5123         unsigned Idx = 0;
5124         for (unsigned I : E->ReuseShuffleIndices) {
5125           if (ShuffleOrOp == Instruction::ExtractElement) {
5126             auto *EE = cast<ExtractElementInst>(VL[I]);
5127             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5128                                                   EE->getVectorOperandType(),
5129                                                   *getExtractIndex(EE));
5130           } else {
5131             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5132                                                   VecTy, Idx);
5133             ++Idx;
5134           }
5135         }
5136         Idx = EntryVF;
5137         for (Value *V : VL) {
5138           if (ShuffleOrOp == Instruction::ExtractElement) {
5139             auto *EE = cast<ExtractElementInst>(V);
5140             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5141                                                   EE->getVectorOperandType(),
5142                                                   *getExtractIndex(EE));
5143           } else {
5144             --Idx;
5145             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5146                                                   VecTy, Idx);
5147           }
5148         }
5149       }
5150       if (ShuffleOrOp == Instruction::ExtractValue) {
5151         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5152           auto *EI = cast<Instruction>(VL[I]);
5153           // Take credit for instruction that will become dead.
5154           if (EI->hasOneUse()) {
5155             Instruction *Ext = EI->user_back();
5156             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5157                 all_of(Ext->users(),
5158                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5159               // Use getExtractWithExtendCost() to calculate the cost of
5160               // extractelement/ext pair.
5161               CommonCost -= TTI->getExtractWithExtendCost(
5162                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5163               // Add back the cost of s|zext which is subtracted separately.
5164               CommonCost += TTI->getCastInstrCost(
5165                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5166                   TTI::getCastContextHint(Ext), CostKind, Ext);
5167               continue;
5168             }
5169           }
5170           CommonCost -=
5171               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5172         }
5173       } else {
5174         AdjustExtractsCost(CommonCost);
5175       }
5176       return CommonCost;
5177     }
5178     case Instruction::InsertElement: {
5179       assert(E->ReuseShuffleIndices.empty() &&
5180              "Unique insertelements only are expected.");
5181       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5182 
5183       unsigned const NumElts = SrcVecTy->getNumElements();
5184       unsigned const NumScalars = VL.size();
5185       APInt DemandedElts = APInt::getZero(NumElts);
5186       // TODO: Add support for Instruction::InsertValue.
5187       SmallVector<int> Mask;
5188       if (!E->ReorderIndices.empty()) {
5189         inversePermutation(E->ReorderIndices, Mask);
5190         Mask.append(NumElts - NumScalars, UndefMaskElem);
5191       } else {
5192         Mask.assign(NumElts, UndefMaskElem);
5193         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5194       }
5195       unsigned Offset = *getInsertIndex(VL0, 0);
5196       bool IsIdentity = true;
5197       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5198       Mask.swap(PrevMask);
5199       for (unsigned I = 0; I < NumScalars; ++I) {
5200         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
5201         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5202           continue;
5203         DemandedElts.setBit(*InsertIdx);
5204         IsIdentity &= *InsertIdx - Offset == I;
5205         Mask[*InsertIdx - Offset] = I;
5206       }
5207       assert(Offset < NumElts && "Failed to find vector index offset");
5208 
5209       InstructionCost Cost = 0;
5210       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5211                                             /*Insert*/ true, /*Extract*/ false);
5212 
5213       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5214         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5215         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5216         Cost += TTI->getShuffleCost(
5217             TargetTransformInfo::SK_PermuteSingleSrc,
5218             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5219       } else if (!IsIdentity) {
5220         auto *FirstInsert =
5221             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5222               return !is_contained(E->Scalars,
5223                                    cast<Instruction>(V)->getOperand(0));
5224             }));
5225         if (isUndefVector(FirstInsert->getOperand(0))) {
5226           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5227         } else {
5228           SmallVector<int> InsertMask(NumElts);
5229           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5230           for (unsigned I = 0; I < NumElts; I++) {
5231             if (Mask[I] != UndefMaskElem)
5232               InsertMask[Offset + I] = NumElts + I;
5233           }
5234           Cost +=
5235               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5236         }
5237       }
5238 
5239       return Cost;
5240     }
5241     case Instruction::ZExt:
5242     case Instruction::SExt:
5243     case Instruction::FPToUI:
5244     case Instruction::FPToSI:
5245     case Instruction::FPExt:
5246     case Instruction::PtrToInt:
5247     case Instruction::IntToPtr:
5248     case Instruction::SIToFP:
5249     case Instruction::UIToFP:
5250     case Instruction::Trunc:
5251     case Instruction::FPTrunc:
5252     case Instruction::BitCast: {
5253       Type *SrcTy = VL0->getOperand(0)->getType();
5254       InstructionCost ScalarEltCost =
5255           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5256                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5257       if (NeedToShuffleReuses) {
5258         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5259       }
5260 
5261       // Calculate the cost of this instruction.
5262       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5263 
5264       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5265       InstructionCost VecCost = 0;
5266       // Check if the values are candidates to demote.
5267       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5268         VecCost = CommonCost + TTI->getCastInstrCost(
5269                                    E->getOpcode(), VecTy, SrcVecTy,
5270                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5271       }
5272       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5273       return VecCost - ScalarCost;
5274     }
5275     case Instruction::FCmp:
5276     case Instruction::ICmp:
5277     case Instruction::Select: {
5278       // Calculate the cost of this instruction.
5279       InstructionCost ScalarEltCost =
5280           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5281                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5282       if (NeedToShuffleReuses) {
5283         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5284       }
5285       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5286       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5287 
5288       // Check if all entries in VL are either compares or selects with compares
5289       // as condition that have the same predicates.
5290       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5291       bool First = true;
5292       for (auto *V : VL) {
5293         CmpInst::Predicate CurrentPred;
5294         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5295         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5296              !match(V, MatchCmp)) ||
5297             (!First && VecPred != CurrentPred)) {
5298           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5299           break;
5300         }
5301         First = false;
5302         VecPred = CurrentPred;
5303       }
5304 
5305       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5306           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5307       // Check if it is possible and profitable to use min/max for selects in
5308       // VL.
5309       //
5310       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5311       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5312         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5313                                           {VecTy, VecTy});
5314         InstructionCost IntrinsicCost =
5315             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5316         // If the selects are the only uses of the compares, they will be dead
5317         // and we can adjust the cost by removing their cost.
5318         if (IntrinsicAndUse.second)
5319           IntrinsicCost -=
5320               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5321                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5322         VecCost = std::min(VecCost, IntrinsicCost);
5323       }
5324       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5325       return CommonCost + VecCost - ScalarCost;
5326     }
5327     case Instruction::FNeg:
5328     case Instruction::Add:
5329     case Instruction::FAdd:
5330     case Instruction::Sub:
5331     case Instruction::FSub:
5332     case Instruction::Mul:
5333     case Instruction::FMul:
5334     case Instruction::UDiv:
5335     case Instruction::SDiv:
5336     case Instruction::FDiv:
5337     case Instruction::URem:
5338     case Instruction::SRem:
5339     case Instruction::FRem:
5340     case Instruction::Shl:
5341     case Instruction::LShr:
5342     case Instruction::AShr:
5343     case Instruction::And:
5344     case Instruction::Or:
5345     case Instruction::Xor: {
5346       // Certain instructions can be cheaper to vectorize if they have a
5347       // constant second vector operand.
5348       TargetTransformInfo::OperandValueKind Op1VK =
5349           TargetTransformInfo::OK_AnyValue;
5350       TargetTransformInfo::OperandValueKind Op2VK =
5351           TargetTransformInfo::OK_UniformConstantValue;
5352       TargetTransformInfo::OperandValueProperties Op1VP =
5353           TargetTransformInfo::OP_None;
5354       TargetTransformInfo::OperandValueProperties Op2VP =
5355           TargetTransformInfo::OP_PowerOf2;
5356 
5357       // If all operands are exactly the same ConstantInt then set the
5358       // operand kind to OK_UniformConstantValue.
5359       // If instead not all operands are constants, then set the operand kind
5360       // to OK_AnyValue. If all operands are constants but not the same,
5361       // then set the operand kind to OK_NonUniformConstantValue.
5362       ConstantInt *CInt0 = nullptr;
5363       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5364         const Instruction *I = cast<Instruction>(VL[i]);
5365         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5366         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5367         if (!CInt) {
5368           Op2VK = TargetTransformInfo::OK_AnyValue;
5369           Op2VP = TargetTransformInfo::OP_None;
5370           break;
5371         }
5372         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5373             !CInt->getValue().isPowerOf2())
5374           Op2VP = TargetTransformInfo::OP_None;
5375         if (i == 0) {
5376           CInt0 = CInt;
5377           continue;
5378         }
5379         if (CInt0 != CInt)
5380           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5381       }
5382 
5383       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5384       InstructionCost ScalarEltCost =
5385           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5386                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5387       if (NeedToShuffleReuses) {
5388         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5389       }
5390       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5391       InstructionCost VecCost =
5392           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5393                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5394       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5395       return CommonCost + VecCost - ScalarCost;
5396     }
5397     case Instruction::GetElementPtr: {
5398       TargetTransformInfo::OperandValueKind Op1VK =
5399           TargetTransformInfo::OK_AnyValue;
5400       TargetTransformInfo::OperandValueKind Op2VK =
5401           TargetTransformInfo::OK_UniformConstantValue;
5402 
5403       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5404           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5405       if (NeedToShuffleReuses) {
5406         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5407       }
5408       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5409       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5410           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5411       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5412       return CommonCost + VecCost - ScalarCost;
5413     }
5414     case Instruction::Load: {
5415       // Cost of wide load - cost of scalar loads.
5416       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5417       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5418           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5419       if (NeedToShuffleReuses) {
5420         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5421       }
5422       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5423       InstructionCost VecLdCost;
5424       if (E->State == TreeEntry::Vectorize) {
5425         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5426                                          CostKind, VL0);
5427       } else {
5428         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5429         Align CommonAlignment = Alignment;
5430         for (Value *V : VL)
5431           CommonAlignment =
5432               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5433         VecLdCost = TTI->getGatherScatterOpCost(
5434             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5435             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5436       }
5437       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5438       return CommonCost + VecLdCost - ScalarLdCost;
5439     }
5440     case Instruction::Store: {
5441       // We know that we can merge the stores. Calculate the cost.
5442       bool IsReorder = !E->ReorderIndices.empty();
5443       auto *SI =
5444           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5445       Align Alignment = SI->getAlign();
5446       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5447           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5448       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5449       InstructionCost VecStCost = TTI->getMemoryOpCost(
5450           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5451       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5452       return CommonCost + VecStCost - ScalarStCost;
5453     }
5454     case Instruction::Call: {
5455       CallInst *CI = cast<CallInst>(VL0);
5456       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5457 
5458       // Calculate the cost of the scalar and vector calls.
5459       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5460       InstructionCost ScalarEltCost =
5461           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5462       if (NeedToShuffleReuses) {
5463         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5464       }
5465       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5466 
5467       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5468       InstructionCost VecCallCost =
5469           std::min(VecCallCosts.first, VecCallCosts.second);
5470 
5471       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5472                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5473                         << " for " << *CI << "\n");
5474 
5475       return CommonCost + VecCallCost - ScalarCallCost;
5476     }
5477     case Instruction::ShuffleVector: {
5478       assert(E->isAltShuffle() &&
5479              ((Instruction::isBinaryOp(E->getOpcode()) &&
5480                Instruction::isBinaryOp(E->getAltOpcode())) ||
5481               (Instruction::isCast(E->getOpcode()) &&
5482                Instruction::isCast(E->getAltOpcode())) ||
5483               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5484              "Invalid Shuffle Vector Operand");
5485       InstructionCost ScalarCost = 0;
5486       if (NeedToShuffleReuses) {
5487         for (unsigned Idx : E->ReuseShuffleIndices) {
5488           Instruction *I = cast<Instruction>(VL[Idx]);
5489           CommonCost -= TTI->getInstructionCost(I, CostKind);
5490         }
5491         for (Value *V : VL) {
5492           Instruction *I = cast<Instruction>(V);
5493           CommonCost += TTI->getInstructionCost(I, CostKind);
5494         }
5495       }
5496       for (Value *V : VL) {
5497         Instruction *I = cast<Instruction>(V);
5498         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5499         ScalarCost += TTI->getInstructionCost(I, CostKind);
5500       }
5501       // VecCost is equal to sum of the cost of creating 2 vectors
5502       // and the cost of creating shuffle.
5503       InstructionCost VecCost = 0;
5504       // Try to find the previous shuffle node with the same operands and same
5505       // main/alternate ops.
5506       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5507         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5508           if (TE.get() == E)
5509             break;
5510           if (TE->isAltShuffle() &&
5511               ((TE->getOpcode() == E->getOpcode() &&
5512                 TE->getAltOpcode() == E->getAltOpcode()) ||
5513                (TE->getOpcode() == E->getAltOpcode() &&
5514                 TE->getAltOpcode() == E->getOpcode())) &&
5515               TE->hasEqualOperands(*E))
5516             return true;
5517         }
5518         return false;
5519       };
5520       if (TryFindNodeWithEqualOperands()) {
5521         LLVM_DEBUG({
5522           dbgs() << "SLP: diamond match for alternate node found.\n";
5523           E->dump();
5524         });
5525         // No need to add new vector costs here since we're going to reuse
5526         // same main/alternate vector ops, just do different shuffling.
5527       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5528         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5529         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5530                                                CostKind);
5531       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5532         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5533                                           Builder.getInt1Ty(),
5534                                           CI0->getPredicate(), CostKind, VL0);
5535         VecCost += TTI->getCmpSelInstrCost(
5536             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5537             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5538             E->getAltOp());
5539       } else {
5540         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5541         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5542         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5543         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5544         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5545                                         TTI::CastContextHint::None, CostKind);
5546         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5547                                          TTI::CastContextHint::None, CostKind);
5548       }
5549 
5550       SmallVector<int> Mask;
5551       buildSuffleEntryMask(
5552           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5553           [E](Instruction *I) {
5554             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5555             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
5556               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
5557               auto *CI = cast<CmpInst>(I);
5558               CmpInst::Predicate P0 = CI0->getPredicate();
5559               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5560               assert(P0 != AltP0 &&
5561                      "Expected different main/alternate predicates.");
5562               CmpInst::Predicate AltP0Swapped =
5563                   CmpInst::getSwappedPredicate(AltP0);
5564               CmpInst::Predicate CurrentPred = CI->getPredicate();
5565               if (P0 == AltP0Swapped)
5566                 return (P0 == CurrentPred &&
5567                         !areCompatibleCmpOps(
5568                             CI0->getOperand(0), CI0->getOperand(1),
5569                             CI->getOperand(0), CI->getOperand(1))) ||
5570                        (AltP0 == CurrentPred &&
5571                         !areCompatibleCmpOps(
5572                             CI0->getOperand(0), CI0->getOperand(1),
5573                             CI->getOperand(1), CI->getOperand(0)));
5574               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5575             }
5576             return I->getOpcode() == E->getAltOpcode();
5577           },
5578           Mask);
5579       CommonCost =
5580           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5581       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5582       return CommonCost + VecCost - ScalarCost;
5583     }
5584     default:
5585       llvm_unreachable("Unknown instruction");
5586   }
5587 }
5588 
5589 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5590   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5591                     << VectorizableTree.size() << " is fully vectorizable .\n");
5592 
5593   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5594     SmallVector<int> Mask;
5595     return TE->State == TreeEntry::NeedToGather &&
5596            !any_of(TE->Scalars,
5597                    [this](Value *V) { return EphValues.contains(V); }) &&
5598            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5599             TE->Scalars.size() < Limit ||
5600             ((TE->getOpcode() == Instruction::ExtractElement ||
5601               all_of(TE->Scalars,
5602                      [](Value *V) {
5603                        return isa<ExtractElementInst, UndefValue>(V);
5604                      })) &&
5605              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5606             (TE->State == TreeEntry::NeedToGather &&
5607              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5608   };
5609 
5610   // We only handle trees of heights 1 and 2.
5611   if (VectorizableTree.size() == 1 &&
5612       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5613        (ForReduction &&
5614         AreVectorizableGathers(VectorizableTree[0].get(),
5615                                VectorizableTree[0]->Scalars.size()) &&
5616         VectorizableTree[0]->getVectorFactor() > 2)))
5617     return true;
5618 
5619   if (VectorizableTree.size() != 2)
5620     return false;
5621 
5622   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5623   // with the second gather nodes if they have less scalar operands rather than
5624   // the initial tree element (may be profitable to shuffle the second gather)
5625   // or they are extractelements, which form shuffle.
5626   SmallVector<int> Mask;
5627   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5628       AreVectorizableGathers(VectorizableTree[1].get(),
5629                              VectorizableTree[0]->Scalars.size()))
5630     return true;
5631 
5632   // Gathering cost would be too much for tiny trees.
5633   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5634       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5635        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5636     return false;
5637 
5638   return true;
5639 }
5640 
5641 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5642                                        TargetTransformInfo *TTI,
5643                                        bool MustMatchOrInst) {
5644   // Look past the root to find a source value. Arbitrarily follow the
5645   // path through operand 0 of any 'or'. Also, peek through optional
5646   // shift-left-by-multiple-of-8-bits.
5647   Value *ZextLoad = Root;
5648   const APInt *ShAmtC;
5649   bool FoundOr = false;
5650   while (!isa<ConstantExpr>(ZextLoad) &&
5651          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5652           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5653            ShAmtC->urem(8) == 0))) {
5654     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5655     ZextLoad = BinOp->getOperand(0);
5656     if (BinOp->getOpcode() == Instruction::Or)
5657       FoundOr = true;
5658   }
5659   // Check if the input is an extended load of the required or/shift expression.
5660   Value *Load;
5661   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5662       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5663     return false;
5664 
5665   // Require that the total load bit width is a legal integer type.
5666   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5667   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5668   Type *SrcTy = Load->getType();
5669   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5670   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5671     return false;
5672 
5673   // Everything matched - assume that we can fold the whole sequence using
5674   // load combining.
5675   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5676              << *(cast<Instruction>(Root)) << "\n");
5677 
5678   return true;
5679 }
5680 
5681 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5682   if (RdxKind != RecurKind::Or)
5683     return false;
5684 
5685   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5686   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5687   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5688                                     /* MatchOr */ false);
5689 }
5690 
5691 bool BoUpSLP::isLoadCombineCandidate() const {
5692   // Peek through a final sequence of stores and check if all operations are
5693   // likely to be load-combined.
5694   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5695   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5696     Value *X;
5697     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5698         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5699       return false;
5700   }
5701   return true;
5702 }
5703 
5704 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5705   // No need to vectorize inserts of gathered values.
5706   if (VectorizableTree.size() == 2 &&
5707       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5708       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5709     return true;
5710 
5711   // We can vectorize the tree if its size is greater than or equal to the
5712   // minimum size specified by the MinTreeSize command line option.
5713   if (VectorizableTree.size() >= MinTreeSize)
5714     return false;
5715 
5716   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5717   // can vectorize it if we can prove it fully vectorizable.
5718   if (isFullyVectorizableTinyTree(ForReduction))
5719     return false;
5720 
5721   assert(VectorizableTree.empty()
5722              ? ExternalUses.empty()
5723              : true && "We shouldn't have any external users");
5724 
5725   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5726   // vectorizable.
5727   return true;
5728 }
5729 
5730 InstructionCost BoUpSLP::getSpillCost() const {
5731   // Walk from the bottom of the tree to the top, tracking which values are
5732   // live. When we see a call instruction that is not part of our tree,
5733   // query TTI to see if there is a cost to keeping values live over it
5734   // (for example, if spills and fills are required).
5735   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5736   InstructionCost Cost = 0;
5737 
5738   SmallPtrSet<Instruction*, 4> LiveValues;
5739   Instruction *PrevInst = nullptr;
5740 
5741   // The entries in VectorizableTree are not necessarily ordered by their
5742   // position in basic blocks. Collect them and order them by dominance so later
5743   // instructions are guaranteed to be visited first. For instructions in
5744   // different basic blocks, we only scan to the beginning of the block, so
5745   // their order does not matter, as long as all instructions in a basic block
5746   // are grouped together. Using dominance ensures a deterministic order.
5747   SmallVector<Instruction *, 16> OrderedScalars;
5748   for (const auto &TEPtr : VectorizableTree) {
5749     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5750     if (!Inst)
5751       continue;
5752     OrderedScalars.push_back(Inst);
5753   }
5754   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5755     auto *NodeA = DT->getNode(A->getParent());
5756     auto *NodeB = DT->getNode(B->getParent());
5757     assert(NodeA && "Should only process reachable instructions");
5758     assert(NodeB && "Should only process reachable instructions");
5759     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5760            "Different nodes should have different DFS numbers");
5761     if (NodeA != NodeB)
5762       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5763     return B->comesBefore(A);
5764   });
5765 
5766   for (Instruction *Inst : OrderedScalars) {
5767     if (!PrevInst) {
5768       PrevInst = Inst;
5769       continue;
5770     }
5771 
5772     // Update LiveValues.
5773     LiveValues.erase(PrevInst);
5774     for (auto &J : PrevInst->operands()) {
5775       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5776         LiveValues.insert(cast<Instruction>(&*J));
5777     }
5778 
5779     LLVM_DEBUG({
5780       dbgs() << "SLP: #LV: " << LiveValues.size();
5781       for (auto *X : LiveValues)
5782         dbgs() << " " << X->getName();
5783       dbgs() << ", Looking at ";
5784       Inst->dump();
5785     });
5786 
5787     // Now find the sequence of instructions between PrevInst and Inst.
5788     unsigned NumCalls = 0;
5789     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5790                                  PrevInstIt =
5791                                      PrevInst->getIterator().getReverse();
5792     while (InstIt != PrevInstIt) {
5793       if (PrevInstIt == PrevInst->getParent()->rend()) {
5794         PrevInstIt = Inst->getParent()->rbegin();
5795         continue;
5796       }
5797 
5798       // Debug information does not impact spill cost.
5799       if ((isa<CallInst>(&*PrevInstIt) &&
5800            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5801           &*PrevInstIt != PrevInst)
5802         NumCalls++;
5803 
5804       ++PrevInstIt;
5805     }
5806 
5807     if (NumCalls) {
5808       SmallVector<Type*, 4> V;
5809       for (auto *II : LiveValues) {
5810         auto *ScalarTy = II->getType();
5811         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5812           ScalarTy = VectorTy->getElementType();
5813         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5814       }
5815       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5816     }
5817 
5818     PrevInst = Inst;
5819   }
5820 
5821   return Cost;
5822 }
5823 
5824 /// Check if two insertelement instructions are from the same buildvector.
5825 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5826                                             InsertElementInst *V) {
5827   // Instructions must be from the same basic blocks.
5828   if (VU->getParent() != V->getParent())
5829     return false;
5830   // Checks if 2 insertelements are from the same buildvector.
5831   if (VU->getType() != V->getType())
5832     return false;
5833   // Multiple used inserts are separate nodes.
5834   if (!VU->hasOneUse() && !V->hasOneUse())
5835     return false;
5836   auto *IE1 = VU;
5837   auto *IE2 = V;
5838   // Go through the vector operand of insertelement instructions trying to find
5839   // either VU as the original vector for IE2 or V as the original vector for
5840   // IE1.
5841   do {
5842     if (IE2 == VU || IE1 == V)
5843       return true;
5844     if (IE1) {
5845       if (IE1 != VU && !IE1->hasOneUse())
5846         IE1 = nullptr;
5847       else
5848         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5849     }
5850     if (IE2) {
5851       if (IE2 != V && !IE2->hasOneUse())
5852         IE2 = nullptr;
5853       else
5854         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5855     }
5856   } while (IE1 || IE2);
5857   return false;
5858 }
5859 
5860 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5861   InstructionCost Cost = 0;
5862   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5863                     << VectorizableTree.size() << ".\n");
5864 
5865   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5866 
5867   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5868     TreeEntry &TE = *VectorizableTree[I].get();
5869 
5870     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5871     Cost += C;
5872     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5873                       << " for bundle that starts with " << *TE.Scalars[0]
5874                       << ".\n"
5875                       << "SLP: Current total cost = " << Cost << "\n");
5876   }
5877 
5878   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5879   InstructionCost ExtractCost = 0;
5880   SmallVector<unsigned> VF;
5881   SmallVector<SmallVector<int>> ShuffleMask;
5882   SmallVector<Value *> FirstUsers;
5883   SmallVector<APInt> DemandedElts;
5884   for (ExternalUser &EU : ExternalUses) {
5885     // We only add extract cost once for the same scalar.
5886     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5887         !ExtractCostCalculated.insert(EU.Scalar).second)
5888       continue;
5889 
5890     // Uses by ephemeral values are free (because the ephemeral value will be
5891     // removed prior to code generation, and so the extraction will be
5892     // removed as well).
5893     if (EphValues.count(EU.User))
5894       continue;
5895 
5896     // No extract cost for vector "scalar"
5897     if (isa<FixedVectorType>(EU.Scalar->getType()))
5898       continue;
5899 
5900     // Already counted the cost for external uses when tried to adjust the cost
5901     // for extractelements, no need to add it again.
5902     if (isa<ExtractElementInst>(EU.Scalar))
5903       continue;
5904 
5905     // If found user is an insertelement, do not calculate extract cost but try
5906     // to detect it as a final shuffled/identity match.
5907     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5908       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5909         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5910         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5911           continue;
5912         auto *It = find_if(FirstUsers, [VU](Value *V) {
5913           return areTwoInsertFromSameBuildVector(VU,
5914                                                  cast<InsertElementInst>(V));
5915         });
5916         int VecId = -1;
5917         if (It == FirstUsers.end()) {
5918           VF.push_back(FTy->getNumElements());
5919           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5920           // Find the insertvector, vectorized in tree, if any.
5921           Value *Base = VU;
5922           while (isa<InsertElementInst>(Base)) {
5923             // Build the mask for the vectorized insertelement instructions.
5924             if (const TreeEntry *E = getTreeEntry(Base)) {
5925               VU = cast<InsertElementInst>(Base);
5926               do {
5927                 int Idx = E->findLaneForValue(Base);
5928                 ShuffleMask.back()[Idx] = Idx;
5929                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5930               } while (E == getTreeEntry(Base));
5931               break;
5932             }
5933             Base = cast<InsertElementInst>(Base)->getOperand(0);
5934           }
5935           FirstUsers.push_back(VU);
5936           DemandedElts.push_back(APInt::getZero(VF.back()));
5937           VecId = FirstUsers.size() - 1;
5938         } else {
5939           VecId = std::distance(FirstUsers.begin(), It);
5940         }
5941         int Idx = *InsertIdx;
5942         ShuffleMask[VecId][Idx] = EU.Lane;
5943         DemandedElts[VecId].setBit(Idx);
5944         continue;
5945       }
5946     }
5947 
5948     // If we plan to rewrite the tree in a smaller type, we will need to sign
5949     // extend the extracted value back to the original type. Here, we account
5950     // for the extract and the added cost of the sign extend if needed.
5951     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5952     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5953     if (MinBWs.count(ScalarRoot)) {
5954       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5955       auto Extend =
5956           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5957       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5958       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5959                                                    VecTy, EU.Lane);
5960     } else {
5961       ExtractCost +=
5962           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5963     }
5964   }
5965 
5966   InstructionCost SpillCost = getSpillCost();
5967   Cost += SpillCost + ExtractCost;
5968   if (FirstUsers.size() == 1) {
5969     int Limit = ShuffleMask.front().size() * 2;
5970     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5971         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5972       InstructionCost C = TTI->getShuffleCost(
5973           TTI::SK_PermuteSingleSrc,
5974           cast<FixedVectorType>(FirstUsers.front()->getType()),
5975           ShuffleMask.front());
5976       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5977                         << " for final shuffle of insertelement external users "
5978                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5979                         << "SLP: Current total cost = " << Cost << "\n");
5980       Cost += C;
5981     }
5982     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5983         cast<FixedVectorType>(FirstUsers.front()->getType()),
5984         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5985     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5986                       << " for insertelements gather.\n"
5987                       << "SLP: Current total cost = " << Cost << "\n");
5988     Cost -= InsertCost;
5989   } else if (FirstUsers.size() >= 2) {
5990     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5991     // Combined masks of the first 2 vectors.
5992     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5993     copy(ShuffleMask.front(), CombinedMask.begin());
5994     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5995     auto *VecTy = FixedVectorType::get(
5996         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5997         MaxVF);
5998     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5999       if (ShuffleMask[1][I] != UndefMaskElem) {
6000         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6001         CombinedDemandedElts.setBit(I);
6002       }
6003     }
6004     InstructionCost C =
6005         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6006     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6007                       << " for final shuffle of vector node and external "
6008                          "insertelement users "
6009                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6010                       << "SLP: Current total cost = " << Cost << "\n");
6011     Cost += C;
6012     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6013         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6014     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6015                       << " for insertelements gather.\n"
6016                       << "SLP: Current total cost = " << Cost << "\n");
6017     Cost -= InsertCost;
6018     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6019       // Other elements - permutation of 2 vectors (the initial one and the
6020       // next Ith incoming vector).
6021       unsigned VF = ShuffleMask[I].size();
6022       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6023         int Mask = ShuffleMask[I][Idx];
6024         if (Mask != UndefMaskElem)
6025           CombinedMask[Idx] = MaxVF + Mask;
6026         else if (CombinedMask[Idx] != UndefMaskElem)
6027           CombinedMask[Idx] = Idx;
6028       }
6029       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6030         if (CombinedMask[Idx] != UndefMaskElem)
6031           CombinedMask[Idx] = Idx;
6032       InstructionCost C =
6033           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6034       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6035                         << " for final shuffle of vector node and external "
6036                            "insertelement users "
6037                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6038                         << "SLP: Current total cost = " << Cost << "\n");
6039       Cost += C;
6040       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6041           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6042           /*Insert*/ true, /*Extract*/ false);
6043       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6044                         << " for insertelements gather.\n"
6045                         << "SLP: Current total cost = " << Cost << "\n");
6046       Cost -= InsertCost;
6047     }
6048   }
6049 
6050 #ifndef NDEBUG
6051   SmallString<256> Str;
6052   {
6053     raw_svector_ostream OS(Str);
6054     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6055        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6056        << "SLP: Total Cost = " << Cost << ".\n";
6057   }
6058   LLVM_DEBUG(dbgs() << Str);
6059   if (ViewSLPTree)
6060     ViewGraph(this, "SLP" + F->getName(), false, Str);
6061 #endif
6062 
6063   return Cost;
6064 }
6065 
6066 Optional<TargetTransformInfo::ShuffleKind>
6067 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6068                                SmallVectorImpl<const TreeEntry *> &Entries) {
6069   // TODO: currently checking only for Scalars in the tree entry, need to count
6070   // reused elements too for better cost estimation.
6071   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6072   Entries.clear();
6073   // Build a lists of values to tree entries.
6074   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6075   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6076     if (EntryPtr.get() == TE)
6077       break;
6078     if (EntryPtr->State != TreeEntry::NeedToGather)
6079       continue;
6080     for (Value *V : EntryPtr->Scalars)
6081       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6082   }
6083   // Find all tree entries used by the gathered values. If no common entries
6084   // found - not a shuffle.
6085   // Here we build a set of tree nodes for each gathered value and trying to
6086   // find the intersection between these sets. If we have at least one common
6087   // tree node for each gathered value - we have just a permutation of the
6088   // single vector. If we have 2 different sets, we're in situation where we
6089   // have a permutation of 2 input vectors.
6090   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6091   DenseMap<Value *, int> UsedValuesEntry;
6092   for (Value *V : TE->Scalars) {
6093     if (isa<UndefValue>(V))
6094       continue;
6095     // Build a list of tree entries where V is used.
6096     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6097     auto It = ValueToTEs.find(V);
6098     if (It != ValueToTEs.end())
6099       VToTEs = It->second;
6100     if (const TreeEntry *VTE = getTreeEntry(V))
6101       VToTEs.insert(VTE);
6102     if (VToTEs.empty())
6103       return None;
6104     if (UsedTEs.empty()) {
6105       // The first iteration, just insert the list of nodes to vector.
6106       UsedTEs.push_back(VToTEs);
6107     } else {
6108       // Need to check if there are any previously used tree nodes which use V.
6109       // If there are no such nodes, consider that we have another one input
6110       // vector.
6111       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6112       unsigned Idx = 0;
6113       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6114         // Do we have a non-empty intersection of previously listed tree entries
6115         // and tree entries using current V?
6116         set_intersect(VToTEs, Set);
6117         if (!VToTEs.empty()) {
6118           // Yes, write the new subset and continue analysis for the next
6119           // scalar.
6120           Set.swap(VToTEs);
6121           break;
6122         }
6123         VToTEs = SavedVToTEs;
6124         ++Idx;
6125       }
6126       // No non-empty intersection found - need to add a second set of possible
6127       // source vectors.
6128       if (Idx == UsedTEs.size()) {
6129         // If the number of input vectors is greater than 2 - not a permutation,
6130         // fallback to the regular gather.
6131         if (UsedTEs.size() == 2)
6132           return None;
6133         UsedTEs.push_back(SavedVToTEs);
6134         Idx = UsedTEs.size() - 1;
6135       }
6136       UsedValuesEntry.try_emplace(V, Idx);
6137     }
6138   }
6139 
6140   unsigned VF = 0;
6141   if (UsedTEs.size() == 1) {
6142     // Try to find the perfect match in another gather node at first.
6143     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6144       return EntryPtr->isSame(TE->Scalars);
6145     });
6146     if (It != UsedTEs.front().end()) {
6147       Entries.push_back(*It);
6148       std::iota(Mask.begin(), Mask.end(), 0);
6149       return TargetTransformInfo::SK_PermuteSingleSrc;
6150     }
6151     // No perfect match, just shuffle, so choose the first tree node.
6152     Entries.push_back(*UsedTEs.front().begin());
6153   } else {
6154     // Try to find nodes with the same vector factor.
6155     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6156     DenseMap<int, const TreeEntry *> VFToTE;
6157     for (const TreeEntry *TE : UsedTEs.front())
6158       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6159     for (const TreeEntry *TE : UsedTEs.back()) {
6160       auto It = VFToTE.find(TE->getVectorFactor());
6161       if (It != VFToTE.end()) {
6162         VF = It->first;
6163         Entries.push_back(It->second);
6164         Entries.push_back(TE);
6165         break;
6166       }
6167     }
6168     // No 2 source vectors with the same vector factor - give up and do regular
6169     // gather.
6170     if (Entries.empty())
6171       return None;
6172   }
6173 
6174   // Build a shuffle mask for better cost estimation and vector emission.
6175   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6176     Value *V = TE->Scalars[I];
6177     if (isa<UndefValue>(V))
6178       continue;
6179     unsigned Idx = UsedValuesEntry.lookup(V);
6180     const TreeEntry *VTE = Entries[Idx];
6181     int FoundLane = VTE->findLaneForValue(V);
6182     Mask[I] = Idx * VF + FoundLane;
6183     // Extra check required by isSingleSourceMaskImpl function (called by
6184     // ShuffleVectorInst::isSingleSourceMask).
6185     if (Mask[I] >= 2 * E)
6186       return None;
6187   }
6188   switch (Entries.size()) {
6189   case 1:
6190     return TargetTransformInfo::SK_PermuteSingleSrc;
6191   case 2:
6192     return TargetTransformInfo::SK_PermuteTwoSrc;
6193   default:
6194     break;
6195   }
6196   return None;
6197 }
6198 
6199 InstructionCost
6200 BoUpSLP::getGatherCost(FixedVectorType *Ty,
6201                        const DenseSet<unsigned> &ShuffledIndices,
6202                        bool NeedToShuffle) const {
6203   unsigned NumElts = Ty->getNumElements();
6204   APInt DemandedElts = APInt::getZero(NumElts);
6205   for (unsigned I = 0; I < NumElts; ++I)
6206     if (!ShuffledIndices.count(I))
6207       DemandedElts.setBit(I);
6208   InstructionCost Cost =
6209       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
6210                                     /*Extract*/ false);
6211   if (NeedToShuffle)
6212     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6213   return Cost;
6214 }
6215 
6216 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6217   // Find the type of the operands in VL.
6218   Type *ScalarTy = VL[0]->getType();
6219   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6220     ScalarTy = SI->getValueOperand()->getType();
6221   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6222   bool DuplicateNonConst = false;
6223   // Find the cost of inserting/extracting values from the vector.
6224   // Check if the same elements are inserted several times and count them as
6225   // shuffle candidates.
6226   DenseSet<unsigned> ShuffledElements;
6227   DenseSet<Value *> UniqueElements;
6228   // Iterate in reverse order to consider insert elements with the high cost.
6229   for (unsigned I = VL.size(); I > 0; --I) {
6230     unsigned Idx = I - 1;
6231     // No need to shuffle duplicates for constants.
6232     if (isConstant(VL[Idx])) {
6233       ShuffledElements.insert(Idx);
6234       continue;
6235     }
6236     if (!UniqueElements.insert(VL[Idx]).second) {
6237       DuplicateNonConst = true;
6238       ShuffledElements.insert(Idx);
6239     }
6240   }
6241   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6242 }
6243 
6244 // Perform operand reordering on the instructions in VL and return the reordered
6245 // operands in Left and Right.
6246 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6247                                              SmallVectorImpl<Value *> &Left,
6248                                              SmallVectorImpl<Value *> &Right,
6249                                              const DataLayout &DL,
6250                                              ScalarEvolution &SE,
6251                                              const BoUpSLP &R) {
6252   if (VL.empty())
6253     return;
6254   VLOperands Ops(VL, DL, SE, R);
6255   // Reorder the operands in place.
6256   Ops.reorder();
6257   Left = Ops.getVL(0);
6258   Right = Ops.getVL(1);
6259 }
6260 
6261 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6262   // Get the basic block this bundle is in. All instructions in the bundle
6263   // should be in this block.
6264   auto *Front = E->getMainOp();
6265   auto *BB = Front->getParent();
6266   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6267     auto *I = cast<Instruction>(V);
6268     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6269   }));
6270 
6271   // The last instruction in the bundle in program order.
6272   Instruction *LastInst = nullptr;
6273 
6274   // Find the last instruction. The common case should be that BB has been
6275   // scheduled, and the last instruction is VL.back(). So we start with
6276   // VL.back() and iterate over schedule data until we reach the end of the
6277   // bundle. The end of the bundle is marked by null ScheduleData.
6278   if (BlocksSchedules.count(BB)) {
6279     auto *Bundle =
6280         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6281     if (Bundle && Bundle->isPartOfBundle())
6282       for (; Bundle; Bundle = Bundle->NextInBundle)
6283         if (Bundle->OpValue == Bundle->Inst)
6284           LastInst = Bundle->Inst;
6285   }
6286 
6287   // LastInst can still be null at this point if there's either not an entry
6288   // for BB in BlocksSchedules or there's no ScheduleData available for
6289   // VL.back(). This can be the case if buildTree_rec aborts for various
6290   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6291   // size is reached, etc.). ScheduleData is initialized in the scheduling
6292   // "dry-run".
6293   //
6294   // If this happens, we can still find the last instruction by brute force. We
6295   // iterate forwards from Front (inclusive) until we either see all
6296   // instructions in the bundle or reach the end of the block. If Front is the
6297   // last instruction in program order, LastInst will be set to Front, and we
6298   // will visit all the remaining instructions in the block.
6299   //
6300   // One of the reasons we exit early from buildTree_rec is to place an upper
6301   // bound on compile-time. Thus, taking an additional compile-time hit here is
6302   // not ideal. However, this should be exceedingly rare since it requires that
6303   // we both exit early from buildTree_rec and that the bundle be out-of-order
6304   // (causing us to iterate all the way to the end of the block).
6305   if (!LastInst) {
6306     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6307     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6308       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6309         LastInst = &I;
6310       if (Bundle.empty())
6311         break;
6312     }
6313   }
6314   assert(LastInst && "Failed to find last instruction in bundle");
6315 
6316   // Set the insertion point after the last instruction in the bundle. Set the
6317   // debug location to Front.
6318   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6319   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6320 }
6321 
6322 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6323   // List of instructions/lanes from current block and/or the blocks which are
6324   // part of the current loop. These instructions will be inserted at the end to
6325   // make it possible to optimize loops and hoist invariant instructions out of
6326   // the loops body with better chances for success.
6327   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6328   SmallSet<int, 4> PostponedIndices;
6329   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6330   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6331     SmallPtrSet<BasicBlock *, 4> Visited;
6332     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6333       InsertBB = InsertBB->getSinglePredecessor();
6334     return InsertBB && InsertBB == InstBB;
6335   };
6336   for (int I = 0, E = VL.size(); I < E; ++I) {
6337     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6338       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6339            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6340           PostponedIndices.insert(I).second)
6341         PostponedInsts.emplace_back(Inst, I);
6342   }
6343 
6344   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6345     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6346     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6347     if (!InsElt)
6348       return Vec;
6349     GatherShuffleSeq.insert(InsElt);
6350     CSEBlocks.insert(InsElt->getParent());
6351     // Add to our 'need-to-extract' list.
6352     if (TreeEntry *Entry = getTreeEntry(V)) {
6353       // Find which lane we need to extract.
6354       unsigned FoundLane = Entry->findLaneForValue(V);
6355       ExternalUses.emplace_back(V, InsElt, FoundLane);
6356     }
6357     return Vec;
6358   };
6359   Value *Val0 =
6360       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6361   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6362   Value *Vec = PoisonValue::get(VecTy);
6363   SmallVector<int> NonConsts;
6364   // Insert constant values at first.
6365   for (int I = 0, E = VL.size(); I < E; ++I) {
6366     if (PostponedIndices.contains(I))
6367       continue;
6368     if (!isConstant(VL[I])) {
6369       NonConsts.push_back(I);
6370       continue;
6371     }
6372     Vec = CreateInsertElement(Vec, VL[I], I);
6373   }
6374   // Insert non-constant values.
6375   for (int I : NonConsts)
6376     Vec = CreateInsertElement(Vec, VL[I], I);
6377   // Append instructions, which are/may be part of the loop, in the end to make
6378   // it possible to hoist non-loop-based instructions.
6379   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6380     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6381 
6382   return Vec;
6383 }
6384 
6385 namespace {
6386 /// Merges shuffle masks and emits final shuffle instruction, if required.
6387 class ShuffleInstructionBuilder {
6388   IRBuilderBase &Builder;
6389   const unsigned VF = 0;
6390   bool IsFinalized = false;
6391   SmallVector<int, 4> Mask;
6392   /// Holds all of the instructions that we gathered.
6393   SetVector<Instruction *> &GatherShuffleSeq;
6394   /// A list of blocks that we are going to CSE.
6395   SetVector<BasicBlock *> &CSEBlocks;
6396 
6397 public:
6398   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6399                             SetVector<Instruction *> &GatherShuffleSeq,
6400                             SetVector<BasicBlock *> &CSEBlocks)
6401       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6402         CSEBlocks(CSEBlocks) {}
6403 
6404   /// Adds a mask, inverting it before applying.
6405   void addInversedMask(ArrayRef<unsigned> SubMask) {
6406     if (SubMask.empty())
6407       return;
6408     SmallVector<int, 4> NewMask;
6409     inversePermutation(SubMask, NewMask);
6410     addMask(NewMask);
6411   }
6412 
6413   /// Functions adds masks, merging them into  single one.
6414   void addMask(ArrayRef<unsigned> SubMask) {
6415     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6416     addMask(NewMask);
6417   }
6418 
6419   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6420 
6421   Value *finalize(Value *V) {
6422     IsFinalized = true;
6423     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6424     if (VF == ValueVF && Mask.empty())
6425       return V;
6426     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6427     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6428     addMask(NormalizedMask);
6429 
6430     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6431       return V;
6432     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6433     if (auto *I = dyn_cast<Instruction>(Vec)) {
6434       GatherShuffleSeq.insert(I);
6435       CSEBlocks.insert(I->getParent());
6436     }
6437     return Vec;
6438   }
6439 
6440   ~ShuffleInstructionBuilder() {
6441     assert((IsFinalized || Mask.empty()) &&
6442            "Shuffle construction must be finalized.");
6443   }
6444 };
6445 } // namespace
6446 
6447 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6448   unsigned VF = VL.size();
6449   InstructionsState S = getSameOpcode(VL);
6450   if (S.getOpcode()) {
6451     if (TreeEntry *E = getTreeEntry(S.OpValue))
6452       if (E->isSame(VL)) {
6453         Value *V = vectorizeTree(E);
6454         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6455           if (!E->ReuseShuffleIndices.empty()) {
6456             // Reshuffle to get only unique values.
6457             // If some of the scalars are duplicated in the vectorization tree
6458             // entry, we do not vectorize them but instead generate a mask for
6459             // the reuses. But if there are several users of the same entry,
6460             // they may have different vectorization factors. This is especially
6461             // important for PHI nodes. In this case, we need to adapt the
6462             // resulting instruction for the user vectorization factor and have
6463             // to reshuffle it again to take only unique elements of the vector.
6464             // Without this code the function incorrectly returns reduced vector
6465             // instruction with the same elements, not with the unique ones.
6466 
6467             // block:
6468             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6469             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6470             // ... (use %2)
6471             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6472             // br %block
6473             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6474             SmallSet<int, 4> UsedIdxs;
6475             int Pos = 0;
6476             int Sz = VL.size();
6477             for (int Idx : E->ReuseShuffleIndices) {
6478               if (Idx != Sz && Idx != UndefMaskElem &&
6479                   UsedIdxs.insert(Idx).second)
6480                 UniqueIdxs[Idx] = Pos;
6481               ++Pos;
6482             }
6483             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6484                                             "less than original vector size.");
6485             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6486             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6487           } else {
6488             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6489                    "Expected vectorization factor less "
6490                    "than original vector size.");
6491             SmallVector<int> UniformMask(VF, 0);
6492             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6493             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6494           }
6495           if (auto *I = dyn_cast<Instruction>(V)) {
6496             GatherShuffleSeq.insert(I);
6497             CSEBlocks.insert(I->getParent());
6498           }
6499         }
6500         return V;
6501       }
6502   }
6503 
6504   // Check that every instruction appears once in this bundle.
6505   SmallVector<int> ReuseShuffleIndicies;
6506   SmallVector<Value *> UniqueValues;
6507   if (VL.size() > 2) {
6508     DenseMap<Value *, unsigned> UniquePositions;
6509     unsigned NumValues =
6510         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6511                                     return !isa<UndefValue>(V);
6512                                   }).base());
6513     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6514     int UniqueVals = 0;
6515     for (Value *V : VL.drop_back(VL.size() - VF)) {
6516       if (isa<UndefValue>(V)) {
6517         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6518         continue;
6519       }
6520       if (isConstant(V)) {
6521         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6522         UniqueValues.emplace_back(V);
6523         continue;
6524       }
6525       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6526       ReuseShuffleIndicies.emplace_back(Res.first->second);
6527       if (Res.second) {
6528         UniqueValues.emplace_back(V);
6529         ++UniqueVals;
6530       }
6531     }
6532     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6533       // Emit pure splat vector.
6534       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6535                                   UndefMaskElem);
6536     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6537       ReuseShuffleIndicies.clear();
6538       UniqueValues.clear();
6539       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6540     }
6541     UniqueValues.append(VF - UniqueValues.size(),
6542                         PoisonValue::get(VL[0]->getType()));
6543     VL = UniqueValues;
6544   }
6545 
6546   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6547                                            CSEBlocks);
6548   Value *Vec = gather(VL);
6549   if (!ReuseShuffleIndicies.empty()) {
6550     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6551     Vec = ShuffleBuilder.finalize(Vec);
6552   }
6553   return Vec;
6554 }
6555 
6556 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6557   IRBuilder<>::InsertPointGuard Guard(Builder);
6558 
6559   if (E->VectorizedValue) {
6560     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6561     return E->VectorizedValue;
6562   }
6563 
6564   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6565   unsigned VF = E->getVectorFactor();
6566   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6567                                            CSEBlocks);
6568   if (E->State == TreeEntry::NeedToGather) {
6569     if (E->getMainOp())
6570       setInsertPointAfterBundle(E);
6571     Value *Vec;
6572     SmallVector<int> Mask;
6573     SmallVector<const TreeEntry *> Entries;
6574     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6575         isGatherShuffledEntry(E, Mask, Entries);
6576     if (Shuffle.hasValue()) {
6577       assert((Entries.size() == 1 || Entries.size() == 2) &&
6578              "Expected shuffle of 1 or 2 entries.");
6579       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6580                                         Entries.back()->VectorizedValue, Mask);
6581       if (auto *I = dyn_cast<Instruction>(Vec)) {
6582         GatherShuffleSeq.insert(I);
6583         CSEBlocks.insert(I->getParent());
6584       }
6585     } else {
6586       Vec = gather(E->Scalars);
6587     }
6588     if (NeedToShuffleReuses) {
6589       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6590       Vec = ShuffleBuilder.finalize(Vec);
6591     }
6592     E->VectorizedValue = Vec;
6593     return Vec;
6594   }
6595 
6596   assert((E->State == TreeEntry::Vectorize ||
6597           E->State == TreeEntry::ScatterVectorize) &&
6598          "Unhandled state");
6599   unsigned ShuffleOrOp =
6600       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6601   Instruction *VL0 = E->getMainOp();
6602   Type *ScalarTy = VL0->getType();
6603   if (auto *Store = dyn_cast<StoreInst>(VL0))
6604     ScalarTy = Store->getValueOperand()->getType();
6605   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6606     ScalarTy = IE->getOperand(1)->getType();
6607   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6608   switch (ShuffleOrOp) {
6609     case Instruction::PHI: {
6610       assert(
6611           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6612           "PHI reordering is free.");
6613       auto *PH = cast<PHINode>(VL0);
6614       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6615       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6616       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6617       Value *V = NewPhi;
6618       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6619       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6620       V = ShuffleBuilder.finalize(V);
6621 
6622       E->VectorizedValue = V;
6623 
6624       // PHINodes may have multiple entries from the same block. We want to
6625       // visit every block once.
6626       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6627 
6628       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6629         ValueList Operands;
6630         BasicBlock *IBB = PH->getIncomingBlock(i);
6631 
6632         if (!VisitedBBs.insert(IBB).second) {
6633           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6634           continue;
6635         }
6636 
6637         Builder.SetInsertPoint(IBB->getTerminator());
6638         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6639         Value *Vec = vectorizeTree(E->getOperand(i));
6640         NewPhi->addIncoming(Vec, IBB);
6641       }
6642 
6643       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6644              "Invalid number of incoming values");
6645       return V;
6646     }
6647 
6648     case Instruction::ExtractElement: {
6649       Value *V = E->getSingleOperand(0);
6650       Builder.SetInsertPoint(VL0);
6651       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6652       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6653       V = ShuffleBuilder.finalize(V);
6654       E->VectorizedValue = V;
6655       return V;
6656     }
6657     case Instruction::ExtractValue: {
6658       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6659       Builder.SetInsertPoint(LI);
6660       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6661       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6662       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6663       Value *NewV = propagateMetadata(V, E->Scalars);
6664       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6665       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6666       NewV = ShuffleBuilder.finalize(NewV);
6667       E->VectorizedValue = NewV;
6668       return NewV;
6669     }
6670     case Instruction::InsertElement: {
6671       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6672       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6673       Value *V = vectorizeTree(E->getOperand(1));
6674 
6675       // Create InsertVector shuffle if necessary
6676       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6677         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6678       }));
6679       const unsigned NumElts =
6680           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6681       const unsigned NumScalars = E->Scalars.size();
6682 
6683       unsigned Offset = *getInsertIndex(VL0, 0);
6684       assert(Offset < NumElts && "Failed to find vector index offset");
6685 
6686       // Create shuffle to resize vector
6687       SmallVector<int> Mask;
6688       if (!E->ReorderIndices.empty()) {
6689         inversePermutation(E->ReorderIndices, Mask);
6690         Mask.append(NumElts - NumScalars, UndefMaskElem);
6691       } else {
6692         Mask.assign(NumElts, UndefMaskElem);
6693         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6694       }
6695       // Create InsertVector shuffle if necessary
6696       bool IsIdentity = true;
6697       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6698       Mask.swap(PrevMask);
6699       for (unsigned I = 0; I < NumScalars; ++I) {
6700         Value *Scalar = E->Scalars[PrevMask[I]];
6701         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6702         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6703           continue;
6704         IsIdentity &= *InsertIdx - Offset == I;
6705         Mask[*InsertIdx - Offset] = I;
6706       }
6707       if (!IsIdentity || NumElts != NumScalars) {
6708         V = Builder.CreateShuffleVector(V, Mask);
6709         if (auto *I = dyn_cast<Instruction>(V)) {
6710           GatherShuffleSeq.insert(I);
6711           CSEBlocks.insert(I->getParent());
6712         }
6713       }
6714 
6715       if ((!IsIdentity || Offset != 0 ||
6716            !isUndefVector(FirstInsert->getOperand(0))) &&
6717           NumElts != NumScalars) {
6718         SmallVector<int> InsertMask(NumElts);
6719         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6720         for (unsigned I = 0; I < NumElts; I++) {
6721           if (Mask[I] != UndefMaskElem)
6722             InsertMask[Offset + I] = NumElts + I;
6723         }
6724 
6725         V = Builder.CreateShuffleVector(
6726             FirstInsert->getOperand(0), V, InsertMask,
6727             cast<Instruction>(E->Scalars.back())->getName());
6728         if (auto *I = dyn_cast<Instruction>(V)) {
6729           GatherShuffleSeq.insert(I);
6730           CSEBlocks.insert(I->getParent());
6731         }
6732       }
6733 
6734       ++NumVectorInstructions;
6735       E->VectorizedValue = V;
6736       return V;
6737     }
6738     case Instruction::ZExt:
6739     case Instruction::SExt:
6740     case Instruction::FPToUI:
6741     case Instruction::FPToSI:
6742     case Instruction::FPExt:
6743     case Instruction::PtrToInt:
6744     case Instruction::IntToPtr:
6745     case Instruction::SIToFP:
6746     case Instruction::UIToFP:
6747     case Instruction::Trunc:
6748     case Instruction::FPTrunc:
6749     case Instruction::BitCast: {
6750       setInsertPointAfterBundle(E);
6751 
6752       Value *InVec = vectorizeTree(E->getOperand(0));
6753 
6754       if (E->VectorizedValue) {
6755         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6756         return E->VectorizedValue;
6757       }
6758 
6759       auto *CI = cast<CastInst>(VL0);
6760       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6761       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6762       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6763       V = ShuffleBuilder.finalize(V);
6764 
6765       E->VectorizedValue = V;
6766       ++NumVectorInstructions;
6767       return V;
6768     }
6769     case Instruction::FCmp:
6770     case Instruction::ICmp: {
6771       setInsertPointAfterBundle(E);
6772 
6773       Value *L = vectorizeTree(E->getOperand(0));
6774       Value *R = vectorizeTree(E->getOperand(1));
6775 
6776       if (E->VectorizedValue) {
6777         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6778         return E->VectorizedValue;
6779       }
6780 
6781       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6782       Value *V = Builder.CreateCmp(P0, L, R);
6783       propagateIRFlags(V, E->Scalars, VL0);
6784       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6785       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6786       V = ShuffleBuilder.finalize(V);
6787 
6788       E->VectorizedValue = V;
6789       ++NumVectorInstructions;
6790       return V;
6791     }
6792     case Instruction::Select: {
6793       setInsertPointAfterBundle(E);
6794 
6795       Value *Cond = vectorizeTree(E->getOperand(0));
6796       Value *True = vectorizeTree(E->getOperand(1));
6797       Value *False = vectorizeTree(E->getOperand(2));
6798 
6799       if (E->VectorizedValue) {
6800         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6801         return E->VectorizedValue;
6802       }
6803 
6804       Value *V = Builder.CreateSelect(Cond, True, False);
6805       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6806       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6807       V = ShuffleBuilder.finalize(V);
6808 
6809       E->VectorizedValue = V;
6810       ++NumVectorInstructions;
6811       return V;
6812     }
6813     case Instruction::FNeg: {
6814       setInsertPointAfterBundle(E);
6815 
6816       Value *Op = vectorizeTree(E->getOperand(0));
6817 
6818       if (E->VectorizedValue) {
6819         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6820         return E->VectorizedValue;
6821       }
6822 
6823       Value *V = Builder.CreateUnOp(
6824           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6825       propagateIRFlags(V, E->Scalars, VL0);
6826       if (auto *I = dyn_cast<Instruction>(V))
6827         V = propagateMetadata(I, E->Scalars);
6828 
6829       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6830       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6831       V = ShuffleBuilder.finalize(V);
6832 
6833       E->VectorizedValue = V;
6834       ++NumVectorInstructions;
6835 
6836       return V;
6837     }
6838     case Instruction::Add:
6839     case Instruction::FAdd:
6840     case Instruction::Sub:
6841     case Instruction::FSub:
6842     case Instruction::Mul:
6843     case Instruction::FMul:
6844     case Instruction::UDiv:
6845     case Instruction::SDiv:
6846     case Instruction::FDiv:
6847     case Instruction::URem:
6848     case Instruction::SRem:
6849     case Instruction::FRem:
6850     case Instruction::Shl:
6851     case Instruction::LShr:
6852     case Instruction::AShr:
6853     case Instruction::And:
6854     case Instruction::Or:
6855     case Instruction::Xor: {
6856       setInsertPointAfterBundle(E);
6857 
6858       Value *LHS = vectorizeTree(E->getOperand(0));
6859       Value *RHS = vectorizeTree(E->getOperand(1));
6860 
6861       if (E->VectorizedValue) {
6862         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6863         return E->VectorizedValue;
6864       }
6865 
6866       Value *V = Builder.CreateBinOp(
6867           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6868           RHS);
6869       propagateIRFlags(V, E->Scalars, VL0);
6870       if (auto *I = dyn_cast<Instruction>(V))
6871         V = propagateMetadata(I, E->Scalars);
6872 
6873       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6874       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6875       V = ShuffleBuilder.finalize(V);
6876 
6877       E->VectorizedValue = V;
6878       ++NumVectorInstructions;
6879 
6880       return V;
6881     }
6882     case Instruction::Load: {
6883       // Loads are inserted at the head of the tree because we don't want to
6884       // sink them all the way down past store instructions.
6885       setInsertPointAfterBundle(E);
6886 
6887       LoadInst *LI = cast<LoadInst>(VL0);
6888       Instruction *NewLI;
6889       unsigned AS = LI->getPointerAddressSpace();
6890       Value *PO = LI->getPointerOperand();
6891       if (E->State == TreeEntry::Vectorize) {
6892 
6893         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6894 
6895         // The pointer operand uses an in-tree scalar so we add the new BitCast
6896         // to ExternalUses list to make sure that an extract will be generated
6897         // in the future.
6898         if (TreeEntry *Entry = getTreeEntry(PO)) {
6899           // Find which lane we need to extract.
6900           unsigned FoundLane = Entry->findLaneForValue(PO);
6901           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6902         }
6903 
6904         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6905       } else {
6906         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6907         Value *VecPtr = vectorizeTree(E->getOperand(0));
6908         // Use the minimum alignment of the gathered loads.
6909         Align CommonAlignment = LI->getAlign();
6910         for (Value *V : E->Scalars)
6911           CommonAlignment =
6912               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6913         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6914       }
6915       Value *V = propagateMetadata(NewLI, E->Scalars);
6916 
6917       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6918       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6919       V = ShuffleBuilder.finalize(V);
6920       E->VectorizedValue = V;
6921       ++NumVectorInstructions;
6922       return V;
6923     }
6924     case Instruction::Store: {
6925       auto *SI = cast<StoreInst>(VL0);
6926       unsigned AS = SI->getPointerAddressSpace();
6927 
6928       setInsertPointAfterBundle(E);
6929 
6930       Value *VecValue = vectorizeTree(E->getOperand(0));
6931       ShuffleBuilder.addMask(E->ReorderIndices);
6932       VecValue = ShuffleBuilder.finalize(VecValue);
6933 
6934       Value *ScalarPtr = SI->getPointerOperand();
6935       Value *VecPtr = Builder.CreateBitCast(
6936           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6937       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6938                                                  SI->getAlign());
6939 
6940       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6941       // ExternalUses to make sure that an extract will be generated in the
6942       // future.
6943       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6944         // Find which lane we need to extract.
6945         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6946         ExternalUses.push_back(
6947             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6948       }
6949 
6950       Value *V = propagateMetadata(ST, E->Scalars);
6951 
6952       E->VectorizedValue = V;
6953       ++NumVectorInstructions;
6954       return V;
6955     }
6956     case Instruction::GetElementPtr: {
6957       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6958       setInsertPointAfterBundle(E);
6959 
6960       Value *Op0 = vectorizeTree(E->getOperand(0));
6961 
6962       SmallVector<Value *> OpVecs;
6963       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6964         Value *OpVec = vectorizeTree(E->getOperand(J));
6965         OpVecs.push_back(OpVec);
6966       }
6967 
6968       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6969       if (Instruction *I = dyn_cast<Instruction>(V))
6970         V = propagateMetadata(I, E->Scalars);
6971 
6972       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6973       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6974       V = ShuffleBuilder.finalize(V);
6975 
6976       E->VectorizedValue = V;
6977       ++NumVectorInstructions;
6978 
6979       return V;
6980     }
6981     case Instruction::Call: {
6982       CallInst *CI = cast<CallInst>(VL0);
6983       setInsertPointAfterBundle(E);
6984 
6985       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6986       if (Function *FI = CI->getCalledFunction())
6987         IID = FI->getIntrinsicID();
6988 
6989       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6990 
6991       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6992       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6993                           VecCallCosts.first <= VecCallCosts.second;
6994 
6995       Value *ScalarArg = nullptr;
6996       std::vector<Value *> OpVecs;
6997       SmallVector<Type *, 2> TysForDecl =
6998           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6999       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7000         ValueList OpVL;
7001         // Some intrinsics have scalar arguments. This argument should not be
7002         // vectorized.
7003         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7004           CallInst *CEI = cast<CallInst>(VL0);
7005           ScalarArg = CEI->getArgOperand(j);
7006           OpVecs.push_back(CEI->getArgOperand(j));
7007           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7008             TysForDecl.push_back(ScalarArg->getType());
7009           continue;
7010         }
7011 
7012         Value *OpVec = vectorizeTree(E->getOperand(j));
7013         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7014         OpVecs.push_back(OpVec);
7015       }
7016 
7017       Function *CF;
7018       if (!UseIntrinsic) {
7019         VFShape Shape =
7020             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7021                                   VecTy->getNumElements())),
7022                          false /*HasGlobalPred*/);
7023         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7024       } else {
7025         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7026       }
7027 
7028       SmallVector<OperandBundleDef, 1> OpBundles;
7029       CI->getOperandBundlesAsDefs(OpBundles);
7030       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7031 
7032       // The scalar argument uses an in-tree scalar so we add the new vectorized
7033       // call to ExternalUses list to make sure that an extract will be
7034       // generated in the future.
7035       if (ScalarArg) {
7036         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7037           // Find which lane we need to extract.
7038           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7039           ExternalUses.push_back(
7040               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7041         }
7042       }
7043 
7044       propagateIRFlags(V, E->Scalars, VL0);
7045       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7046       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7047       V = ShuffleBuilder.finalize(V);
7048 
7049       E->VectorizedValue = V;
7050       ++NumVectorInstructions;
7051       return V;
7052     }
7053     case Instruction::ShuffleVector: {
7054       assert(E->isAltShuffle() &&
7055              ((Instruction::isBinaryOp(E->getOpcode()) &&
7056                Instruction::isBinaryOp(E->getAltOpcode())) ||
7057               (Instruction::isCast(E->getOpcode()) &&
7058                Instruction::isCast(E->getAltOpcode())) ||
7059               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7060              "Invalid Shuffle Vector Operand");
7061 
7062       Value *LHS = nullptr, *RHS = nullptr;
7063       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7064         setInsertPointAfterBundle(E);
7065         LHS = vectorizeTree(E->getOperand(0));
7066         RHS = vectorizeTree(E->getOperand(1));
7067       } else {
7068         setInsertPointAfterBundle(E);
7069         LHS = vectorizeTree(E->getOperand(0));
7070       }
7071 
7072       if (E->VectorizedValue) {
7073         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7074         return E->VectorizedValue;
7075       }
7076 
7077       Value *V0, *V1;
7078       if (Instruction::isBinaryOp(E->getOpcode())) {
7079         V0 = Builder.CreateBinOp(
7080             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7081         V1 = Builder.CreateBinOp(
7082             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7083       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7084         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7085         auto *AltCI = cast<CmpInst>(E->getAltOp());
7086         CmpInst::Predicate AltPred = AltCI->getPredicate();
7087         unsigned AltIdx =
7088             std::distance(E->Scalars.begin(), find(E->Scalars, AltCI));
7089         if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx])
7090           AltPred = CmpInst::getSwappedPredicate(AltPred);
7091         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7092       } else {
7093         V0 = Builder.CreateCast(
7094             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7095         V1 = Builder.CreateCast(
7096             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7097       }
7098       // Add V0 and V1 to later analysis to try to find and remove matching
7099       // instruction, if any.
7100       for (Value *V : {V0, V1}) {
7101         if (auto *I = dyn_cast<Instruction>(V)) {
7102           GatherShuffleSeq.insert(I);
7103           CSEBlocks.insert(I->getParent());
7104         }
7105       }
7106 
7107       // Create shuffle to take alternate operations from the vector.
7108       // Also, gather up main and alt scalar ops to propagate IR flags to
7109       // each vector operation.
7110       ValueList OpScalars, AltScalars;
7111       SmallVector<int> Mask;
7112       buildSuffleEntryMask(
7113           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7114           [E](Instruction *I) {
7115             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7116             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
7117               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
7118               auto *CI = cast<CmpInst>(I);
7119               CmpInst::Predicate P0 = CI0->getPredicate();
7120               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
7121               assert(P0 != AltP0 &&
7122                      "Expected different main/alternate predicates.");
7123               CmpInst::Predicate AltP0Swapped =
7124                   CmpInst::getSwappedPredicate(AltP0);
7125               CmpInst::Predicate CurrentPred = CI->getPredicate();
7126               if (P0 == AltP0Swapped)
7127                 return (P0 == CurrentPred &&
7128                         !areCompatibleCmpOps(
7129                             CI0->getOperand(0), CI0->getOperand(1),
7130                             CI->getOperand(0), CI->getOperand(1))) ||
7131                        (AltP0 == CurrentPred &&
7132                         !areCompatibleCmpOps(
7133                             CI0->getOperand(0), CI0->getOperand(1),
7134                             CI->getOperand(1), CI->getOperand(0)));
7135               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
7136             }
7137             return I->getOpcode() == E->getAltOpcode();
7138           },
7139           Mask, &OpScalars, &AltScalars);
7140 
7141       propagateIRFlags(V0, OpScalars);
7142       propagateIRFlags(V1, AltScalars);
7143 
7144       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7145       if (auto *I = dyn_cast<Instruction>(V)) {
7146         V = propagateMetadata(I, E->Scalars);
7147         GatherShuffleSeq.insert(I);
7148         CSEBlocks.insert(I->getParent());
7149       }
7150       V = ShuffleBuilder.finalize(V);
7151 
7152       E->VectorizedValue = V;
7153       ++NumVectorInstructions;
7154 
7155       return V;
7156     }
7157     default:
7158     llvm_unreachable("unknown inst");
7159   }
7160   return nullptr;
7161 }
7162 
7163 Value *BoUpSLP::vectorizeTree() {
7164   ExtraValueToDebugLocsMap ExternallyUsedValues;
7165   return vectorizeTree(ExternallyUsedValues);
7166 }
7167 
7168 Value *
7169 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7170   // All blocks must be scheduled before any instructions are inserted.
7171   for (auto &BSIter : BlocksSchedules) {
7172     scheduleBlock(BSIter.second.get());
7173   }
7174 
7175   Builder.SetInsertPoint(&F->getEntryBlock().front());
7176   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7177 
7178   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7179   // vectorized root. InstCombine will then rewrite the entire expression. We
7180   // sign extend the extracted values below.
7181   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7182   if (MinBWs.count(ScalarRoot)) {
7183     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7184       // If current instr is a phi and not the last phi, insert it after the
7185       // last phi node.
7186       if (isa<PHINode>(I))
7187         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7188       else
7189         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7190     }
7191     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7192     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7193     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7194     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7195     VectorizableTree[0]->VectorizedValue = Trunc;
7196   }
7197 
7198   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7199                     << " values .\n");
7200 
7201   // Extract all of the elements with the external uses.
7202   for (const auto &ExternalUse : ExternalUses) {
7203     Value *Scalar = ExternalUse.Scalar;
7204     llvm::User *User = ExternalUse.User;
7205 
7206     // Skip users that we already RAUW. This happens when one instruction
7207     // has multiple uses of the same value.
7208     if (User && !is_contained(Scalar->users(), User))
7209       continue;
7210     TreeEntry *E = getTreeEntry(Scalar);
7211     assert(E && "Invalid scalar");
7212     assert(E->State != TreeEntry::NeedToGather &&
7213            "Extracting from a gather list");
7214 
7215     Value *Vec = E->VectorizedValue;
7216     assert(Vec && "Can't find vectorizable value");
7217 
7218     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7219     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7220       if (Scalar->getType() != Vec->getType()) {
7221         Value *Ex;
7222         // "Reuse" the existing extract to improve final codegen.
7223         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7224           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7225                                             ES->getOperand(1));
7226         } else {
7227           Ex = Builder.CreateExtractElement(Vec, Lane);
7228         }
7229         // If necessary, sign-extend or zero-extend ScalarRoot
7230         // to the larger type.
7231         if (!MinBWs.count(ScalarRoot))
7232           return Ex;
7233         if (MinBWs[ScalarRoot].second)
7234           return Builder.CreateSExt(Ex, Scalar->getType());
7235         return Builder.CreateZExt(Ex, Scalar->getType());
7236       }
7237       assert(isa<FixedVectorType>(Scalar->getType()) &&
7238              isa<InsertElementInst>(Scalar) &&
7239              "In-tree scalar of vector type is not insertelement?");
7240       return Vec;
7241     };
7242     // If User == nullptr, the Scalar is used as extra arg. Generate
7243     // ExtractElement instruction and update the record for this scalar in
7244     // ExternallyUsedValues.
7245     if (!User) {
7246       assert(ExternallyUsedValues.count(Scalar) &&
7247              "Scalar with nullptr as an external user must be registered in "
7248              "ExternallyUsedValues map");
7249       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7250         Builder.SetInsertPoint(VecI->getParent(),
7251                                std::next(VecI->getIterator()));
7252       } else {
7253         Builder.SetInsertPoint(&F->getEntryBlock().front());
7254       }
7255       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7256       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7257       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7258       auto It = ExternallyUsedValues.find(Scalar);
7259       assert(It != ExternallyUsedValues.end() &&
7260              "Externally used scalar is not found in ExternallyUsedValues");
7261       NewInstLocs.append(It->second);
7262       ExternallyUsedValues.erase(Scalar);
7263       // Required to update internally referenced instructions.
7264       Scalar->replaceAllUsesWith(NewInst);
7265       continue;
7266     }
7267 
7268     // Generate extracts for out-of-tree users.
7269     // Find the insertion point for the extractelement lane.
7270     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7271       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7272         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7273           if (PH->getIncomingValue(i) == Scalar) {
7274             Instruction *IncomingTerminator =
7275                 PH->getIncomingBlock(i)->getTerminator();
7276             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7277               Builder.SetInsertPoint(VecI->getParent(),
7278                                      std::next(VecI->getIterator()));
7279             } else {
7280               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7281             }
7282             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7283             CSEBlocks.insert(PH->getIncomingBlock(i));
7284             PH->setOperand(i, NewInst);
7285           }
7286         }
7287       } else {
7288         Builder.SetInsertPoint(cast<Instruction>(User));
7289         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7290         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7291         User->replaceUsesOfWith(Scalar, NewInst);
7292       }
7293     } else {
7294       Builder.SetInsertPoint(&F->getEntryBlock().front());
7295       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7296       CSEBlocks.insert(&F->getEntryBlock());
7297       User->replaceUsesOfWith(Scalar, NewInst);
7298     }
7299 
7300     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7301   }
7302 
7303   // For each vectorized value:
7304   for (auto &TEPtr : VectorizableTree) {
7305     TreeEntry *Entry = TEPtr.get();
7306 
7307     // No need to handle users of gathered values.
7308     if (Entry->State == TreeEntry::NeedToGather)
7309       continue;
7310 
7311     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7312 
7313     // For each lane:
7314     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7315       Value *Scalar = Entry->Scalars[Lane];
7316 
7317 #ifndef NDEBUG
7318       Type *Ty = Scalar->getType();
7319       if (!Ty->isVoidTy()) {
7320         for (User *U : Scalar->users()) {
7321           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7322 
7323           // It is legal to delete users in the ignorelist.
7324           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7325                   (isa_and_nonnull<Instruction>(U) &&
7326                    isDeleted(cast<Instruction>(U)))) &&
7327                  "Deleting out-of-tree value");
7328         }
7329       }
7330 #endif
7331       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7332       eraseInstruction(cast<Instruction>(Scalar));
7333     }
7334   }
7335 
7336   Builder.ClearInsertionPoint();
7337   InstrElementSize.clear();
7338 
7339   return VectorizableTree[0]->VectorizedValue;
7340 }
7341 
7342 void BoUpSLP::optimizeGatherSequence() {
7343   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7344                     << " gather sequences instructions.\n");
7345   // LICM InsertElementInst sequences.
7346   for (Instruction *I : GatherShuffleSeq) {
7347     if (isDeleted(I))
7348       continue;
7349 
7350     // Check if this block is inside a loop.
7351     Loop *L = LI->getLoopFor(I->getParent());
7352     if (!L)
7353       continue;
7354 
7355     // Check if it has a preheader.
7356     BasicBlock *PreHeader = L->getLoopPreheader();
7357     if (!PreHeader)
7358       continue;
7359 
7360     // If the vector or the element that we insert into it are
7361     // instructions that are defined in this basic block then we can't
7362     // hoist this instruction.
7363     if (any_of(I->operands(), [L](Value *V) {
7364           auto *OpI = dyn_cast<Instruction>(V);
7365           return OpI && L->contains(OpI);
7366         }))
7367       continue;
7368 
7369     // We can hoist this instruction. Move it to the pre-header.
7370     I->moveBefore(PreHeader->getTerminator());
7371   }
7372 
7373   // Make a list of all reachable blocks in our CSE queue.
7374   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7375   CSEWorkList.reserve(CSEBlocks.size());
7376   for (BasicBlock *BB : CSEBlocks)
7377     if (DomTreeNode *N = DT->getNode(BB)) {
7378       assert(DT->isReachableFromEntry(N));
7379       CSEWorkList.push_back(N);
7380     }
7381 
7382   // Sort blocks by domination. This ensures we visit a block after all blocks
7383   // dominating it are visited.
7384   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7385     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7386            "Different nodes should have different DFS numbers");
7387     return A->getDFSNumIn() < B->getDFSNumIn();
7388   });
7389 
7390   // Less defined shuffles can be replaced by the more defined copies.
7391   // Between two shuffles one is less defined if it has the same vector operands
7392   // and its mask indeces are the same as in the first one or undefs. E.g.
7393   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7394   // poison, <0, 0, 0, 0>.
7395   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7396                                            SmallVectorImpl<int> &NewMask) {
7397     if (I1->getType() != I2->getType())
7398       return false;
7399     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7400     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7401     if (!SI1 || !SI2)
7402       return I1->isIdenticalTo(I2);
7403     if (SI1->isIdenticalTo(SI2))
7404       return true;
7405     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7406       if (SI1->getOperand(I) != SI2->getOperand(I))
7407         return false;
7408     // Check if the second instruction is more defined than the first one.
7409     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7410     ArrayRef<int> SM1 = SI1->getShuffleMask();
7411     // Count trailing undefs in the mask to check the final number of used
7412     // registers.
7413     unsigned LastUndefsCnt = 0;
7414     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7415       if (SM1[I] == UndefMaskElem)
7416         ++LastUndefsCnt;
7417       else
7418         LastUndefsCnt = 0;
7419       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7420           NewMask[I] != SM1[I])
7421         return false;
7422       if (NewMask[I] == UndefMaskElem)
7423         NewMask[I] = SM1[I];
7424     }
7425     // Check if the last undefs actually change the final number of used vector
7426     // registers.
7427     return SM1.size() - LastUndefsCnt > 1 &&
7428            TTI->getNumberOfParts(SI1->getType()) ==
7429                TTI->getNumberOfParts(
7430                    FixedVectorType::get(SI1->getType()->getElementType(),
7431                                         SM1.size() - LastUndefsCnt));
7432   };
7433   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7434   // instructions. TODO: We can further optimize this scan if we split the
7435   // instructions into different buckets based on the insert lane.
7436   SmallVector<Instruction *, 16> Visited;
7437   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7438     assert(*I &&
7439            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7440            "Worklist not sorted properly!");
7441     BasicBlock *BB = (*I)->getBlock();
7442     // For all instructions in blocks containing gather sequences:
7443     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7444       if (isDeleted(&In))
7445         continue;
7446       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7447           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7448         continue;
7449 
7450       // Check if we can replace this instruction with any of the
7451       // visited instructions.
7452       bool Replaced = false;
7453       for (Instruction *&V : Visited) {
7454         SmallVector<int> NewMask;
7455         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7456             DT->dominates(V->getParent(), In.getParent())) {
7457           In.replaceAllUsesWith(V);
7458           eraseInstruction(&In);
7459           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7460             if (!NewMask.empty())
7461               SI->setShuffleMask(NewMask);
7462           Replaced = true;
7463           break;
7464         }
7465         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7466             GatherShuffleSeq.contains(V) &&
7467             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7468             DT->dominates(In.getParent(), V->getParent())) {
7469           In.moveAfter(V);
7470           V->replaceAllUsesWith(&In);
7471           eraseInstruction(V);
7472           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7473             if (!NewMask.empty())
7474               SI->setShuffleMask(NewMask);
7475           V = &In;
7476           Replaced = true;
7477           break;
7478         }
7479       }
7480       if (!Replaced) {
7481         assert(!is_contained(Visited, &In));
7482         Visited.push_back(&In);
7483       }
7484     }
7485   }
7486   CSEBlocks.clear();
7487   GatherShuffleSeq.clear();
7488 }
7489 
7490 BoUpSLP::ScheduleData *
7491 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7492   ScheduleData *Bundle = nullptr;
7493   ScheduleData *PrevInBundle = nullptr;
7494   for (Value *V : VL) {
7495     ScheduleData *BundleMember = getScheduleData(V);
7496     assert(BundleMember &&
7497            "no ScheduleData for bundle member "
7498            "(maybe not in same basic block)");
7499     assert(BundleMember->isSchedulingEntity() &&
7500            "bundle member already part of other bundle");
7501     if (PrevInBundle) {
7502       PrevInBundle->NextInBundle = BundleMember;
7503     } else {
7504       Bundle = BundleMember;
7505     }
7506     BundleMember->UnscheduledDepsInBundle = 0;
7507     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7508 
7509     // Group the instructions to a bundle.
7510     BundleMember->FirstInBundle = Bundle;
7511     PrevInBundle = BundleMember;
7512   }
7513   assert(Bundle && "Failed to find schedule bundle");
7514   return Bundle;
7515 }
7516 
7517 // Groups the instructions to a bundle (which is then a single scheduling entity)
7518 // and schedules instructions until the bundle gets ready.
7519 Optional<BoUpSLP::ScheduleData *>
7520 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7521                                             const InstructionsState &S) {
7522   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7523   // instructions.
7524   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7525     return nullptr;
7526 
7527   // Initialize the instruction bundle.
7528   Instruction *OldScheduleEnd = ScheduleEnd;
7529   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7530 
7531   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7532                                                          ScheduleData *Bundle) {
7533     // The scheduling region got new instructions at the lower end (or it is a
7534     // new region for the first bundle). This makes it necessary to
7535     // recalculate all dependencies.
7536     // It is seldom that this needs to be done a second time after adding the
7537     // initial bundle to the region.
7538     if (ScheduleEnd != OldScheduleEnd) {
7539       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7540         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7541       ReSchedule = true;
7542     }
7543     if (Bundle) {
7544       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7545                         << " in block " << BB->getName() << "\n");
7546       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7547     }
7548 
7549     if (ReSchedule) {
7550       resetSchedule();
7551       initialFillReadyList(ReadyInsts);
7552     }
7553 
7554     // Now try to schedule the new bundle or (if no bundle) just calculate
7555     // dependencies. As soon as the bundle is "ready" it means that there are no
7556     // cyclic dependencies and we can schedule it. Note that's important that we
7557     // don't "schedule" the bundle yet (see cancelScheduling).
7558     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7559            !ReadyInsts.empty()) {
7560       ScheduleData *Picked = ReadyInsts.pop_back_val();
7561       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7562              "must be ready to schedule");
7563       schedule(Picked, ReadyInsts);
7564     }
7565   };
7566 
7567   // Make sure that the scheduling region contains all
7568   // instructions of the bundle.
7569   for (Value *V : VL) {
7570     if (!extendSchedulingRegion(V, S)) {
7571       // If the scheduling region got new instructions at the lower end (or it
7572       // is a new region for the first bundle). This makes it necessary to
7573       // recalculate all dependencies.
7574       // Otherwise the compiler may crash trying to incorrectly calculate
7575       // dependencies and emit instruction in the wrong order at the actual
7576       // scheduling.
7577       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7578       return None;
7579     }
7580   }
7581 
7582   bool ReSchedule = false;
7583   for (Value *V : VL) {
7584     ScheduleData *BundleMember = getScheduleData(V);
7585     assert(BundleMember &&
7586            "no ScheduleData for bundle member (maybe not in same basic block)");
7587 
7588     // Make sure we don't leave the pieces of the bundle in the ready list when
7589     // whole bundle might not be ready.
7590     ReadyInsts.remove(BundleMember);
7591 
7592     if (!BundleMember->IsScheduled)
7593       continue;
7594     // A bundle member was scheduled as single instruction before and now
7595     // needs to be scheduled as part of the bundle. We just get rid of the
7596     // existing schedule.
7597     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7598                       << " was already scheduled\n");
7599     ReSchedule = true;
7600   }
7601 
7602   auto *Bundle = buildBundle(VL);
7603   TryScheduleBundleImpl(ReSchedule, Bundle);
7604   if (!Bundle->isReady()) {
7605     cancelScheduling(VL, S.OpValue);
7606     return None;
7607   }
7608   return Bundle;
7609 }
7610 
7611 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7612                                                 Value *OpValue) {
7613   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7614     return;
7615 
7616   ScheduleData *Bundle = getScheduleData(OpValue);
7617   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7618   assert(!Bundle->IsScheduled &&
7619          "Can't cancel bundle which is already scheduled");
7620   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7621          "tried to unbundle something which is not a bundle");
7622 
7623   // Remove the bundle from the ready list.
7624   if (Bundle->isReady())
7625     ReadyInsts.remove(Bundle);
7626 
7627   // Un-bundle: make single instructions out of the bundle.
7628   ScheduleData *BundleMember = Bundle;
7629   while (BundleMember) {
7630     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7631     BundleMember->FirstInBundle = BundleMember;
7632     ScheduleData *Next = BundleMember->NextInBundle;
7633     BundleMember->NextInBundle = nullptr;
7634     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7635     if (BundleMember->UnscheduledDepsInBundle == 0) {
7636       ReadyInsts.insert(BundleMember);
7637     }
7638     BundleMember = Next;
7639   }
7640 }
7641 
7642 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7643   // Allocate a new ScheduleData for the instruction.
7644   if (ChunkPos >= ChunkSize) {
7645     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7646     ChunkPos = 0;
7647   }
7648   return &(ScheduleDataChunks.back()[ChunkPos++]);
7649 }
7650 
7651 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7652                                                       const InstructionsState &S) {
7653   if (getScheduleData(V, isOneOf(S, V)))
7654     return true;
7655   Instruction *I = dyn_cast<Instruction>(V);
7656   assert(I && "bundle member must be an instruction");
7657   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7658          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7659          "be scheduled");
7660   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7661     ScheduleData *ISD = getScheduleData(I);
7662     if (!ISD)
7663       return false;
7664     assert(isInSchedulingRegion(ISD) &&
7665            "ScheduleData not in scheduling region");
7666     ScheduleData *SD = allocateScheduleDataChunks();
7667     SD->Inst = I;
7668     SD->init(SchedulingRegionID, S.OpValue);
7669     ExtraScheduleDataMap[I][S.OpValue] = SD;
7670     return true;
7671   };
7672   if (CheckSheduleForI(I))
7673     return true;
7674   if (!ScheduleStart) {
7675     // It's the first instruction in the new region.
7676     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7677     ScheduleStart = I;
7678     ScheduleEnd = I->getNextNode();
7679     if (isOneOf(S, I) != I)
7680       CheckSheduleForI(I);
7681     assert(ScheduleEnd && "tried to vectorize a terminator?");
7682     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7683     return true;
7684   }
7685   // Search up and down at the same time, because we don't know if the new
7686   // instruction is above or below the existing scheduling region.
7687   BasicBlock::reverse_iterator UpIter =
7688       ++ScheduleStart->getIterator().getReverse();
7689   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7690   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7691   BasicBlock::iterator LowerEnd = BB->end();
7692   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7693          &*DownIter != I) {
7694     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7695       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7696       return false;
7697     }
7698 
7699     ++UpIter;
7700     ++DownIter;
7701   }
7702   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7703     assert(I->getParent() == ScheduleStart->getParent() &&
7704            "Instruction is in wrong basic block.");
7705     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7706     ScheduleStart = I;
7707     if (isOneOf(S, I) != I)
7708       CheckSheduleForI(I);
7709     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7710                       << "\n");
7711     return true;
7712   }
7713   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7714          "Expected to reach top of the basic block or instruction down the "
7715          "lower end.");
7716   assert(I->getParent() == ScheduleEnd->getParent() &&
7717          "Instruction is in wrong basic block.");
7718   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7719                    nullptr);
7720   ScheduleEnd = I->getNextNode();
7721   if (isOneOf(S, I) != I)
7722     CheckSheduleForI(I);
7723   assert(ScheduleEnd && "tried to vectorize a terminator?");
7724   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7725   return true;
7726 }
7727 
7728 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7729                                                 Instruction *ToI,
7730                                                 ScheduleData *PrevLoadStore,
7731                                                 ScheduleData *NextLoadStore) {
7732   ScheduleData *CurrentLoadStore = PrevLoadStore;
7733   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7734     ScheduleData *SD = ScheduleDataMap[I];
7735     if (!SD) {
7736       SD = allocateScheduleDataChunks();
7737       ScheduleDataMap[I] = SD;
7738       SD->Inst = I;
7739     }
7740     assert(!isInSchedulingRegion(SD) &&
7741            "new ScheduleData already in scheduling region");
7742     SD->init(SchedulingRegionID, I);
7743 
7744     if (I->mayReadOrWriteMemory() &&
7745         (!isa<IntrinsicInst>(I) ||
7746          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7747           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7748               Intrinsic::pseudoprobe))) {
7749       // Update the linked list of memory accessing instructions.
7750       if (CurrentLoadStore) {
7751         CurrentLoadStore->NextLoadStore = SD;
7752       } else {
7753         FirstLoadStoreInRegion = SD;
7754       }
7755       CurrentLoadStore = SD;
7756     }
7757   }
7758   if (NextLoadStore) {
7759     if (CurrentLoadStore)
7760       CurrentLoadStore->NextLoadStore = NextLoadStore;
7761   } else {
7762     LastLoadStoreInRegion = CurrentLoadStore;
7763   }
7764 }
7765 
7766 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7767                                                      bool InsertInReadyList,
7768                                                      BoUpSLP *SLP) {
7769   assert(SD->isSchedulingEntity());
7770 
7771   SmallVector<ScheduleData *, 10> WorkList;
7772   WorkList.push_back(SD);
7773 
7774   while (!WorkList.empty()) {
7775     ScheduleData *SD = WorkList.pop_back_val();
7776     for (ScheduleData *BundleMember = SD; BundleMember;
7777          BundleMember = BundleMember->NextInBundle) {
7778       assert(isInSchedulingRegion(BundleMember));
7779       if (BundleMember->hasValidDependencies())
7780         continue;
7781 
7782       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7783                  << "\n");
7784       BundleMember->Dependencies = 0;
7785       BundleMember->resetUnscheduledDeps();
7786 
7787       // Handle def-use chain dependencies.
7788       if (BundleMember->OpValue != BundleMember->Inst) {
7789         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7790         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7791           BundleMember->Dependencies++;
7792           ScheduleData *DestBundle = UseSD->FirstInBundle;
7793           if (!DestBundle->IsScheduled)
7794             BundleMember->incrementUnscheduledDeps(1);
7795           if (!DestBundle->hasValidDependencies())
7796             WorkList.push_back(DestBundle);
7797         }
7798       } else {
7799         for (User *U : BundleMember->Inst->users()) {
7800           assert(isa<Instruction>(U) &&
7801                  "user of instruction must be instruction");
7802           ScheduleData *UseSD = getScheduleData(U);
7803           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7804             BundleMember->Dependencies++;
7805             ScheduleData *DestBundle = UseSD->FirstInBundle;
7806             if (!DestBundle->IsScheduled)
7807               BundleMember->incrementUnscheduledDeps(1);
7808             if (!DestBundle->hasValidDependencies())
7809               WorkList.push_back(DestBundle);
7810           }
7811         }
7812       }
7813 
7814       // Handle the memory dependencies (if any).
7815       ScheduleData *DepDest = BundleMember->NextLoadStore;
7816       if (!DepDest)
7817         continue;
7818       Instruction *SrcInst = BundleMember->Inst;
7819       assert(SrcInst->mayReadOrWriteMemory() &&
7820              "NextLoadStore list for non memory effecting bundle?");
7821       MemoryLocation SrcLoc = getLocation(SrcInst);
7822       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7823       unsigned numAliased = 0;
7824       unsigned DistToSrc = 1;
7825 
7826       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7827         assert(isInSchedulingRegion(DepDest));
7828 
7829         // We have two limits to reduce the complexity:
7830         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7831         //    SLP->isAliased (which is the expensive part in this loop).
7832         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7833         //    the whole loop (even if the loop is fast, it's quadratic).
7834         //    It's important for the loop break condition (see below) to
7835         //    check this limit even between two read-only instructions.
7836         if (DistToSrc >= MaxMemDepDistance ||
7837             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7838              (numAliased >= AliasedCheckLimit ||
7839               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7840 
7841           // We increment the counter only if the locations are aliased
7842           // (instead of counting all alias checks). This gives a better
7843           // balance between reduced runtime and accurate dependencies.
7844           numAliased++;
7845 
7846           DepDest->MemoryDependencies.push_back(BundleMember);
7847           BundleMember->Dependencies++;
7848           ScheduleData *DestBundle = DepDest->FirstInBundle;
7849           if (!DestBundle->IsScheduled) {
7850             BundleMember->incrementUnscheduledDeps(1);
7851           }
7852           if (!DestBundle->hasValidDependencies()) {
7853             WorkList.push_back(DestBundle);
7854           }
7855         }
7856 
7857         // Example, explaining the loop break condition: Let's assume our
7858         // starting instruction is i0 and MaxMemDepDistance = 3.
7859         //
7860         //                      +--------v--v--v
7861         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7862         //             +--------^--^--^
7863         //
7864         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7865         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7866         // Previously we already added dependencies from i3 to i6,i7,i8
7867         // (because of MaxMemDepDistance). As we added a dependency from
7868         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7869         // and we can abort this loop at i6.
7870         if (DistToSrc >= 2 * MaxMemDepDistance)
7871           break;
7872         DistToSrc++;
7873       }
7874     }
7875     if (InsertInReadyList && SD->isReady()) {
7876       ReadyInsts.insert(SD);
7877       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7878                         << "\n");
7879     }
7880   }
7881 }
7882 
7883 void BoUpSLP::BlockScheduling::resetSchedule() {
7884   assert(ScheduleStart &&
7885          "tried to reset schedule on block which has not been scheduled");
7886   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7887     doForAllOpcodes(I, [&](ScheduleData *SD) {
7888       assert(isInSchedulingRegion(SD) &&
7889              "ScheduleData not in scheduling region");
7890       SD->IsScheduled = false;
7891       SD->resetUnscheduledDeps();
7892     });
7893   }
7894   ReadyInsts.clear();
7895 }
7896 
7897 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7898   if (!BS->ScheduleStart)
7899     return;
7900 
7901   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7902 
7903   BS->resetSchedule();
7904 
7905   // For the real scheduling we use a more sophisticated ready-list: it is
7906   // sorted by the original instruction location. This lets the final schedule
7907   // be as  close as possible to the original instruction order.
7908   struct ScheduleDataCompare {
7909     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7910       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7911     }
7912   };
7913   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7914 
7915   // Ensure that all dependency data is updated and fill the ready-list with
7916   // initial instructions.
7917   int Idx = 0;
7918   int NumToSchedule = 0;
7919   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7920        I = I->getNextNode()) {
7921     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7922       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7923               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7924              "scheduler and vectorizer bundle mismatch");
7925       SD->FirstInBundle->SchedulingPriority = Idx++;
7926       if (SD->isSchedulingEntity()) {
7927         BS->calculateDependencies(SD, false, this);
7928         NumToSchedule++;
7929       }
7930     });
7931   }
7932   BS->initialFillReadyList(ReadyInsts);
7933 
7934   Instruction *LastScheduledInst = BS->ScheduleEnd;
7935 
7936   // Do the "real" scheduling.
7937   while (!ReadyInsts.empty()) {
7938     ScheduleData *picked = *ReadyInsts.begin();
7939     ReadyInsts.erase(ReadyInsts.begin());
7940 
7941     // Move the scheduled instruction(s) to their dedicated places, if not
7942     // there yet.
7943     for (ScheduleData *BundleMember = picked; BundleMember;
7944          BundleMember = BundleMember->NextInBundle) {
7945       Instruction *pickedInst = BundleMember->Inst;
7946       if (pickedInst->getNextNode() != LastScheduledInst)
7947         pickedInst->moveBefore(LastScheduledInst);
7948       LastScheduledInst = pickedInst;
7949     }
7950 
7951     BS->schedule(picked, ReadyInsts);
7952     NumToSchedule--;
7953   }
7954   assert(NumToSchedule == 0 && "could not schedule all instructions");
7955 
7956   // Check that we didn't break any of our invariants.
7957 #ifdef EXPENSIVE_CHECKS
7958   BS->verify();
7959 #endif
7960 
7961   // Avoid duplicate scheduling of the block.
7962   BS->ScheduleStart = nullptr;
7963 }
7964 
7965 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7966   // If V is a store, just return the width of the stored value (or value
7967   // truncated just before storing) without traversing the expression tree.
7968   // This is the common case.
7969   if (auto *Store = dyn_cast<StoreInst>(V)) {
7970     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7971       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7972     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7973   }
7974 
7975   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7976     return getVectorElementSize(IEI->getOperand(1));
7977 
7978   auto E = InstrElementSize.find(V);
7979   if (E != InstrElementSize.end())
7980     return E->second;
7981 
7982   // If V is not a store, we can traverse the expression tree to find loads
7983   // that feed it. The type of the loaded value may indicate a more suitable
7984   // width than V's type. We want to base the vector element size on the width
7985   // of memory operations where possible.
7986   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7987   SmallPtrSet<Instruction *, 16> Visited;
7988   if (auto *I = dyn_cast<Instruction>(V)) {
7989     Worklist.emplace_back(I, I->getParent());
7990     Visited.insert(I);
7991   }
7992 
7993   // Traverse the expression tree in bottom-up order looking for loads. If we
7994   // encounter an instruction we don't yet handle, we give up.
7995   auto Width = 0u;
7996   while (!Worklist.empty()) {
7997     Instruction *I;
7998     BasicBlock *Parent;
7999     std::tie(I, Parent) = Worklist.pop_back_val();
8000 
8001     // We should only be looking at scalar instructions here. If the current
8002     // instruction has a vector type, skip.
8003     auto *Ty = I->getType();
8004     if (isa<VectorType>(Ty))
8005       continue;
8006 
8007     // If the current instruction is a load, update MaxWidth to reflect the
8008     // width of the loaded value.
8009     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8010         isa<ExtractValueInst>(I))
8011       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8012 
8013     // Otherwise, we need to visit the operands of the instruction. We only
8014     // handle the interesting cases from buildTree here. If an operand is an
8015     // instruction we haven't yet visited and from the same basic block as the
8016     // user or the use is a PHI node, we add it to the worklist.
8017     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8018              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8019              isa<UnaryOperator>(I)) {
8020       for (Use &U : I->operands())
8021         if (auto *J = dyn_cast<Instruction>(U.get()))
8022           if (Visited.insert(J).second &&
8023               (isa<PHINode>(I) || J->getParent() == Parent))
8024             Worklist.emplace_back(J, J->getParent());
8025     } else {
8026       break;
8027     }
8028   }
8029 
8030   // If we didn't encounter a memory access in the expression tree, or if we
8031   // gave up for some reason, just return the width of V. Otherwise, return the
8032   // maximum width we found.
8033   if (!Width) {
8034     if (auto *CI = dyn_cast<CmpInst>(V))
8035       V = CI->getOperand(0);
8036     Width = DL->getTypeSizeInBits(V->getType());
8037   }
8038 
8039   for (Instruction *I : Visited)
8040     InstrElementSize[I] = Width;
8041 
8042   return Width;
8043 }
8044 
8045 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8046 // smaller type with a truncation. We collect the values that will be demoted
8047 // in ToDemote and additional roots that require investigating in Roots.
8048 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8049                                   SmallVectorImpl<Value *> &ToDemote,
8050                                   SmallVectorImpl<Value *> &Roots) {
8051   // We can always demote constants.
8052   if (isa<Constant>(V)) {
8053     ToDemote.push_back(V);
8054     return true;
8055   }
8056 
8057   // If the value is not an instruction in the expression with only one use, it
8058   // cannot be demoted.
8059   auto *I = dyn_cast<Instruction>(V);
8060   if (!I || !I->hasOneUse() || !Expr.count(I))
8061     return false;
8062 
8063   switch (I->getOpcode()) {
8064 
8065   // We can always demote truncations and extensions. Since truncations can
8066   // seed additional demotion, we save the truncated value.
8067   case Instruction::Trunc:
8068     Roots.push_back(I->getOperand(0));
8069     break;
8070   case Instruction::ZExt:
8071   case Instruction::SExt:
8072     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8073         isa<InsertElementInst>(I->getOperand(0)))
8074       return false;
8075     break;
8076 
8077   // We can demote certain binary operations if we can demote both of their
8078   // operands.
8079   case Instruction::Add:
8080   case Instruction::Sub:
8081   case Instruction::Mul:
8082   case Instruction::And:
8083   case Instruction::Or:
8084   case Instruction::Xor:
8085     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8086         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8087       return false;
8088     break;
8089 
8090   // We can demote selects if we can demote their true and false values.
8091   case Instruction::Select: {
8092     SelectInst *SI = cast<SelectInst>(I);
8093     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8094         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8095       return false;
8096     break;
8097   }
8098 
8099   // We can demote phis if we can demote all their incoming operands. Note that
8100   // we don't need to worry about cycles since we ensure single use above.
8101   case Instruction::PHI: {
8102     PHINode *PN = cast<PHINode>(I);
8103     for (Value *IncValue : PN->incoming_values())
8104       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8105         return false;
8106     break;
8107   }
8108 
8109   // Otherwise, conservatively give up.
8110   default:
8111     return false;
8112   }
8113 
8114   // Record the value that we can demote.
8115   ToDemote.push_back(V);
8116   return true;
8117 }
8118 
8119 void BoUpSLP::computeMinimumValueSizes() {
8120   // If there are no external uses, the expression tree must be rooted by a
8121   // store. We can't demote in-memory values, so there is nothing to do here.
8122   if (ExternalUses.empty())
8123     return;
8124 
8125   // We only attempt to truncate integer expressions.
8126   auto &TreeRoot = VectorizableTree[0]->Scalars;
8127   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8128   if (!TreeRootIT)
8129     return;
8130 
8131   // If the expression is not rooted by a store, these roots should have
8132   // external uses. We will rely on InstCombine to rewrite the expression in
8133   // the narrower type. However, InstCombine only rewrites single-use values.
8134   // This means that if a tree entry other than a root is used externally, it
8135   // must have multiple uses and InstCombine will not rewrite it. The code
8136   // below ensures that only the roots are used externally.
8137   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8138   for (auto &EU : ExternalUses)
8139     if (!Expr.erase(EU.Scalar))
8140       return;
8141   if (!Expr.empty())
8142     return;
8143 
8144   // Collect the scalar values of the vectorizable expression. We will use this
8145   // context to determine which values can be demoted. If we see a truncation,
8146   // we mark it as seeding another demotion.
8147   for (auto &EntryPtr : VectorizableTree)
8148     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8149 
8150   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8151   // have a single external user that is not in the vectorizable tree.
8152   for (auto *Root : TreeRoot)
8153     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8154       return;
8155 
8156   // Conservatively determine if we can actually truncate the roots of the
8157   // expression. Collect the values that can be demoted in ToDemote and
8158   // additional roots that require investigating in Roots.
8159   SmallVector<Value *, 32> ToDemote;
8160   SmallVector<Value *, 4> Roots;
8161   for (auto *Root : TreeRoot)
8162     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8163       return;
8164 
8165   // The maximum bit width required to represent all the values that can be
8166   // demoted without loss of precision. It would be safe to truncate the roots
8167   // of the expression to this width.
8168   auto MaxBitWidth = 8u;
8169 
8170   // We first check if all the bits of the roots are demanded. If they're not,
8171   // we can truncate the roots to this narrower type.
8172   for (auto *Root : TreeRoot) {
8173     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8174     MaxBitWidth = std::max<unsigned>(
8175         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8176   }
8177 
8178   // True if the roots can be zero-extended back to their original type, rather
8179   // than sign-extended. We know that if the leading bits are not demanded, we
8180   // can safely zero-extend. So we initialize IsKnownPositive to True.
8181   bool IsKnownPositive = true;
8182 
8183   // If all the bits of the roots are demanded, we can try a little harder to
8184   // compute a narrower type. This can happen, for example, if the roots are
8185   // getelementptr indices. InstCombine promotes these indices to the pointer
8186   // width. Thus, all their bits are technically demanded even though the
8187   // address computation might be vectorized in a smaller type.
8188   //
8189   // We start by looking at each entry that can be demoted. We compute the
8190   // maximum bit width required to store the scalar by using ValueTracking to
8191   // compute the number of high-order bits we can truncate.
8192   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8193       llvm::all_of(TreeRoot, [](Value *R) {
8194         assert(R->hasOneUse() && "Root should have only one use!");
8195         return isa<GetElementPtrInst>(R->user_back());
8196       })) {
8197     MaxBitWidth = 8u;
8198 
8199     // Determine if the sign bit of all the roots is known to be zero. If not,
8200     // IsKnownPositive is set to False.
8201     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8202       KnownBits Known = computeKnownBits(R, *DL);
8203       return Known.isNonNegative();
8204     });
8205 
8206     // Determine the maximum number of bits required to store the scalar
8207     // values.
8208     for (auto *Scalar : ToDemote) {
8209       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8210       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8211       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8212     }
8213 
8214     // If we can't prove that the sign bit is zero, we must add one to the
8215     // maximum bit width to account for the unknown sign bit. This preserves
8216     // the existing sign bit so we can safely sign-extend the root back to the
8217     // original type. Otherwise, if we know the sign bit is zero, we will
8218     // zero-extend the root instead.
8219     //
8220     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8221     //        one to the maximum bit width will yield a larger-than-necessary
8222     //        type. In general, we need to add an extra bit only if we can't
8223     //        prove that the upper bit of the original type is equal to the
8224     //        upper bit of the proposed smaller type. If these two bits are the
8225     //        same (either zero or one) we know that sign-extending from the
8226     //        smaller type will result in the same value. Here, since we can't
8227     //        yet prove this, we are just making the proposed smaller type
8228     //        larger to ensure correctness.
8229     if (!IsKnownPositive)
8230       ++MaxBitWidth;
8231   }
8232 
8233   // Round MaxBitWidth up to the next power-of-two.
8234   if (!isPowerOf2_64(MaxBitWidth))
8235     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8236 
8237   // If the maximum bit width we compute is less than the with of the roots'
8238   // type, we can proceed with the narrowing. Otherwise, do nothing.
8239   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8240     return;
8241 
8242   // If we can truncate the root, we must collect additional values that might
8243   // be demoted as a result. That is, those seeded by truncations we will
8244   // modify.
8245   while (!Roots.empty())
8246     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8247 
8248   // Finally, map the values we can demote to the maximum bit with we computed.
8249   for (auto *Scalar : ToDemote)
8250     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8251 }
8252 
8253 namespace {
8254 
8255 /// The SLPVectorizer Pass.
8256 struct SLPVectorizer : public FunctionPass {
8257   SLPVectorizerPass Impl;
8258 
8259   /// Pass identification, replacement for typeid
8260   static char ID;
8261 
8262   explicit SLPVectorizer() : FunctionPass(ID) {
8263     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8264   }
8265 
8266   bool doInitialization(Module &M) override { return false; }
8267 
8268   bool runOnFunction(Function &F) override {
8269     if (skipFunction(F))
8270       return false;
8271 
8272     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8273     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8274     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8275     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8276     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8277     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8278     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8279     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8280     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8281     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8282 
8283     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8284   }
8285 
8286   void getAnalysisUsage(AnalysisUsage &AU) const override {
8287     FunctionPass::getAnalysisUsage(AU);
8288     AU.addRequired<AssumptionCacheTracker>();
8289     AU.addRequired<ScalarEvolutionWrapperPass>();
8290     AU.addRequired<AAResultsWrapperPass>();
8291     AU.addRequired<TargetTransformInfoWrapperPass>();
8292     AU.addRequired<LoopInfoWrapperPass>();
8293     AU.addRequired<DominatorTreeWrapperPass>();
8294     AU.addRequired<DemandedBitsWrapperPass>();
8295     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8296     AU.addRequired<InjectTLIMappingsLegacy>();
8297     AU.addPreserved<LoopInfoWrapperPass>();
8298     AU.addPreserved<DominatorTreeWrapperPass>();
8299     AU.addPreserved<AAResultsWrapperPass>();
8300     AU.addPreserved<GlobalsAAWrapperPass>();
8301     AU.setPreservesCFG();
8302   }
8303 };
8304 
8305 } // end anonymous namespace
8306 
8307 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8308   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8309   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8310   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8311   auto *AA = &AM.getResult<AAManager>(F);
8312   auto *LI = &AM.getResult<LoopAnalysis>(F);
8313   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8314   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8315   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8316   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8317 
8318   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8319   if (!Changed)
8320     return PreservedAnalyses::all();
8321 
8322   PreservedAnalyses PA;
8323   PA.preserveSet<CFGAnalyses>();
8324   return PA;
8325 }
8326 
8327 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8328                                 TargetTransformInfo *TTI_,
8329                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8330                                 LoopInfo *LI_, DominatorTree *DT_,
8331                                 AssumptionCache *AC_, DemandedBits *DB_,
8332                                 OptimizationRemarkEmitter *ORE_) {
8333   if (!RunSLPVectorization)
8334     return false;
8335   SE = SE_;
8336   TTI = TTI_;
8337   TLI = TLI_;
8338   AA = AA_;
8339   LI = LI_;
8340   DT = DT_;
8341   AC = AC_;
8342   DB = DB_;
8343   DL = &F.getParent()->getDataLayout();
8344 
8345   Stores.clear();
8346   GEPs.clear();
8347   bool Changed = false;
8348 
8349   // If the target claims to have no vector registers don't attempt
8350   // vectorization.
8351   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8352     LLVM_DEBUG(
8353         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8354     return false;
8355   }
8356 
8357   // Don't vectorize when the attribute NoImplicitFloat is used.
8358   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8359     return false;
8360 
8361   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8362 
8363   // Use the bottom up slp vectorizer to construct chains that start with
8364   // store instructions.
8365   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8366 
8367   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8368   // delete instructions.
8369 
8370   // Update DFS numbers now so that we can use them for ordering.
8371   DT->updateDFSNumbers();
8372 
8373   // Scan the blocks in the function in post order.
8374   for (auto BB : post_order(&F.getEntryBlock())) {
8375     collectSeedInstructions(BB);
8376 
8377     // Vectorize trees that end at stores.
8378     if (!Stores.empty()) {
8379       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8380                         << " underlying objects.\n");
8381       Changed |= vectorizeStoreChains(R);
8382     }
8383 
8384     // Vectorize trees that end at reductions.
8385     Changed |= vectorizeChainsInBlock(BB, R);
8386 
8387     // Vectorize the index computations of getelementptr instructions. This
8388     // is primarily intended to catch gather-like idioms ending at
8389     // non-consecutive loads.
8390     if (!GEPs.empty()) {
8391       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8392                         << " underlying objects.\n");
8393       Changed |= vectorizeGEPIndices(BB, R);
8394     }
8395   }
8396 
8397   if (Changed) {
8398     R.optimizeGatherSequence();
8399     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8400   }
8401   return Changed;
8402 }
8403 
8404 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8405                                             unsigned Idx) {
8406   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8407                     << "\n");
8408   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8409   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8410   unsigned VF = Chain.size();
8411 
8412   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8413     return false;
8414 
8415   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8416                     << "\n");
8417 
8418   R.buildTree(Chain);
8419   if (R.isTreeTinyAndNotFullyVectorizable())
8420     return false;
8421   if (R.isLoadCombineCandidate())
8422     return false;
8423   R.reorderTopToBottom();
8424   R.reorderBottomToTop();
8425   R.buildExternalUses();
8426 
8427   R.computeMinimumValueSizes();
8428 
8429   InstructionCost Cost = R.getTreeCost();
8430 
8431   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8432   if (Cost < -SLPCostThreshold) {
8433     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8434 
8435     using namespace ore;
8436 
8437     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8438                                         cast<StoreInst>(Chain[0]))
8439                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8440                      << " and with tree size "
8441                      << NV("TreeSize", R.getTreeSize()));
8442 
8443     R.vectorizeTree();
8444     return true;
8445   }
8446 
8447   return false;
8448 }
8449 
8450 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8451                                         BoUpSLP &R) {
8452   // We may run into multiple chains that merge into a single chain. We mark the
8453   // stores that we vectorized so that we don't visit the same store twice.
8454   BoUpSLP::ValueSet VectorizedStores;
8455   bool Changed = false;
8456 
8457   int E = Stores.size();
8458   SmallBitVector Tails(E, false);
8459   int MaxIter = MaxStoreLookup.getValue();
8460   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8461       E, std::make_pair(E, INT_MAX));
8462   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8463   int IterCnt;
8464   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8465                                   &CheckedPairs,
8466                                   &ConsecutiveChain](int K, int Idx) {
8467     if (IterCnt >= MaxIter)
8468       return true;
8469     if (CheckedPairs[Idx].test(K))
8470       return ConsecutiveChain[K].second == 1 &&
8471              ConsecutiveChain[K].first == Idx;
8472     ++IterCnt;
8473     CheckedPairs[Idx].set(K);
8474     CheckedPairs[K].set(Idx);
8475     Optional<int> Diff = getPointersDiff(
8476         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8477         Stores[Idx]->getValueOperand()->getType(),
8478         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8479     if (!Diff || *Diff == 0)
8480       return false;
8481     int Val = *Diff;
8482     if (Val < 0) {
8483       if (ConsecutiveChain[Idx].second > -Val) {
8484         Tails.set(K);
8485         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8486       }
8487       return false;
8488     }
8489     if (ConsecutiveChain[K].second <= Val)
8490       return false;
8491 
8492     Tails.set(Idx);
8493     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8494     return Val == 1;
8495   };
8496   // Do a quadratic search on all of the given stores in reverse order and find
8497   // all of the pairs of stores that follow each other.
8498   for (int Idx = E - 1; Idx >= 0; --Idx) {
8499     // If a store has multiple consecutive store candidates, search according
8500     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8501     // This is because usually pairing with immediate succeeding or preceding
8502     // candidate create the best chance to find slp vectorization opportunity.
8503     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8504     IterCnt = 0;
8505     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8506       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8507           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8508         break;
8509   }
8510 
8511   // Tracks if we tried to vectorize stores starting from the given tail
8512   // already.
8513   SmallBitVector TriedTails(E, false);
8514   // For stores that start but don't end a link in the chain:
8515   for (int Cnt = E; Cnt > 0; --Cnt) {
8516     int I = Cnt - 1;
8517     if (ConsecutiveChain[I].first == E || Tails.test(I))
8518       continue;
8519     // We found a store instr that starts a chain. Now follow the chain and try
8520     // to vectorize it.
8521     BoUpSLP::ValueList Operands;
8522     // Collect the chain into a list.
8523     while (I != E && !VectorizedStores.count(Stores[I])) {
8524       Operands.push_back(Stores[I]);
8525       Tails.set(I);
8526       if (ConsecutiveChain[I].second != 1) {
8527         // Mark the new end in the chain and go back, if required. It might be
8528         // required if the original stores come in reversed order, for example.
8529         if (ConsecutiveChain[I].first != E &&
8530             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8531             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8532           TriedTails.set(I);
8533           Tails.reset(ConsecutiveChain[I].first);
8534           if (Cnt < ConsecutiveChain[I].first + 2)
8535             Cnt = ConsecutiveChain[I].first + 2;
8536         }
8537         break;
8538       }
8539       // Move to the next value in the chain.
8540       I = ConsecutiveChain[I].first;
8541     }
8542     assert(!Operands.empty() && "Expected non-empty list of stores.");
8543 
8544     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8545     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8546     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8547 
8548     unsigned MinVF = R.getMinVF(EltSize);
8549     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8550                               MaxElts);
8551 
8552     // FIXME: Is division-by-2 the correct step? Should we assert that the
8553     // register size is a power-of-2?
8554     unsigned StartIdx = 0;
8555     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8556       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8557         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8558         if (!VectorizedStores.count(Slice.front()) &&
8559             !VectorizedStores.count(Slice.back()) &&
8560             vectorizeStoreChain(Slice, R, Cnt)) {
8561           // Mark the vectorized stores so that we don't vectorize them again.
8562           VectorizedStores.insert(Slice.begin(), Slice.end());
8563           Changed = true;
8564           // If we vectorized initial block, no need to try to vectorize it
8565           // again.
8566           if (Cnt == StartIdx)
8567             StartIdx += Size;
8568           Cnt += Size;
8569           continue;
8570         }
8571         ++Cnt;
8572       }
8573       // Check if the whole array was vectorized already - exit.
8574       if (StartIdx >= Operands.size())
8575         break;
8576     }
8577   }
8578 
8579   return Changed;
8580 }
8581 
8582 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8583   // Initialize the collections. We will make a single pass over the block.
8584   Stores.clear();
8585   GEPs.clear();
8586 
8587   // Visit the store and getelementptr instructions in BB and organize them in
8588   // Stores and GEPs according to the underlying objects of their pointer
8589   // operands.
8590   for (Instruction &I : *BB) {
8591     // Ignore store instructions that are volatile or have a pointer operand
8592     // that doesn't point to a scalar type.
8593     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8594       if (!SI->isSimple())
8595         continue;
8596       if (!isValidElementType(SI->getValueOperand()->getType()))
8597         continue;
8598       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8599     }
8600 
8601     // Ignore getelementptr instructions that have more than one index, a
8602     // constant index, or a pointer operand that doesn't point to a scalar
8603     // type.
8604     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8605       auto Idx = GEP->idx_begin()->get();
8606       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8607         continue;
8608       if (!isValidElementType(Idx->getType()))
8609         continue;
8610       if (GEP->getType()->isVectorTy())
8611         continue;
8612       GEPs[GEP->getPointerOperand()].push_back(GEP);
8613     }
8614   }
8615 }
8616 
8617 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8618   if (!A || !B)
8619     return false;
8620   Value *VL[] = {A, B};
8621   return tryToVectorizeList(VL, R);
8622 }
8623 
8624 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8625                                            bool LimitForRegisterSize) {
8626   if (VL.size() < 2)
8627     return false;
8628 
8629   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8630                     << VL.size() << ".\n");
8631 
8632   // Check that all of the parts are instructions of the same type,
8633   // we permit an alternate opcode via InstructionsState.
8634   InstructionsState S = getSameOpcode(VL);
8635   if (!S.getOpcode())
8636     return false;
8637 
8638   Instruction *I0 = cast<Instruction>(S.OpValue);
8639   // Make sure invalid types (including vector type) are rejected before
8640   // determining vectorization factor for scalar instructions.
8641   for (Value *V : VL) {
8642     Type *Ty = V->getType();
8643     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8644       // NOTE: the following will give user internal llvm type name, which may
8645       // not be useful.
8646       R.getORE()->emit([&]() {
8647         std::string type_str;
8648         llvm::raw_string_ostream rso(type_str);
8649         Ty->print(rso);
8650         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8651                << "Cannot SLP vectorize list: type "
8652                << rso.str() + " is unsupported by vectorizer";
8653       });
8654       return false;
8655     }
8656   }
8657 
8658   unsigned Sz = R.getVectorElementSize(I0);
8659   unsigned MinVF = R.getMinVF(Sz);
8660   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8661   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8662   if (MaxVF < 2) {
8663     R.getORE()->emit([&]() {
8664       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8665              << "Cannot SLP vectorize list: vectorization factor "
8666              << "less than 2 is not supported";
8667     });
8668     return false;
8669   }
8670 
8671   bool Changed = false;
8672   bool CandidateFound = false;
8673   InstructionCost MinCost = SLPCostThreshold.getValue();
8674   Type *ScalarTy = VL[0]->getType();
8675   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8676     ScalarTy = IE->getOperand(1)->getType();
8677 
8678   unsigned NextInst = 0, MaxInst = VL.size();
8679   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8680     // No actual vectorization should happen, if number of parts is the same as
8681     // provided vectorization factor (i.e. the scalar type is used for vector
8682     // code during codegen).
8683     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8684     if (TTI->getNumberOfParts(VecTy) == VF)
8685       continue;
8686     for (unsigned I = NextInst; I < MaxInst; ++I) {
8687       unsigned OpsWidth = 0;
8688 
8689       if (I + VF > MaxInst)
8690         OpsWidth = MaxInst - I;
8691       else
8692         OpsWidth = VF;
8693 
8694       if (!isPowerOf2_32(OpsWidth))
8695         continue;
8696 
8697       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8698           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8699         break;
8700 
8701       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8702       // Check that a previous iteration of this loop did not delete the Value.
8703       if (llvm::any_of(Ops, [&R](Value *V) {
8704             auto *I = dyn_cast<Instruction>(V);
8705             return I && R.isDeleted(I);
8706           }))
8707         continue;
8708 
8709       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8710                         << "\n");
8711 
8712       R.buildTree(Ops);
8713       if (R.isTreeTinyAndNotFullyVectorizable())
8714         continue;
8715       R.reorderTopToBottom();
8716       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8717       R.buildExternalUses();
8718 
8719       R.computeMinimumValueSizes();
8720       InstructionCost Cost = R.getTreeCost();
8721       CandidateFound = true;
8722       MinCost = std::min(MinCost, Cost);
8723 
8724       if (Cost < -SLPCostThreshold) {
8725         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8726         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8727                                                     cast<Instruction>(Ops[0]))
8728                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8729                                  << " and with tree size "
8730                                  << ore::NV("TreeSize", R.getTreeSize()));
8731 
8732         R.vectorizeTree();
8733         // Move to the next bundle.
8734         I += VF - 1;
8735         NextInst = I + 1;
8736         Changed = true;
8737       }
8738     }
8739   }
8740 
8741   if (!Changed && CandidateFound) {
8742     R.getORE()->emit([&]() {
8743       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8744              << "List vectorization was possible but not beneficial with cost "
8745              << ore::NV("Cost", MinCost) << " >= "
8746              << ore::NV("Treshold", -SLPCostThreshold);
8747     });
8748   } else if (!Changed) {
8749     R.getORE()->emit([&]() {
8750       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8751              << "Cannot SLP vectorize list: vectorization was impossible"
8752              << " with available vectorization factors";
8753     });
8754   }
8755   return Changed;
8756 }
8757 
8758 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8759   if (!I)
8760     return false;
8761 
8762   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8763     return false;
8764 
8765   Value *P = I->getParent();
8766 
8767   // Vectorize in current basic block only.
8768   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8769   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8770   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8771     return false;
8772 
8773   // Try to vectorize V.
8774   if (tryToVectorizePair(Op0, Op1, R))
8775     return true;
8776 
8777   auto *A = dyn_cast<BinaryOperator>(Op0);
8778   auto *B = dyn_cast<BinaryOperator>(Op1);
8779   // Try to skip B.
8780   if (B && B->hasOneUse()) {
8781     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8782     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8783     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8784       return true;
8785     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8786       return true;
8787   }
8788 
8789   // Try to skip A.
8790   if (A && A->hasOneUse()) {
8791     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8792     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8793     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8794       return true;
8795     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8796       return true;
8797   }
8798   return false;
8799 }
8800 
8801 namespace {
8802 
8803 /// Model horizontal reductions.
8804 ///
8805 /// A horizontal reduction is a tree of reduction instructions that has values
8806 /// that can be put into a vector as its leaves. For example:
8807 ///
8808 /// mul mul mul mul
8809 ///  \  /    \  /
8810 ///   +       +
8811 ///    \     /
8812 ///       +
8813 /// This tree has "mul" as its leaf values and "+" as its reduction
8814 /// instructions. A reduction can feed into a store or a binary operation
8815 /// feeding a phi.
8816 ///    ...
8817 ///    \  /
8818 ///     +
8819 ///     |
8820 ///  phi +=
8821 ///
8822 ///  Or:
8823 ///    ...
8824 ///    \  /
8825 ///     +
8826 ///     |
8827 ///   *p =
8828 ///
8829 class HorizontalReduction {
8830   using ReductionOpsType = SmallVector<Value *, 16>;
8831   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8832   ReductionOpsListType ReductionOps;
8833   SmallVector<Value *, 32> ReducedVals;
8834   // Use map vector to make stable output.
8835   MapVector<Instruction *, Value *> ExtraArgs;
8836   WeakTrackingVH ReductionRoot;
8837   /// The type of reduction operation.
8838   RecurKind RdxKind;
8839 
8840   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8841 
8842   static bool isCmpSelMinMax(Instruction *I) {
8843     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8844            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8845   }
8846 
8847   // And/or are potentially poison-safe logical patterns like:
8848   // select x, y, false
8849   // select x, true, y
8850   static bool isBoolLogicOp(Instruction *I) {
8851     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8852            match(I, m_LogicalOr(m_Value(), m_Value()));
8853   }
8854 
8855   /// Checks if instruction is associative and can be vectorized.
8856   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8857     if (Kind == RecurKind::None)
8858       return false;
8859 
8860     // Integer ops that map to select instructions or intrinsics are fine.
8861     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8862         isBoolLogicOp(I))
8863       return true;
8864 
8865     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8866       // FP min/max are associative except for NaN and -0.0. We do not
8867       // have to rule out -0.0 here because the intrinsic semantics do not
8868       // specify a fixed result for it.
8869       return I->getFastMathFlags().noNaNs();
8870     }
8871 
8872     return I->isAssociative();
8873   }
8874 
8875   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8876     // Poison-safe 'or' takes the form: select X, true, Y
8877     // To make that work with the normal operand processing, we skip the
8878     // true value operand.
8879     // TODO: Change the code and data structures to handle this without a hack.
8880     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8881       return I->getOperand(2);
8882     return I->getOperand(Index);
8883   }
8884 
8885   /// Checks if the ParentStackElem.first should be marked as a reduction
8886   /// operation with an extra argument or as extra argument itself.
8887   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8888                     Value *ExtraArg) {
8889     if (ExtraArgs.count(ParentStackElem.first)) {
8890       ExtraArgs[ParentStackElem.first] = nullptr;
8891       // We ran into something like:
8892       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8893       // The whole ParentStackElem.first should be considered as an extra value
8894       // in this case.
8895       // Do not perform analysis of remaining operands of ParentStackElem.first
8896       // instruction, this whole instruction is an extra argument.
8897       ParentStackElem.second = INVALID_OPERAND_INDEX;
8898     } else {
8899       // We ran into something like:
8900       // ParentStackElem.first += ... + ExtraArg + ...
8901       ExtraArgs[ParentStackElem.first] = ExtraArg;
8902     }
8903   }
8904 
8905   /// Creates reduction operation with the current opcode.
8906   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8907                          Value *RHS, const Twine &Name, bool UseSelect) {
8908     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8909     switch (Kind) {
8910     case RecurKind::Or:
8911       if (UseSelect &&
8912           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8913         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8914       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8915                                  Name);
8916     case RecurKind::And:
8917       if (UseSelect &&
8918           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8919         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8920       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8921                                  Name);
8922     case RecurKind::Add:
8923     case RecurKind::Mul:
8924     case RecurKind::Xor:
8925     case RecurKind::FAdd:
8926     case RecurKind::FMul:
8927       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8928                                  Name);
8929     case RecurKind::FMax:
8930       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8931     case RecurKind::FMin:
8932       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8933     case RecurKind::SMax:
8934       if (UseSelect) {
8935         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8936         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8937       }
8938       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8939     case RecurKind::SMin:
8940       if (UseSelect) {
8941         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8942         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8943       }
8944       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8945     case RecurKind::UMax:
8946       if (UseSelect) {
8947         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8948         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8949       }
8950       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8951     case RecurKind::UMin:
8952       if (UseSelect) {
8953         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8954         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8955       }
8956       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8957     default:
8958       llvm_unreachable("Unknown reduction operation.");
8959     }
8960   }
8961 
8962   /// Creates reduction operation with the current opcode with the IR flags
8963   /// from \p ReductionOps.
8964   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8965                          Value *RHS, const Twine &Name,
8966                          const ReductionOpsListType &ReductionOps) {
8967     bool UseSelect = ReductionOps.size() == 2 ||
8968                      // Logical or/and.
8969                      (ReductionOps.size() == 1 &&
8970                       isa<SelectInst>(ReductionOps.front().front()));
8971     assert((!UseSelect || ReductionOps.size() != 2 ||
8972             isa<SelectInst>(ReductionOps[1][0])) &&
8973            "Expected cmp + select pairs for reduction");
8974     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8975     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8976       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8977         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8978         propagateIRFlags(Op, ReductionOps[1]);
8979         return Op;
8980       }
8981     }
8982     propagateIRFlags(Op, ReductionOps[0]);
8983     return Op;
8984   }
8985 
8986   /// Creates reduction operation with the current opcode with the IR flags
8987   /// from \p I.
8988   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8989                          Value *RHS, const Twine &Name, Instruction *I) {
8990     auto *SelI = dyn_cast<SelectInst>(I);
8991     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8992     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8993       if (auto *Sel = dyn_cast<SelectInst>(Op))
8994         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8995     }
8996     propagateIRFlags(Op, I);
8997     return Op;
8998   }
8999 
9000   static RecurKind getRdxKind(Instruction *I) {
9001     assert(I && "Expected instruction for reduction matching");
9002     if (match(I, m_Add(m_Value(), m_Value())))
9003       return RecurKind::Add;
9004     if (match(I, m_Mul(m_Value(), m_Value())))
9005       return RecurKind::Mul;
9006     if (match(I, m_And(m_Value(), m_Value())) ||
9007         match(I, m_LogicalAnd(m_Value(), m_Value())))
9008       return RecurKind::And;
9009     if (match(I, m_Or(m_Value(), m_Value())) ||
9010         match(I, m_LogicalOr(m_Value(), m_Value())))
9011       return RecurKind::Or;
9012     if (match(I, m_Xor(m_Value(), m_Value())))
9013       return RecurKind::Xor;
9014     if (match(I, m_FAdd(m_Value(), m_Value())))
9015       return RecurKind::FAdd;
9016     if (match(I, m_FMul(m_Value(), m_Value())))
9017       return RecurKind::FMul;
9018 
9019     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9020       return RecurKind::FMax;
9021     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9022       return RecurKind::FMin;
9023 
9024     // This matches either cmp+select or intrinsics. SLP is expected to handle
9025     // either form.
9026     // TODO: If we are canonicalizing to intrinsics, we can remove several
9027     //       special-case paths that deal with selects.
9028     if (match(I, m_SMax(m_Value(), m_Value())))
9029       return RecurKind::SMax;
9030     if (match(I, m_SMin(m_Value(), m_Value())))
9031       return RecurKind::SMin;
9032     if (match(I, m_UMax(m_Value(), m_Value())))
9033       return RecurKind::UMax;
9034     if (match(I, m_UMin(m_Value(), m_Value())))
9035       return RecurKind::UMin;
9036 
9037     if (auto *Select = dyn_cast<SelectInst>(I)) {
9038       // Try harder: look for min/max pattern based on instructions producing
9039       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9040       // During the intermediate stages of SLP, it's very common to have
9041       // pattern like this (since optimizeGatherSequence is run only once
9042       // at the end):
9043       // %1 = extractelement <2 x i32> %a, i32 0
9044       // %2 = extractelement <2 x i32> %a, i32 1
9045       // %cond = icmp sgt i32 %1, %2
9046       // %3 = extractelement <2 x i32> %a, i32 0
9047       // %4 = extractelement <2 x i32> %a, i32 1
9048       // %select = select i1 %cond, i32 %3, i32 %4
9049       CmpInst::Predicate Pred;
9050       Instruction *L1;
9051       Instruction *L2;
9052 
9053       Value *LHS = Select->getTrueValue();
9054       Value *RHS = Select->getFalseValue();
9055       Value *Cond = Select->getCondition();
9056 
9057       // TODO: Support inverse predicates.
9058       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9059         if (!isa<ExtractElementInst>(RHS) ||
9060             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9061           return RecurKind::None;
9062       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9063         if (!isa<ExtractElementInst>(LHS) ||
9064             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9065           return RecurKind::None;
9066       } else {
9067         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9068           return RecurKind::None;
9069         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9070             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9071             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9072           return RecurKind::None;
9073       }
9074 
9075       switch (Pred) {
9076       default:
9077         return RecurKind::None;
9078       case CmpInst::ICMP_SGT:
9079       case CmpInst::ICMP_SGE:
9080         return RecurKind::SMax;
9081       case CmpInst::ICMP_SLT:
9082       case CmpInst::ICMP_SLE:
9083         return RecurKind::SMin;
9084       case CmpInst::ICMP_UGT:
9085       case CmpInst::ICMP_UGE:
9086         return RecurKind::UMax;
9087       case CmpInst::ICMP_ULT:
9088       case CmpInst::ICMP_ULE:
9089         return RecurKind::UMin;
9090       }
9091     }
9092     return RecurKind::None;
9093   }
9094 
9095   /// Get the index of the first operand.
9096   static unsigned getFirstOperandIndex(Instruction *I) {
9097     return isCmpSelMinMax(I) ? 1 : 0;
9098   }
9099 
9100   /// Total number of operands in the reduction operation.
9101   static unsigned getNumberOfOperands(Instruction *I) {
9102     return isCmpSelMinMax(I) ? 3 : 2;
9103   }
9104 
9105   /// Checks if the instruction is in basic block \p BB.
9106   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9107   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9108     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9109       auto *Sel = cast<SelectInst>(I);
9110       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9111       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9112     }
9113     return I->getParent() == BB;
9114   }
9115 
9116   /// Expected number of uses for reduction operations/reduced values.
9117   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9118     if (IsCmpSelMinMax) {
9119       // SelectInst must be used twice while the condition op must have single
9120       // use only.
9121       if (auto *Sel = dyn_cast<SelectInst>(I))
9122         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9123       return I->hasNUses(2);
9124     }
9125 
9126     // Arithmetic reduction operation must be used once only.
9127     return I->hasOneUse();
9128   }
9129 
9130   /// Initializes the list of reduction operations.
9131   void initReductionOps(Instruction *I) {
9132     if (isCmpSelMinMax(I))
9133       ReductionOps.assign(2, ReductionOpsType());
9134     else
9135       ReductionOps.assign(1, ReductionOpsType());
9136   }
9137 
9138   /// Add all reduction operations for the reduction instruction \p I.
9139   void addReductionOps(Instruction *I) {
9140     if (isCmpSelMinMax(I)) {
9141       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9142       ReductionOps[1].emplace_back(I);
9143     } else {
9144       ReductionOps[0].emplace_back(I);
9145     }
9146   }
9147 
9148   static Value *getLHS(RecurKind Kind, Instruction *I) {
9149     if (Kind == RecurKind::None)
9150       return nullptr;
9151     return I->getOperand(getFirstOperandIndex(I));
9152   }
9153   static Value *getRHS(RecurKind Kind, Instruction *I) {
9154     if (Kind == RecurKind::None)
9155       return nullptr;
9156     return I->getOperand(getFirstOperandIndex(I) + 1);
9157   }
9158 
9159 public:
9160   HorizontalReduction() = default;
9161 
9162   /// Try to find a reduction tree.
9163   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9164     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9165            "Phi needs to use the binary operator");
9166     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9167             isa<IntrinsicInst>(Inst)) &&
9168            "Expected binop, select, or intrinsic for reduction matching");
9169     RdxKind = getRdxKind(Inst);
9170 
9171     // We could have a initial reductions that is not an add.
9172     //  r *= v1 + v2 + v3 + v4
9173     // In such a case start looking for a tree rooted in the first '+'.
9174     if (Phi) {
9175       if (getLHS(RdxKind, Inst) == Phi) {
9176         Phi = nullptr;
9177         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9178         if (!Inst)
9179           return false;
9180         RdxKind = getRdxKind(Inst);
9181       } else if (getRHS(RdxKind, Inst) == Phi) {
9182         Phi = nullptr;
9183         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9184         if (!Inst)
9185           return false;
9186         RdxKind = getRdxKind(Inst);
9187       }
9188     }
9189 
9190     if (!isVectorizable(RdxKind, Inst))
9191       return false;
9192 
9193     // Analyze "regular" integer/FP types for reductions - no target-specific
9194     // types or pointers.
9195     Type *Ty = Inst->getType();
9196     if (!isValidElementType(Ty) || Ty->isPointerTy())
9197       return false;
9198 
9199     // Though the ultimate reduction may have multiple uses, its condition must
9200     // have only single use.
9201     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9202       if (!Sel->getCondition()->hasOneUse())
9203         return false;
9204 
9205     ReductionRoot = Inst;
9206 
9207     // The opcode for leaf values that we perform a reduction on.
9208     // For example: load(x) + load(y) + load(z) + fptoui(w)
9209     // The leaf opcode for 'w' does not match, so we don't include it as a
9210     // potential candidate for the reduction.
9211     unsigned LeafOpcode = 0;
9212 
9213     // Post-order traverse the reduction tree starting at Inst. We only handle
9214     // true trees containing binary operators or selects.
9215     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9216     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9217     initReductionOps(Inst);
9218     while (!Stack.empty()) {
9219       Instruction *TreeN = Stack.back().first;
9220       unsigned EdgeToVisit = Stack.back().second++;
9221       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9222       bool IsReducedValue = TreeRdxKind != RdxKind;
9223 
9224       // Postorder visit.
9225       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9226         if (IsReducedValue)
9227           ReducedVals.push_back(TreeN);
9228         else {
9229           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9230           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9231             // Check if TreeN is an extra argument of its parent operation.
9232             if (Stack.size() <= 1) {
9233               // TreeN can't be an extra argument as it is a root reduction
9234               // operation.
9235               return false;
9236             }
9237             // Yes, TreeN is an extra argument, do not add it to a list of
9238             // reduction operations.
9239             // Stack[Stack.size() - 2] always points to the parent operation.
9240             markExtraArg(Stack[Stack.size() - 2], TreeN);
9241             ExtraArgs.erase(TreeN);
9242           } else
9243             addReductionOps(TreeN);
9244         }
9245         // Retract.
9246         Stack.pop_back();
9247         continue;
9248       }
9249 
9250       // Visit operands.
9251       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9252       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9253       if (!EdgeInst) {
9254         // Edge value is not a reduction instruction or a leaf instruction.
9255         // (It may be a constant, function argument, or something else.)
9256         markExtraArg(Stack.back(), EdgeVal);
9257         continue;
9258       }
9259       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9260       // Continue analysis if the next operand is a reduction operation or
9261       // (possibly) a leaf value. If the leaf value opcode is not set,
9262       // the first met operation != reduction operation is considered as the
9263       // leaf opcode.
9264       // Only handle trees in the current basic block.
9265       // Each tree node needs to have minimal number of users except for the
9266       // ultimate reduction.
9267       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9268       if (EdgeInst != Phi && EdgeInst != Inst &&
9269           hasSameParent(EdgeInst, Inst->getParent()) &&
9270           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9271           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9272         if (IsRdxInst) {
9273           // We need to be able to reassociate the reduction operations.
9274           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9275             // I is an extra argument for TreeN (its parent operation).
9276             markExtraArg(Stack.back(), EdgeInst);
9277             continue;
9278           }
9279         } else if (!LeafOpcode) {
9280           LeafOpcode = EdgeInst->getOpcode();
9281         }
9282         Stack.push_back(
9283             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9284         continue;
9285       }
9286       // I is an extra argument for TreeN (its parent operation).
9287       markExtraArg(Stack.back(), EdgeInst);
9288     }
9289     return true;
9290   }
9291 
9292   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9293   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9294     // If there are a sufficient number of reduction values, reduce
9295     // to a nearby power-of-2. We can safely generate oversized
9296     // vectors and rely on the backend to split them to legal sizes.
9297     unsigned NumReducedVals = ReducedVals.size();
9298     if (NumReducedVals < 4)
9299       return nullptr;
9300 
9301     // Intersect the fast-math-flags from all reduction operations.
9302     FastMathFlags RdxFMF;
9303     RdxFMF.set();
9304     for (ReductionOpsType &RdxOp : ReductionOps) {
9305       for (Value *RdxVal : RdxOp) {
9306         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9307           RdxFMF &= FPMO->getFastMathFlags();
9308       }
9309     }
9310 
9311     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9312     Builder.setFastMathFlags(RdxFMF);
9313 
9314     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9315     // The same extra argument may be used several times, so log each attempt
9316     // to use it.
9317     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9318       assert(Pair.first && "DebugLoc must be set.");
9319       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9320     }
9321 
9322     // The compare instruction of a min/max is the insertion point for new
9323     // instructions and may be replaced with a new compare instruction.
9324     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9325       assert(isa<SelectInst>(RdxRootInst) &&
9326              "Expected min/max reduction to have select root instruction");
9327       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9328       assert(isa<Instruction>(ScalarCond) &&
9329              "Expected min/max reduction to have compare condition");
9330       return cast<Instruction>(ScalarCond);
9331     };
9332 
9333     // The reduction root is used as the insertion point for new instructions,
9334     // so set it as externally used to prevent it from being deleted.
9335     ExternallyUsedValues[ReductionRoot];
9336     SmallVector<Value *, 16> IgnoreList;
9337     for (ReductionOpsType &RdxOp : ReductionOps)
9338       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9339 
9340     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9341     if (NumReducedVals > ReduxWidth) {
9342       // In the loop below, we are building a tree based on a window of
9343       // 'ReduxWidth' values.
9344       // If the operands of those values have common traits (compare predicate,
9345       // constant operand, etc), then we want to group those together to
9346       // minimize the cost of the reduction.
9347 
9348       // TODO: This should be extended to count common operands for
9349       //       compares and binops.
9350 
9351       // Step 1: Count the number of times each compare predicate occurs.
9352       SmallDenseMap<unsigned, unsigned> PredCountMap;
9353       for (Value *RdxVal : ReducedVals) {
9354         CmpInst::Predicate Pred;
9355         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9356           ++PredCountMap[Pred];
9357       }
9358       // Step 2: Sort the values so the most common predicates come first.
9359       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9360         CmpInst::Predicate PredA, PredB;
9361         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9362             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9363           return PredCountMap[PredA] > PredCountMap[PredB];
9364         }
9365         return false;
9366       });
9367     }
9368 
9369     Value *VectorizedTree = nullptr;
9370     unsigned i = 0;
9371     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9372       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9373       V.buildTree(VL, IgnoreList);
9374       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9375         break;
9376       if (V.isLoadCombineReductionCandidate(RdxKind))
9377         break;
9378       V.reorderTopToBottom();
9379       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9380       V.buildExternalUses(ExternallyUsedValues);
9381 
9382       // For a poison-safe boolean logic reduction, do not replace select
9383       // instructions with logic ops. All reduced values will be frozen (see
9384       // below) to prevent leaking poison.
9385       if (isa<SelectInst>(ReductionRoot) &&
9386           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9387           NumReducedVals != ReduxWidth)
9388         break;
9389 
9390       V.computeMinimumValueSizes();
9391 
9392       // Estimate cost.
9393       InstructionCost TreeCost =
9394           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9395       InstructionCost ReductionCost =
9396           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9397       InstructionCost Cost = TreeCost + ReductionCost;
9398       if (!Cost.isValid()) {
9399         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9400         return nullptr;
9401       }
9402       if (Cost >= -SLPCostThreshold) {
9403         V.getORE()->emit([&]() {
9404           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9405                                           cast<Instruction>(VL[0]))
9406                  << "Vectorizing horizontal reduction is possible"
9407                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9408                  << " and threshold "
9409                  << ore::NV("Threshold", -SLPCostThreshold);
9410         });
9411         break;
9412       }
9413 
9414       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9415                         << Cost << ". (HorRdx)\n");
9416       V.getORE()->emit([&]() {
9417         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9418                                   cast<Instruction>(VL[0]))
9419                << "Vectorized horizontal reduction with cost "
9420                << ore::NV("Cost", Cost) << " and with tree size "
9421                << ore::NV("TreeSize", V.getTreeSize());
9422       });
9423 
9424       // Vectorize a tree.
9425       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9426       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9427 
9428       // Emit a reduction. If the root is a select (min/max idiom), the insert
9429       // point is the compare condition of that select.
9430       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9431       if (isCmpSelMinMax(RdxRootInst))
9432         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9433       else
9434         Builder.SetInsertPoint(RdxRootInst);
9435 
9436       // To prevent poison from leaking across what used to be sequential, safe,
9437       // scalar boolean logic operations, the reduction operand must be frozen.
9438       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9439         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9440 
9441       Value *ReducedSubTree =
9442           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9443 
9444       if (!VectorizedTree) {
9445         // Initialize the final value in the reduction.
9446         VectorizedTree = ReducedSubTree;
9447       } else {
9448         // Update the final value in the reduction.
9449         Builder.SetCurrentDebugLocation(Loc);
9450         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9451                                   ReducedSubTree, "op.rdx", ReductionOps);
9452       }
9453       i += ReduxWidth;
9454       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9455     }
9456 
9457     if (VectorizedTree) {
9458       // Finish the reduction.
9459       for (; i < NumReducedVals; ++i) {
9460         auto *I = cast<Instruction>(ReducedVals[i]);
9461         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9462         VectorizedTree =
9463             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9464       }
9465       for (auto &Pair : ExternallyUsedValues) {
9466         // Add each externally used value to the final reduction.
9467         for (auto *I : Pair.second) {
9468           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9469           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9470                                     Pair.first, "op.extra", I);
9471         }
9472       }
9473 
9474       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9475 
9476       // Mark all scalar reduction ops for deletion, they are replaced by the
9477       // vector reductions.
9478       V.eraseInstructions(IgnoreList);
9479     }
9480     return VectorizedTree;
9481   }
9482 
9483   unsigned numReductionValues() const { return ReducedVals.size(); }
9484 
9485 private:
9486   /// Calculate the cost of a reduction.
9487   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9488                                    Value *FirstReducedVal, unsigned ReduxWidth,
9489                                    FastMathFlags FMF) {
9490     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9491     Type *ScalarTy = FirstReducedVal->getType();
9492     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9493     InstructionCost VectorCost, ScalarCost;
9494     switch (RdxKind) {
9495     case RecurKind::Add:
9496     case RecurKind::Mul:
9497     case RecurKind::Or:
9498     case RecurKind::And:
9499     case RecurKind::Xor:
9500     case RecurKind::FAdd:
9501     case RecurKind::FMul: {
9502       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9503       VectorCost =
9504           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9505       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9506       break;
9507     }
9508     case RecurKind::FMax:
9509     case RecurKind::FMin: {
9510       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9511       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9512       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9513                                                /*IsUnsigned=*/false, CostKind);
9514       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9515       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9516                                            SclCondTy, RdxPred, CostKind) +
9517                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9518                                            SclCondTy, RdxPred, CostKind);
9519       break;
9520     }
9521     case RecurKind::SMax:
9522     case RecurKind::SMin:
9523     case RecurKind::UMax:
9524     case RecurKind::UMin: {
9525       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9526       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9527       bool IsUnsigned =
9528           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9529       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9530                                                CostKind);
9531       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9532       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9533                                            SclCondTy, RdxPred, CostKind) +
9534                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9535                                            SclCondTy, RdxPred, CostKind);
9536       break;
9537     }
9538     default:
9539       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9540     }
9541 
9542     // Scalar cost is repeated for N-1 elements.
9543     ScalarCost *= (ReduxWidth - 1);
9544     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9545                       << " for reduction that starts with " << *FirstReducedVal
9546                       << " (It is a splitting reduction)\n");
9547     return VectorCost - ScalarCost;
9548   }
9549 
9550   /// Emit a horizontal reduction of the vectorized value.
9551   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9552                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9553     assert(VectorizedValue && "Need to have a vectorized tree node");
9554     assert(isPowerOf2_32(ReduxWidth) &&
9555            "We only handle power-of-two reductions for now");
9556     assert(RdxKind != RecurKind::FMulAdd &&
9557            "A call to the llvm.fmuladd intrinsic is not handled yet");
9558 
9559     ++NumVectorInstructions;
9560     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9561   }
9562 };
9563 
9564 } // end anonymous namespace
9565 
9566 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9567   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9568     return cast<FixedVectorType>(IE->getType())->getNumElements();
9569 
9570   unsigned AggregateSize = 1;
9571   auto *IV = cast<InsertValueInst>(InsertInst);
9572   Type *CurrentType = IV->getType();
9573   do {
9574     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9575       for (auto *Elt : ST->elements())
9576         if (Elt != ST->getElementType(0)) // check homogeneity
9577           return None;
9578       AggregateSize *= ST->getNumElements();
9579       CurrentType = ST->getElementType(0);
9580     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9581       AggregateSize *= AT->getNumElements();
9582       CurrentType = AT->getElementType();
9583     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9584       AggregateSize *= VT->getNumElements();
9585       return AggregateSize;
9586     } else if (CurrentType->isSingleValueType()) {
9587       return AggregateSize;
9588     } else {
9589       return None;
9590     }
9591   } while (true);
9592 }
9593 
9594 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9595                                    TargetTransformInfo *TTI,
9596                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9597                                    SmallVectorImpl<Value *> &InsertElts,
9598                                    unsigned OperandOffset) {
9599   do {
9600     Value *InsertedOperand = LastInsertInst->getOperand(1);
9601     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9602     if (!OperandIndex)
9603       return false;
9604     if (isa<InsertElementInst>(InsertedOperand) ||
9605         isa<InsertValueInst>(InsertedOperand)) {
9606       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9607                                   BuildVectorOpds, InsertElts, *OperandIndex))
9608         return false;
9609     } else {
9610       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9611       InsertElts[*OperandIndex] = LastInsertInst;
9612     }
9613     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9614   } while (LastInsertInst != nullptr &&
9615            (isa<InsertValueInst>(LastInsertInst) ||
9616             isa<InsertElementInst>(LastInsertInst)) &&
9617            LastInsertInst->hasOneUse());
9618   return true;
9619 }
9620 
9621 /// Recognize construction of vectors like
9622 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9623 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9624 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9625 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9626 ///  starting from the last insertelement or insertvalue instruction.
9627 ///
9628 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9629 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9630 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9631 ///
9632 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9633 ///
9634 /// \return true if it matches.
9635 static bool findBuildAggregate(Instruction *LastInsertInst,
9636                                TargetTransformInfo *TTI,
9637                                SmallVectorImpl<Value *> &BuildVectorOpds,
9638                                SmallVectorImpl<Value *> &InsertElts) {
9639 
9640   assert((isa<InsertElementInst>(LastInsertInst) ||
9641           isa<InsertValueInst>(LastInsertInst)) &&
9642          "Expected insertelement or insertvalue instruction!");
9643 
9644   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9645          "Expected empty result vectors!");
9646 
9647   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9648   if (!AggregateSize)
9649     return false;
9650   BuildVectorOpds.resize(*AggregateSize);
9651   InsertElts.resize(*AggregateSize);
9652 
9653   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9654                              0)) {
9655     llvm::erase_value(BuildVectorOpds, nullptr);
9656     llvm::erase_value(InsertElts, nullptr);
9657     if (BuildVectorOpds.size() >= 2)
9658       return true;
9659   }
9660 
9661   return false;
9662 }
9663 
9664 /// Try and get a reduction value from a phi node.
9665 ///
9666 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9667 /// if they come from either \p ParentBB or a containing loop latch.
9668 ///
9669 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9670 /// if not possible.
9671 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9672                                 BasicBlock *ParentBB, LoopInfo *LI) {
9673   // There are situations where the reduction value is not dominated by the
9674   // reduction phi. Vectorizing such cases has been reported to cause
9675   // miscompiles. See PR25787.
9676   auto DominatedReduxValue = [&](Value *R) {
9677     return isa<Instruction>(R) &&
9678            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9679   };
9680 
9681   Value *Rdx = nullptr;
9682 
9683   // Return the incoming value if it comes from the same BB as the phi node.
9684   if (P->getIncomingBlock(0) == ParentBB) {
9685     Rdx = P->getIncomingValue(0);
9686   } else if (P->getIncomingBlock(1) == ParentBB) {
9687     Rdx = P->getIncomingValue(1);
9688   }
9689 
9690   if (Rdx && DominatedReduxValue(Rdx))
9691     return Rdx;
9692 
9693   // Otherwise, check whether we have a loop latch to look at.
9694   Loop *BBL = LI->getLoopFor(ParentBB);
9695   if (!BBL)
9696     return nullptr;
9697   BasicBlock *BBLatch = BBL->getLoopLatch();
9698   if (!BBLatch)
9699     return nullptr;
9700 
9701   // There is a loop latch, return the incoming value if it comes from
9702   // that. This reduction pattern occasionally turns up.
9703   if (P->getIncomingBlock(0) == BBLatch) {
9704     Rdx = P->getIncomingValue(0);
9705   } else if (P->getIncomingBlock(1) == BBLatch) {
9706     Rdx = P->getIncomingValue(1);
9707   }
9708 
9709   if (Rdx && DominatedReduxValue(Rdx))
9710     return Rdx;
9711 
9712   return nullptr;
9713 }
9714 
9715 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9716   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9717     return true;
9718   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9719     return true;
9720   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9721     return true;
9722   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9723     return true;
9724   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9725     return true;
9726   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9727     return true;
9728   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9729     return true;
9730   return false;
9731 }
9732 
9733 /// Attempt to reduce a horizontal reduction.
9734 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9735 /// with reduction operators \a Root (or one of its operands) in a basic block
9736 /// \a BB, then check if it can be done. If horizontal reduction is not found
9737 /// and root instruction is a binary operation, vectorization of the operands is
9738 /// attempted.
9739 /// \returns true if a horizontal reduction was matched and reduced or operands
9740 /// of one of the binary instruction were vectorized.
9741 /// \returns false if a horizontal reduction was not matched (or not possible)
9742 /// or no vectorization of any binary operation feeding \a Root instruction was
9743 /// performed.
9744 static bool tryToVectorizeHorReductionOrInstOperands(
9745     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9746     TargetTransformInfo *TTI,
9747     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9748   if (!ShouldVectorizeHor)
9749     return false;
9750 
9751   if (!Root)
9752     return false;
9753 
9754   if (Root->getParent() != BB || isa<PHINode>(Root))
9755     return false;
9756   // Start analysis starting from Root instruction. If horizontal reduction is
9757   // found, try to vectorize it. If it is not a horizontal reduction or
9758   // vectorization is not possible or not effective, and currently analyzed
9759   // instruction is a binary operation, try to vectorize the operands, using
9760   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9761   // the same procedure considering each operand as a possible root of the
9762   // horizontal reduction.
9763   // Interrupt the process if the Root instruction itself was vectorized or all
9764   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9765   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9766   // CmpInsts so we can skip extra attempts in
9767   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9768   std::queue<std::pair<Instruction *, unsigned>> Stack;
9769   Stack.emplace(Root, 0);
9770   SmallPtrSet<Value *, 8> VisitedInstrs;
9771   SmallVector<WeakTrackingVH> PostponedInsts;
9772   bool Res = false;
9773   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9774                                      Value *&B1) -> Value * {
9775     bool IsBinop = matchRdxBop(Inst, B0, B1);
9776     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9777     if (IsBinop || IsSelect) {
9778       HorizontalReduction HorRdx;
9779       if (HorRdx.matchAssociativeReduction(P, Inst))
9780         return HorRdx.tryToReduce(R, TTI);
9781     }
9782     return nullptr;
9783   };
9784   while (!Stack.empty()) {
9785     Instruction *Inst;
9786     unsigned Level;
9787     std::tie(Inst, Level) = Stack.front();
9788     Stack.pop();
9789     // Do not try to analyze instruction that has already been vectorized.
9790     // This may happen when we vectorize instruction operands on a previous
9791     // iteration while stack was populated before that happened.
9792     if (R.isDeleted(Inst))
9793       continue;
9794     Value *B0 = nullptr, *B1 = nullptr;
9795     if (Value *V = TryToReduce(Inst, B0, B1)) {
9796       Res = true;
9797       // Set P to nullptr to avoid re-analysis of phi node in
9798       // matchAssociativeReduction function unless this is the root node.
9799       P = nullptr;
9800       if (auto *I = dyn_cast<Instruction>(V)) {
9801         // Try to find another reduction.
9802         Stack.emplace(I, Level);
9803         continue;
9804       }
9805     } else {
9806       bool IsBinop = B0 && B1;
9807       if (P && IsBinop) {
9808         Inst = dyn_cast<Instruction>(B0);
9809         if (Inst == P)
9810           Inst = dyn_cast<Instruction>(B1);
9811         if (!Inst) {
9812           // Set P to nullptr to avoid re-analysis of phi node in
9813           // matchAssociativeReduction function unless this is the root node.
9814           P = nullptr;
9815           continue;
9816         }
9817       }
9818       // Set P to nullptr to avoid re-analysis of phi node in
9819       // matchAssociativeReduction function unless this is the root node.
9820       P = nullptr;
9821       // Do not try to vectorize CmpInst operands, this is done separately.
9822       // Final attempt for binop args vectorization should happen after the loop
9823       // to try to find reductions.
9824       if (!isa<CmpInst>(Inst))
9825         PostponedInsts.push_back(Inst);
9826     }
9827 
9828     // Try to vectorize operands.
9829     // Continue analysis for the instruction from the same basic block only to
9830     // save compile time.
9831     if (++Level < RecursionMaxDepth)
9832       for (auto *Op : Inst->operand_values())
9833         if (VisitedInstrs.insert(Op).second)
9834           if (auto *I = dyn_cast<Instruction>(Op))
9835             // Do not try to vectorize CmpInst operands,  this is done
9836             // separately.
9837             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9838                 I->getParent() == BB)
9839               Stack.emplace(I, Level);
9840   }
9841   // Try to vectorized binops where reductions were not found.
9842   for (Value *V : PostponedInsts)
9843     if (auto *Inst = dyn_cast<Instruction>(V))
9844       if (!R.isDeleted(Inst))
9845         Res |= Vectorize(Inst, R);
9846   return Res;
9847 }
9848 
9849 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9850                                                  BasicBlock *BB, BoUpSLP &R,
9851                                                  TargetTransformInfo *TTI) {
9852   auto *I = dyn_cast_or_null<Instruction>(V);
9853   if (!I)
9854     return false;
9855 
9856   if (!isa<BinaryOperator>(I))
9857     P = nullptr;
9858   // Try to match and vectorize a horizontal reduction.
9859   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9860     return tryToVectorize(I, R);
9861   };
9862   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9863                                                   ExtraVectorization);
9864 }
9865 
9866 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9867                                                  BasicBlock *BB, BoUpSLP &R) {
9868   const DataLayout &DL = BB->getModule()->getDataLayout();
9869   if (!R.canMapToVector(IVI->getType(), DL))
9870     return false;
9871 
9872   SmallVector<Value *, 16> BuildVectorOpds;
9873   SmallVector<Value *, 16> BuildVectorInsts;
9874   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9875     return false;
9876 
9877   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9878   // Aggregate value is unlikely to be processed in vector register.
9879   return tryToVectorizeList(BuildVectorOpds, R);
9880 }
9881 
9882 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9883                                                    BasicBlock *BB, BoUpSLP &R) {
9884   SmallVector<Value *, 16> BuildVectorInsts;
9885   SmallVector<Value *, 16> BuildVectorOpds;
9886   SmallVector<int> Mask;
9887   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9888       (llvm::all_of(
9889            BuildVectorOpds,
9890            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9891        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9892     return false;
9893 
9894   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9895   return tryToVectorizeList(BuildVectorInsts, R);
9896 }
9897 
9898 template <typename T>
9899 static bool
9900 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9901                        function_ref<unsigned(T *)> Limit,
9902                        function_ref<bool(T *, T *)> Comparator,
9903                        function_ref<bool(T *, T *)> AreCompatible,
9904                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9905                        bool LimitForRegisterSize) {
9906   bool Changed = false;
9907   // Sort by type, parent, operands.
9908   stable_sort(Incoming, Comparator);
9909 
9910   // Try to vectorize elements base on their type.
9911   SmallVector<T *> Candidates;
9912   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9913     // Look for the next elements with the same type, parent and operand
9914     // kinds.
9915     auto *SameTypeIt = IncIt;
9916     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9917       ++SameTypeIt;
9918 
9919     // Try to vectorize them.
9920     unsigned NumElts = (SameTypeIt - IncIt);
9921     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9922                       << NumElts << ")\n");
9923     // The vectorization is a 3-state attempt:
9924     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9925     // size of maximal register at first.
9926     // 2. Try to vectorize remaining instructions with the same type, if
9927     // possible. This may result in the better vectorization results rather than
9928     // if we try just to vectorize instructions with the same/alternate opcodes.
9929     // 3. Final attempt to try to vectorize all instructions with the
9930     // same/alternate ops only, this may result in some extra final
9931     // vectorization.
9932     if (NumElts > 1 &&
9933         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9934       // Success start over because instructions might have been changed.
9935       Changed = true;
9936     } else if (NumElts < Limit(*IncIt) &&
9937                (Candidates.empty() ||
9938                 Candidates.front()->getType() == (*IncIt)->getType())) {
9939       Candidates.append(IncIt, std::next(IncIt, NumElts));
9940     }
9941     // Final attempt to vectorize instructions with the same types.
9942     if (Candidates.size() > 1 &&
9943         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9944       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9945         // Success start over because instructions might have been changed.
9946         Changed = true;
9947       } else if (LimitForRegisterSize) {
9948         // Try to vectorize using small vectors.
9949         for (auto *It = Candidates.begin(), *End = Candidates.end();
9950              It != End;) {
9951           auto *SameTypeIt = It;
9952           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9953             ++SameTypeIt;
9954           unsigned NumElts = (SameTypeIt - It);
9955           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9956                                             /*LimitForRegisterSize=*/false))
9957             Changed = true;
9958           It = SameTypeIt;
9959         }
9960       }
9961       Candidates.clear();
9962     }
9963 
9964     // Start over at the next instruction of a different type (or the end).
9965     IncIt = SameTypeIt;
9966   }
9967   return Changed;
9968 }
9969 
9970 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9971 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9972 /// operands. If IsCompatibility is false, function implements strict weak
9973 /// ordering relation between two cmp instructions, returning true if the first
9974 /// instruction is "less" than the second, i.e. its predicate is less than the
9975 /// predicate of the second or the operands IDs are less than the operands IDs
9976 /// of the second cmp instruction.
9977 template <bool IsCompatibility>
9978 static bool compareCmp(Value *V, Value *V2,
9979                        function_ref<bool(Instruction *)> IsDeleted) {
9980   auto *CI1 = cast<CmpInst>(V);
9981   auto *CI2 = cast<CmpInst>(V2);
9982   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9983     return false;
9984   if (CI1->getOperand(0)->getType()->getTypeID() <
9985       CI2->getOperand(0)->getType()->getTypeID())
9986     return !IsCompatibility;
9987   if (CI1->getOperand(0)->getType()->getTypeID() >
9988       CI2->getOperand(0)->getType()->getTypeID())
9989     return false;
9990   CmpInst::Predicate Pred1 = CI1->getPredicate();
9991   CmpInst::Predicate Pred2 = CI2->getPredicate();
9992   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9993   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9994   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9995   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9996   if (BasePred1 < BasePred2)
9997     return !IsCompatibility;
9998   if (BasePred1 > BasePred2)
9999     return false;
10000   // Compare operands.
10001   bool LEPreds = Pred1 <= Pred2;
10002   bool GEPreds = Pred1 >= Pred2;
10003   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10004     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10005     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10006     if (Op1->getValueID() < Op2->getValueID())
10007       return !IsCompatibility;
10008     if (Op1->getValueID() > Op2->getValueID())
10009       return false;
10010     if (auto *I1 = dyn_cast<Instruction>(Op1))
10011       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10012         if (I1->getParent() != I2->getParent())
10013           return false;
10014         InstructionsState S = getSameOpcode({I1, I2});
10015         if (S.getOpcode())
10016           continue;
10017         return false;
10018       }
10019   }
10020   return IsCompatibility;
10021 }
10022 
10023 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10024     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10025     bool AtTerminator) {
10026   bool OpsChanged = false;
10027   SmallVector<Instruction *, 4> PostponedCmps;
10028   for (auto *I : reverse(Instructions)) {
10029     if (R.isDeleted(I))
10030       continue;
10031     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10032       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10033     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10034       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10035     else if (isa<CmpInst>(I))
10036       PostponedCmps.push_back(I);
10037   }
10038   if (AtTerminator) {
10039     // Try to find reductions first.
10040     for (Instruction *I : PostponedCmps) {
10041       if (R.isDeleted(I))
10042         continue;
10043       for (Value *Op : I->operands())
10044         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10045     }
10046     // Try to vectorize operands as vector bundles.
10047     for (Instruction *I : PostponedCmps) {
10048       if (R.isDeleted(I))
10049         continue;
10050       OpsChanged |= tryToVectorize(I, R);
10051     }
10052     // Try to vectorize list of compares.
10053     // Sort by type, compare predicate, etc.
10054     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10055       return compareCmp<false>(V, V2,
10056                                [&R](Instruction *I) { return R.isDeleted(I); });
10057     };
10058 
10059     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10060       if (V1 == V2)
10061         return true;
10062       return compareCmp<true>(V1, V2,
10063                               [&R](Instruction *I) { return R.isDeleted(I); });
10064     };
10065     auto Limit = [&R](Value *V) {
10066       unsigned EltSize = R.getVectorElementSize(V);
10067       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10068     };
10069 
10070     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10071     OpsChanged |= tryToVectorizeSequence<Value>(
10072         Vals, Limit, CompareSorter, AreCompatibleCompares,
10073         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10074           // Exclude possible reductions from other blocks.
10075           bool ArePossiblyReducedInOtherBlock =
10076               any_of(Candidates, [](Value *V) {
10077                 return any_of(V->users(), [V](User *U) {
10078                   return isa<SelectInst>(U) &&
10079                          cast<SelectInst>(U)->getParent() !=
10080                              cast<Instruction>(V)->getParent();
10081                 });
10082               });
10083           if (ArePossiblyReducedInOtherBlock)
10084             return false;
10085           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10086         },
10087         /*LimitForRegisterSize=*/true);
10088     Instructions.clear();
10089   } else {
10090     // Insert in reverse order since the PostponedCmps vector was filled in
10091     // reverse order.
10092     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10093   }
10094   return OpsChanged;
10095 }
10096 
10097 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10098   bool Changed = false;
10099   SmallVector<Value *, 4> Incoming;
10100   SmallPtrSet<Value *, 16> VisitedInstrs;
10101   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10102   // node. Allows better to identify the chains that can be vectorized in the
10103   // better way.
10104   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10105   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10106     assert(isValidElementType(V1->getType()) &&
10107            isValidElementType(V2->getType()) &&
10108            "Expected vectorizable types only.");
10109     // It is fine to compare type IDs here, since we expect only vectorizable
10110     // types, like ints, floats and pointers, we don't care about other type.
10111     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10112       return true;
10113     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10114       return false;
10115     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10116     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10117     if (Opcodes1.size() < Opcodes2.size())
10118       return true;
10119     if (Opcodes1.size() > Opcodes2.size())
10120       return false;
10121     Optional<bool> ConstOrder;
10122     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10123       // Undefs are compatible with any other value.
10124       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10125         if (!ConstOrder)
10126           ConstOrder =
10127               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10128         continue;
10129       }
10130       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10131         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10132           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10133           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10134           if (!NodeI1)
10135             return NodeI2 != nullptr;
10136           if (!NodeI2)
10137             return false;
10138           assert((NodeI1 == NodeI2) ==
10139                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10140                  "Different nodes should have different DFS numbers");
10141           if (NodeI1 != NodeI2)
10142             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10143           InstructionsState S = getSameOpcode({I1, I2});
10144           if (S.getOpcode())
10145             continue;
10146           return I1->getOpcode() < I2->getOpcode();
10147         }
10148       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10149         if (!ConstOrder)
10150           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10151         continue;
10152       }
10153       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10154         return true;
10155       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10156         return false;
10157     }
10158     return ConstOrder && *ConstOrder;
10159   };
10160   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10161     if (V1 == V2)
10162       return true;
10163     if (V1->getType() != V2->getType())
10164       return false;
10165     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10166     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10167     if (Opcodes1.size() != Opcodes2.size())
10168       return false;
10169     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10170       // Undefs are compatible with any other value.
10171       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10172         continue;
10173       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10174         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10175           if (I1->getParent() != I2->getParent())
10176             return false;
10177           InstructionsState S = getSameOpcode({I1, I2});
10178           if (S.getOpcode())
10179             continue;
10180           return false;
10181         }
10182       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10183         continue;
10184       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10185         return false;
10186     }
10187     return true;
10188   };
10189   auto Limit = [&R](Value *V) {
10190     unsigned EltSize = R.getVectorElementSize(V);
10191     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10192   };
10193 
10194   bool HaveVectorizedPhiNodes = false;
10195   do {
10196     // Collect the incoming values from the PHIs.
10197     Incoming.clear();
10198     for (Instruction &I : *BB) {
10199       PHINode *P = dyn_cast<PHINode>(&I);
10200       if (!P)
10201         break;
10202 
10203       // No need to analyze deleted, vectorized and non-vectorizable
10204       // instructions.
10205       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10206           isValidElementType(P->getType()))
10207         Incoming.push_back(P);
10208     }
10209 
10210     // Find the corresponding non-phi nodes for better matching when trying to
10211     // build the tree.
10212     for (Value *V : Incoming) {
10213       SmallVectorImpl<Value *> &Opcodes =
10214           PHIToOpcodes.try_emplace(V).first->getSecond();
10215       if (!Opcodes.empty())
10216         continue;
10217       SmallVector<Value *, 4> Nodes(1, V);
10218       SmallPtrSet<Value *, 4> Visited;
10219       while (!Nodes.empty()) {
10220         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10221         if (!Visited.insert(PHI).second)
10222           continue;
10223         for (Value *V : PHI->incoming_values()) {
10224           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10225             Nodes.push_back(PHI1);
10226             continue;
10227           }
10228           Opcodes.emplace_back(V);
10229         }
10230       }
10231     }
10232 
10233     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10234         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10235         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10236           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10237         },
10238         /*LimitForRegisterSize=*/true);
10239     Changed |= HaveVectorizedPhiNodes;
10240     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10241   } while (HaveVectorizedPhiNodes);
10242 
10243   VisitedInstrs.clear();
10244 
10245   SmallVector<Instruction *, 8> PostProcessInstructions;
10246   SmallDenseSet<Instruction *, 4> KeyNodes;
10247   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10248     // Skip instructions with scalable type. The num of elements is unknown at
10249     // compile-time for scalable type.
10250     if (isa<ScalableVectorType>(it->getType()))
10251       continue;
10252 
10253     // Skip instructions marked for the deletion.
10254     if (R.isDeleted(&*it))
10255       continue;
10256     // We may go through BB multiple times so skip the one we have checked.
10257     if (!VisitedInstrs.insert(&*it).second) {
10258       if (it->use_empty() && KeyNodes.contains(&*it) &&
10259           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10260                                       it->isTerminator())) {
10261         // We would like to start over since some instructions are deleted
10262         // and the iterator may become invalid value.
10263         Changed = true;
10264         it = BB->begin();
10265         e = BB->end();
10266       }
10267       continue;
10268     }
10269 
10270     if (isa<DbgInfoIntrinsic>(it))
10271       continue;
10272 
10273     // Try to vectorize reductions that use PHINodes.
10274     if (PHINode *P = dyn_cast<PHINode>(it)) {
10275       // Check that the PHI is a reduction PHI.
10276       if (P->getNumIncomingValues() == 2) {
10277         // Try to match and vectorize a horizontal reduction.
10278         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10279                                      TTI)) {
10280           Changed = true;
10281           it = BB->begin();
10282           e = BB->end();
10283           continue;
10284         }
10285       }
10286       // Try to vectorize the incoming values of the PHI, to catch reductions
10287       // that feed into PHIs.
10288       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10289         // Skip if the incoming block is the current BB for now. Also, bypass
10290         // unreachable IR for efficiency and to avoid crashing.
10291         // TODO: Collect the skipped incoming values and try to vectorize them
10292         // after processing BB.
10293         if (BB == P->getIncomingBlock(I) ||
10294             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10295           continue;
10296 
10297         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10298                                             P->getIncomingBlock(I), R, TTI);
10299       }
10300       continue;
10301     }
10302 
10303     // Ran into an instruction without users, like terminator, or function call
10304     // with ignored return value, store. Ignore unused instructions (basing on
10305     // instruction type, except for CallInst and InvokeInst).
10306     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10307                             isa<InvokeInst>(it))) {
10308       KeyNodes.insert(&*it);
10309       bool OpsChanged = false;
10310       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10311         for (auto *V : it->operand_values()) {
10312           // Try to match and vectorize a horizontal reduction.
10313           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10314         }
10315       }
10316       // Start vectorization of post-process list of instructions from the
10317       // top-tree instructions to try to vectorize as many instructions as
10318       // possible.
10319       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10320                                                 it->isTerminator());
10321       if (OpsChanged) {
10322         // We would like to start over since some instructions are deleted
10323         // and the iterator may become invalid value.
10324         Changed = true;
10325         it = BB->begin();
10326         e = BB->end();
10327         continue;
10328       }
10329     }
10330 
10331     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10332         isa<InsertValueInst>(it))
10333       PostProcessInstructions.push_back(&*it);
10334   }
10335 
10336   return Changed;
10337 }
10338 
10339 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10340   auto Changed = false;
10341   for (auto &Entry : GEPs) {
10342     // If the getelementptr list has fewer than two elements, there's nothing
10343     // to do.
10344     if (Entry.second.size() < 2)
10345       continue;
10346 
10347     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10348                       << Entry.second.size() << ".\n");
10349 
10350     // Process the GEP list in chunks suitable for the target's supported
10351     // vector size. If a vector register can't hold 1 element, we are done. We
10352     // are trying to vectorize the index computations, so the maximum number of
10353     // elements is based on the size of the index expression, rather than the
10354     // size of the GEP itself (the target's pointer size).
10355     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10356     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10357     if (MaxVecRegSize < EltSize)
10358       continue;
10359 
10360     unsigned MaxElts = MaxVecRegSize / EltSize;
10361     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10362       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10363       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10364 
10365       // Initialize a set a candidate getelementptrs. Note that we use a
10366       // SetVector here to preserve program order. If the index computations
10367       // are vectorizable and begin with loads, we want to minimize the chance
10368       // of having to reorder them later.
10369       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10370 
10371       // Some of the candidates may have already been vectorized after we
10372       // initially collected them. If so, they are marked as deleted, so remove
10373       // them from the set of candidates.
10374       Candidates.remove_if(
10375           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10376 
10377       // Remove from the set of candidates all pairs of getelementptrs with
10378       // constant differences. Such getelementptrs are likely not good
10379       // candidates for vectorization in a bottom-up phase since one can be
10380       // computed from the other. We also ensure all candidate getelementptr
10381       // indices are unique.
10382       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10383         auto *GEPI = GEPList[I];
10384         if (!Candidates.count(GEPI))
10385           continue;
10386         auto *SCEVI = SE->getSCEV(GEPList[I]);
10387         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10388           auto *GEPJ = GEPList[J];
10389           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10390           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10391             Candidates.remove(GEPI);
10392             Candidates.remove(GEPJ);
10393           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10394             Candidates.remove(GEPJ);
10395           }
10396         }
10397       }
10398 
10399       // We break out of the above computation as soon as we know there are
10400       // fewer than two candidates remaining.
10401       if (Candidates.size() < 2)
10402         continue;
10403 
10404       // Add the single, non-constant index of each candidate to the bundle. We
10405       // ensured the indices met these constraints when we originally collected
10406       // the getelementptrs.
10407       SmallVector<Value *, 16> Bundle(Candidates.size());
10408       auto BundleIndex = 0u;
10409       for (auto *V : Candidates) {
10410         auto *GEP = cast<GetElementPtrInst>(V);
10411         auto *GEPIdx = GEP->idx_begin()->get();
10412         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10413         Bundle[BundleIndex++] = GEPIdx;
10414       }
10415 
10416       // Try and vectorize the indices. We are currently only interested in
10417       // gather-like cases of the form:
10418       //
10419       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10420       //
10421       // where the loads of "a", the loads of "b", and the subtractions can be
10422       // performed in parallel. It's likely that detecting this pattern in a
10423       // bottom-up phase will be simpler and less costly than building a
10424       // full-blown top-down phase beginning at the consecutive loads.
10425       Changed |= tryToVectorizeList(Bundle, R);
10426     }
10427   }
10428   return Changed;
10429 }
10430 
10431 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10432   bool Changed = false;
10433   // Sort by type, base pointers and values operand. Value operands must be
10434   // compatible (have the same opcode, same parent), otherwise it is
10435   // definitely not profitable to try to vectorize them.
10436   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10437     if (V->getPointerOperandType()->getTypeID() <
10438         V2->getPointerOperandType()->getTypeID())
10439       return true;
10440     if (V->getPointerOperandType()->getTypeID() >
10441         V2->getPointerOperandType()->getTypeID())
10442       return false;
10443     // UndefValues are compatible with all other values.
10444     if (isa<UndefValue>(V->getValueOperand()) ||
10445         isa<UndefValue>(V2->getValueOperand()))
10446       return false;
10447     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10448       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10449         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10450             DT->getNode(I1->getParent());
10451         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10452             DT->getNode(I2->getParent());
10453         assert(NodeI1 && "Should only process reachable instructions");
10454         assert(NodeI1 && "Should only process reachable instructions");
10455         assert((NodeI1 == NodeI2) ==
10456                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10457                "Different nodes should have different DFS numbers");
10458         if (NodeI1 != NodeI2)
10459           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10460         InstructionsState S = getSameOpcode({I1, I2});
10461         if (S.getOpcode())
10462           return false;
10463         return I1->getOpcode() < I2->getOpcode();
10464       }
10465     if (isa<Constant>(V->getValueOperand()) &&
10466         isa<Constant>(V2->getValueOperand()))
10467       return false;
10468     return V->getValueOperand()->getValueID() <
10469            V2->getValueOperand()->getValueID();
10470   };
10471 
10472   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10473     if (V1 == V2)
10474       return true;
10475     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10476       return false;
10477     // Undefs are compatible with any other value.
10478     if (isa<UndefValue>(V1->getValueOperand()) ||
10479         isa<UndefValue>(V2->getValueOperand()))
10480       return true;
10481     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10482       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10483         if (I1->getParent() != I2->getParent())
10484           return false;
10485         InstructionsState S = getSameOpcode({I1, I2});
10486         return S.getOpcode() > 0;
10487       }
10488     if (isa<Constant>(V1->getValueOperand()) &&
10489         isa<Constant>(V2->getValueOperand()))
10490       return true;
10491     return V1->getValueOperand()->getValueID() ==
10492            V2->getValueOperand()->getValueID();
10493   };
10494   auto Limit = [&R, this](StoreInst *SI) {
10495     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10496     return R.getMinVF(EltSize);
10497   };
10498 
10499   // Attempt to sort and vectorize each of the store-groups.
10500   for (auto &Pair : Stores) {
10501     if (Pair.second.size() < 2)
10502       continue;
10503 
10504     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10505                       << Pair.second.size() << ".\n");
10506 
10507     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10508       continue;
10509 
10510     Changed |= tryToVectorizeSequence<StoreInst>(
10511         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10512         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10513           return vectorizeStores(Candidates, R);
10514         },
10515         /*LimitForRegisterSize=*/false);
10516   }
10517   return Changed;
10518 }
10519 
10520 char SLPVectorizer::ID = 0;
10521 
10522 static const char lv_name[] = "SLP Vectorizer";
10523 
10524 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10525 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10526 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10527 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10528 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10529 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10530 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10531 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10532 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10533 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10534 
10535 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10536