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