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