1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
732   int Index = Offset;
733   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
734     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
735       auto *VT = cast<FixedVectorType>(IE->getType());
736       if (CI->getValue().uge(VT->getNumElements()))
737         return UndefMaskElem;
738       Index *= VT->getNumElements();
739       Index += CI->getZExtValue();
740       return Index;
741     }
742     if (isa<UndefValue>(IE->getOperand(2)))
743       return UndefMaskElem;
744     return None;
745   }
746 
747   auto *IV = cast<InsertValueInst>(InsertInst);
748   Type *CurrentType = IV->getType();
749   for (unsigned I : IV->indices()) {
750     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
751       Index *= ST->getNumElements();
752       CurrentType = ST->getElementType(I);
753     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
754       Index *= AT->getNumElements();
755       CurrentType = AT->getElementType();
756     } else {
757       return None;
758     }
759     Index += I;
760   }
761   return Index;
762 }
763 
764 /// Reorders the list of scalars in accordance with the given \p Order and then
765 /// the \p Mask. \p Order - is the original order of the scalars, need to
766 /// reorder scalars into an unordered state at first according to the given
767 /// order. Then the ordered scalars are shuffled once again in accordance with
768 /// the provided mask.
769 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
770                            ArrayRef<int> Mask) {
771   assert(!Mask.empty() && "Expected non-empty mask.");
772   SmallVector<Value *> Prev(Scalars.size(),
773                             UndefValue::get(Scalars.front()->getType()));
774   Prev.swap(Scalars);
775   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
776     if (Mask[I] != UndefMaskElem)
777       Scalars[Mask[I]] = Prev[I];
778 }
779 
780 namespace slpvectorizer {
781 
782 /// Bottom Up SLP Vectorizer.
783 class BoUpSLP {
784   struct TreeEntry;
785   struct ScheduleData;
786 
787 public:
788   using ValueList = SmallVector<Value *, 8>;
789   using InstrList = SmallVector<Instruction *, 16>;
790   using ValueSet = SmallPtrSet<Value *, 16>;
791   using StoreList = SmallVector<StoreInst *, 8>;
792   using ExtraValueToDebugLocsMap =
793       MapVector<Value *, SmallVector<Instruction *, 2>>;
794   using OrdersType = SmallVector<unsigned, 4>;
795 
796   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
797           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
798           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
799           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
800       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
801         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
802     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
803     // Use the vector register size specified by the target unless overridden
804     // by a command-line option.
805     // TODO: It would be better to limit the vectorization factor based on
806     //       data type rather than just register size. For example, x86 AVX has
807     //       256-bit registers, but it does not support integer operations
808     //       at that width (that requires AVX2).
809     if (MaxVectorRegSizeOption.getNumOccurrences())
810       MaxVecRegSize = MaxVectorRegSizeOption;
811     else
812       MaxVecRegSize =
813           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
814               .getFixedSize();
815 
816     if (MinVectorRegSizeOption.getNumOccurrences())
817       MinVecRegSize = MinVectorRegSizeOption;
818     else
819       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
820   }
821 
822   /// Vectorize the tree that starts with the elements in \p VL.
823   /// Returns the vectorized root.
824   Value *vectorizeTree();
825 
826   /// Vectorize the tree but with the list of externally used values \p
827   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
828   /// generated extractvalue instructions.
829   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
830 
831   /// \returns the cost incurred by unwanted spills and fills, caused by
832   /// holding live values over call sites.
833   InstructionCost getSpillCost() const;
834 
835   /// \returns the vectorization cost of the subtree that starts at \p VL.
836   /// A negative number means that this is profitable.
837   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
838 
839   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
840   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
841   void buildTree(ArrayRef<Value *> Roots,
842                  ArrayRef<Value *> UserIgnoreLst = None);
843 
844   /// Builds external uses of the vectorized scalars, i.e. the list of
845   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
846   /// ExternallyUsedValues contains additional list of external uses to handle
847   /// vectorization of reductions.
848   void
849   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
850 
851   /// Clear the internal data structures that are created by 'buildTree'.
852   void deleteTree() {
853     VectorizableTree.clear();
854     ScalarToTreeEntry.clear();
855     MustGather.clear();
856     ExternalUses.clear();
857     for (auto &Iter : BlocksSchedules) {
858       BlockScheduling *BS = Iter.second.get();
859       BS->clear();
860     }
861     MinBWs.clear();
862     InstrElementSize.clear();
863   }
864 
865   unsigned getTreeSize() const { return VectorizableTree.size(); }
866 
867   /// Perform LICM and CSE on the newly generated gather sequences.
868   void optimizeGatherSequence();
869 
870   /// Checks if the specified gather tree entry \p TE can be represented as a
871   /// shuffled vector entry + (possibly) permutation with other gathers. It
872   /// implements the checks only for possibly ordered scalars (Loads,
873   /// ExtractElement, ExtractValue), which can be part of the graph.
874   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
875 
876   /// Gets reordering data for the given tree entry. If the entry is vectorized
877   /// - just return ReorderIndices, otherwise check if the scalars can be
878   /// reordered and return the most optimal order.
879   /// \param TopToBottom If true, include the order of vectorized stores and
880   /// insertelement nodes, otherwise skip them.
881   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
882 
883   /// Reorders the current graph to the most profitable order starting from the
884   /// root node to the leaf nodes. The best order is chosen only from the nodes
885   /// of the same size (vectorization factor). Smaller nodes are considered
886   /// parts of subgraph with smaller VF and they are reordered independently. We
887   /// can make it because we still need to extend smaller nodes to the wider VF
888   /// and we can merge reordering shuffles with the widening shuffles.
889   void reorderTopToBottom();
890 
891   /// Reorders the current graph to the most profitable order starting from
892   /// leaves to the root. It allows to rotate small subgraphs and reduce the
893   /// number of reshuffles if the leaf nodes use the same order. In this case we
894   /// can merge the orders and just shuffle user node instead of shuffling its
895   /// operands. Plus, even the leaf nodes have different orders, it allows to
896   /// sink reordering in the graph closer to the root node and merge it later
897   /// during analysis.
898   void reorderBottomToTop(bool IgnoreReorder = false);
899 
900   /// \return The vector element size in bits to use when vectorizing the
901   /// expression tree ending at \p V. If V is a store, the size is the width of
902   /// the stored value. Otherwise, the size is the width of the largest loaded
903   /// value reaching V. This method is used by the vectorizer to calculate
904   /// vectorization factors.
905   unsigned getVectorElementSize(Value *V);
906 
907   /// Compute the minimum type sizes required to represent the entries in a
908   /// vectorizable tree.
909   void computeMinimumValueSizes();
910 
911   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
912   unsigned getMaxVecRegSize() const {
913     return MaxVecRegSize;
914   }
915 
916   // \returns minimum vector register size as set by cl::opt.
917   unsigned getMinVecRegSize() const {
918     return MinVecRegSize;
919   }
920 
921   unsigned getMinVF(unsigned Sz) const {
922     return std::max(2U, getMinVecRegSize() / Sz);
923   }
924 
925   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
926     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
927       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
928     return MaxVF ? MaxVF : UINT_MAX;
929   }
930 
931   /// Check if homogeneous aggregate is isomorphic to some VectorType.
932   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
933   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
934   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
935   ///
936   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
937   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
938 
939   /// \returns True if the VectorizableTree is both tiny and not fully
940   /// vectorizable. We do not vectorize such trees.
941   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
942 
943   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
944   /// can be load combined in the backend. Load combining may not be allowed in
945   /// the IR optimizer, so we do not want to alter the pattern. For example,
946   /// partially transforming a scalar bswap() pattern into vector code is
947   /// effectively impossible for the backend to undo.
948   /// TODO: If load combining is allowed in the IR optimizer, this analysis
949   ///       may not be necessary.
950   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
951 
952   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
953   /// can be load combined in the backend. Load combining may not be allowed in
954   /// the IR optimizer, so we do not want to alter the pattern. For example,
955   /// partially transforming a scalar bswap() pattern into vector code is
956   /// effectively impossible for the backend to undo.
957   /// TODO: If load combining is allowed in the IR optimizer, this analysis
958   ///       may not be necessary.
959   bool isLoadCombineCandidate() const;
960 
961   OptimizationRemarkEmitter *getORE() { return ORE; }
962 
963   /// This structure holds any data we need about the edges being traversed
964   /// during buildTree_rec(). We keep track of:
965   /// (i) the user TreeEntry index, and
966   /// (ii) the index of the edge.
967   struct EdgeInfo {
968     EdgeInfo() = default;
969     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
970         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
971     /// The user TreeEntry.
972     TreeEntry *UserTE = nullptr;
973     /// The operand index of the use.
974     unsigned EdgeIdx = UINT_MAX;
975 #ifndef NDEBUG
976     friend inline raw_ostream &operator<<(raw_ostream &OS,
977                                           const BoUpSLP::EdgeInfo &EI) {
978       EI.dump(OS);
979       return OS;
980     }
981     /// Debug print.
982     void dump(raw_ostream &OS) const {
983       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
984          << " EdgeIdx:" << EdgeIdx << "}";
985     }
986     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
987 #endif
988   };
989 
990   /// A helper data structure to hold the operands of a vector of instructions.
991   /// This supports a fixed vector length for all operand vectors.
992   class VLOperands {
993     /// For each operand we need (i) the value, and (ii) the opcode that it
994     /// would be attached to if the expression was in a left-linearized form.
995     /// This is required to avoid illegal operand reordering.
996     /// For example:
997     /// \verbatim
998     ///                         0 Op1
999     ///                         |/
1000     /// Op1 Op2   Linearized    + Op2
1001     ///   \ /     ---------->   |/
1002     ///    -                    -
1003     ///
1004     /// Op1 - Op2            (0 + Op1) - Op2
1005     /// \endverbatim
1006     ///
1007     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1008     ///
1009     /// Another way to think of this is to track all the operations across the
1010     /// path from the operand all the way to the root of the tree and to
1011     /// calculate the operation that corresponds to this path. For example, the
1012     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1013     /// corresponding operation is a '-' (which matches the one in the
1014     /// linearized tree, as shown above).
1015     ///
1016     /// For lack of a better term, we refer to this operation as Accumulated
1017     /// Path Operation (APO).
1018     struct OperandData {
1019       OperandData() = default;
1020       OperandData(Value *V, bool APO, bool IsUsed)
1021           : V(V), APO(APO), IsUsed(IsUsed) {}
1022       /// The operand value.
1023       Value *V = nullptr;
1024       /// TreeEntries only allow a single opcode, or an alternate sequence of
1025       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1026       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1027       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1028       /// (e.g., Add/Mul)
1029       bool APO = false;
1030       /// Helper data for the reordering function.
1031       bool IsUsed = false;
1032     };
1033 
1034     /// During operand reordering, we are trying to select the operand at lane
1035     /// that matches best with the operand at the neighboring lane. Our
1036     /// selection is based on the type of value we are looking for. For example,
1037     /// if the neighboring lane has a load, we need to look for a load that is
1038     /// accessing a consecutive address. These strategies are summarized in the
1039     /// 'ReorderingMode' enumerator.
1040     enum class ReorderingMode {
1041       Load,     ///< Matching loads to consecutive memory addresses
1042       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1043       Constant, ///< Matching constants
1044       Splat,    ///< Matching the same instruction multiple times (broadcast)
1045       Failed,   ///< We failed to create a vectorizable group
1046     };
1047 
1048     using OperandDataVec = SmallVector<OperandData, 2>;
1049 
1050     /// A vector of operand vectors.
1051     SmallVector<OperandDataVec, 4> OpsVec;
1052 
1053     const DataLayout &DL;
1054     ScalarEvolution &SE;
1055     const BoUpSLP &R;
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane.
1058     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1063     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1064       return OpsVec[OpIdx][Lane];
1065     }
1066 
1067     /// Clears the used flag for all entries.
1068     void clearUsed() {
1069       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1070            OpIdx != NumOperands; ++OpIdx)
1071         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1072              ++Lane)
1073           OpsVec[OpIdx][Lane].IsUsed = false;
1074     }
1075 
1076     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1077     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1078       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1079     }
1080 
1081     // The hard-coded scores listed here are not very important, though it shall
1082     // be higher for better matches to improve the resulting cost. When
1083     // computing the scores of matching one sub-tree with another, we are
1084     // basically counting the number of values that are matching. So even if all
1085     // scores are set to 1, we would still get a decent matching result.
1086     // However, sometimes we have to break ties. For example we may have to
1087     // choose between matching loads vs matching opcodes. This is what these
1088     // scores are helping us with: they provide the order of preference. Also,
1089     // this is important if the scalar is externally used or used in another
1090     // tree entry node in the different lane.
1091 
1092     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1093     static const int ScoreConsecutiveLoads = 4;
1094     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1095     static const int ScoreReversedLoads = 3;
1096     /// ExtractElementInst from same vector and consecutive indexes.
1097     static const int ScoreConsecutiveExtracts = 4;
1098     /// ExtractElementInst from same vector and reversed indices.
1099     static const int ScoreReversedExtracts = 3;
1100     /// Constants.
1101     static const int ScoreConstants = 2;
1102     /// Instructions with the same opcode.
1103     static const int ScoreSameOpcode = 2;
1104     /// Instructions with alt opcodes (e.g, add + sub).
1105     static const int ScoreAltOpcodes = 1;
1106     /// Identical instructions (a.k.a. splat or broadcast).
1107     static const int ScoreSplat = 1;
1108     /// Matching with an undef is preferable to failing.
1109     static const int ScoreUndef = 1;
1110     /// Score for failing to find a decent match.
1111     static const int ScoreFail = 0;
1112     /// Score if all users are vectorized.
1113     static const int ScoreAllUserVectorized = 1;
1114 
1115     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1116     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1117     /// MainAltOps.
1118     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1119                                ScalarEvolution &SE, int NumLanes,
1120                                ArrayRef<Value *> MainAltOps) {
1121       if (V1 == V2)
1122         return VLOperands::ScoreSplat;
1123 
1124       auto *LI1 = dyn_cast<LoadInst>(V1);
1125       auto *LI2 = dyn_cast<LoadInst>(V2);
1126       if (LI1 && LI2) {
1127         if (LI1->getParent() != LI2->getParent())
1128           return VLOperands::ScoreFail;
1129 
1130         Optional<int> Dist = getPointersDiff(
1131             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1132             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1133         if (!Dist || *Dist == 0)
1134           return VLOperands::ScoreFail;
1135         // The distance is too large - still may be profitable to use masked
1136         // loads/gathers.
1137         if (std::abs(*Dist) > NumLanes / 2)
1138           return VLOperands::ScoreAltOpcodes;
1139         // This still will detect consecutive loads, but we might have "holes"
1140         // in some cases. It is ok for non-power-2 vectorization and may produce
1141         // better results. It should not affect current vectorization.
1142         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1143                            : VLOperands::ScoreReversedLoads;
1144       }
1145 
1146       auto *C1 = dyn_cast<Constant>(V1);
1147       auto *C2 = dyn_cast<Constant>(V2);
1148       if (C1 && C2)
1149         return VLOperands::ScoreConstants;
1150 
1151       // Extracts from consecutive indexes of the same vector better score as
1152       // the extracts could be optimized away.
1153       Value *EV1;
1154       ConstantInt *Ex1Idx;
1155       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1156         // Undefs are always profitable for extractelements.
1157         if (isa<UndefValue>(V2))
1158           return VLOperands::ScoreConsecutiveExtracts;
1159         Value *EV2 = nullptr;
1160         ConstantInt *Ex2Idx = nullptr;
1161         if (match(V2,
1162                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1163                                                          m_Undef())))) {
1164           // Undefs are always profitable for extractelements.
1165           if (!Ex2Idx)
1166             return VLOperands::ScoreConsecutiveExtracts;
1167           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1168             return VLOperands::ScoreConsecutiveExtracts;
1169           if (EV2 == EV1) {
1170             int Idx1 = Ex1Idx->getZExtValue();
1171             int Idx2 = Ex2Idx->getZExtValue();
1172             int Dist = Idx2 - Idx1;
1173             // The distance is too large - still may be profitable to use
1174             // shuffles.
1175             if (std::abs(Dist) == 0)
1176               return VLOperands::ScoreSplat;
1177             if (std::abs(Dist) > NumLanes / 2)
1178               return VLOperands::ScoreSameOpcode;
1179             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1180                               : VLOperands::ScoreReversedExtracts;
1181           }
1182           return VLOperands::ScoreAltOpcodes;
1183         }
1184         return VLOperands::ScoreFail;
1185       }
1186 
1187       auto *I1 = dyn_cast<Instruction>(V1);
1188       auto *I2 = dyn_cast<Instruction>(V2);
1189       if (I1 && I2) {
1190         if (I1->getParent() != I2->getParent())
1191           return VLOperands::ScoreFail;
1192         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1193         Ops.push_back(I1);
1194         Ops.push_back(I2);
1195         InstructionsState S = getSameOpcode(Ops);
1196         // Note: Only consider instructions with <= 2 operands to avoid
1197         // complexity explosion.
1198         if (S.getOpcode() &&
1199             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1200              !S.isAltShuffle()) &&
1201             all_of(Ops, [&S](Value *V) {
1202               return cast<Instruction>(V)->getNumOperands() ==
1203                      S.MainOp->getNumOperands();
1204             }))
1205           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1206                                   : VLOperands::ScoreSameOpcode;
1207       }
1208 
1209       if (isa<UndefValue>(V2))
1210         return VLOperands::ScoreUndef;
1211 
1212       return VLOperands::ScoreFail;
1213     }
1214 
1215     /// \param Lane lane of the operands under analysis.
1216     /// \param OpIdx operand index in \p Lane lane we're looking the best
1217     /// candidate for.
1218     /// \param Idx operand index of the current candidate value.
1219     /// \returns The additional score due to possible broadcasting of the
1220     /// elements in the lane. It is more profitable to have power-of-2 unique
1221     /// elements in the lane, it will be vectorized with higher probability
1222     /// after removing duplicates. Currently the SLP vectorizer supports only
1223     /// vectorization of the power-of-2 number of unique scalars.
1224     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1225       Value *IdxLaneV = getData(Idx, Lane).V;
1226       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1227         return 0;
1228       SmallPtrSet<Value *, 4> Uniques;
1229       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1230         if (Ln == Lane)
1231           continue;
1232         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1233         if (!isa<Instruction>(OpIdxLnV))
1234           return 0;
1235         Uniques.insert(OpIdxLnV);
1236       }
1237       int UniquesCount = Uniques.size();
1238       int UniquesCntWithIdxLaneV =
1239           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1240       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1241       int UniquesCntWithOpIdxLaneV =
1242           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1243       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1244         return 0;
1245       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1246               UniquesCntWithOpIdxLaneV) -
1247              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1248     }
1249 
1250     /// \param Lane lane of the operands under analysis.
1251     /// \param OpIdx operand index in \p Lane lane we're looking the best
1252     /// candidate for.
1253     /// \param Idx operand index of the current candidate value.
1254     /// \returns The additional score for the scalar which users are all
1255     /// vectorized.
1256     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1257       Value *IdxLaneV = getData(Idx, Lane).V;
1258       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1259       // Do not care about number of uses for vector-like instructions
1260       // (extractelement/extractvalue with constant indices), they are extracts
1261       // themselves and already externally used. Vectorization of such
1262       // instructions does not add extra extractelement instruction, just may
1263       // remove it.
1264       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1265           isVectorLikeInstWithConstOps(OpIdxLaneV))
1266         return VLOperands::ScoreAllUserVectorized;
1267       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1268       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1269         return 0;
1270       return R.areAllUsersVectorized(IdxLaneI, None)
1271                  ? VLOperands::ScoreAllUserVectorized
1272                  : 0;
1273     }
1274 
1275     /// Go through the operands of \p LHS and \p RHS recursively until \p
1276     /// MaxLevel, and return the cummulative score. For example:
1277     /// \verbatim
1278     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1279     ///     \ /         \ /         \ /        \ /
1280     ///      +           +           +          +
1281     ///     G1          G2          G3         G4
1282     /// \endverbatim
1283     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1284     /// each level recursively, accumulating the score. It starts from matching
1285     /// the additions at level 0, then moves on to the loads (level 1). The
1286     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1287     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1288     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1289     /// Please note that the order of the operands does not matter, as we
1290     /// evaluate the score of all profitable combinations of operands. In
1291     /// other words the score of G1 and G4 is the same as G1 and G2. This
1292     /// heuristic is based on ideas described in:
1293     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1294     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1295     ///   Luís F. W. Góes
1296     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1297                            ArrayRef<Value *> MainAltOps) {
1298 
1299       // Get the shallow score of V1 and V2.
1300       int ShallowScoreAtThisLevel =
1301           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1302 
1303       // If reached MaxLevel,
1304       //  or if V1 and V2 are not instructions,
1305       //  or if they are SPLAT,
1306       //  or if they are not consecutive,
1307       //  or if profitable to vectorize loads or extractelements, early return
1308       //  the current cost.
1309       auto *I1 = dyn_cast<Instruction>(LHS);
1310       auto *I2 = dyn_cast<Instruction>(RHS);
1311       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1312           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1313           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1314             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1315             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1316            ShallowScoreAtThisLevel))
1317         return ShallowScoreAtThisLevel;
1318       assert(I1 && I2 && "Should have early exited.");
1319 
1320       // Contains the I2 operand indexes that got matched with I1 operands.
1321       SmallSet<unsigned, 4> Op2Used;
1322 
1323       // Recursion towards the operands of I1 and I2. We are trying all possible
1324       // operand pairs, and keeping track of the best score.
1325       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1326            OpIdx1 != NumOperands1; ++OpIdx1) {
1327         // Try to pair op1I with the best operand of I2.
1328         int MaxTmpScore = 0;
1329         unsigned MaxOpIdx2 = 0;
1330         bool FoundBest = false;
1331         // If I2 is commutative try all combinations.
1332         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1333         unsigned ToIdx = isCommutative(I2)
1334                              ? I2->getNumOperands()
1335                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1336         assert(FromIdx <= ToIdx && "Bad index");
1337         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1338           // Skip operands already paired with OpIdx1.
1339           if (Op2Used.count(OpIdx2))
1340             continue;
1341           // Recursively calculate the cost at each level
1342           int TmpScore =
1343               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1344                                  CurrLevel + 1, MaxLevel, None);
1345           // Look for the best score.
1346           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1347             MaxTmpScore = TmpScore;
1348             MaxOpIdx2 = OpIdx2;
1349             FoundBest = true;
1350           }
1351         }
1352         if (FoundBest) {
1353           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1354           Op2Used.insert(MaxOpIdx2);
1355           ShallowScoreAtThisLevel += MaxTmpScore;
1356         }
1357       }
1358       return ShallowScoreAtThisLevel;
1359     }
1360 
1361     /// Score scaling factor for fully compatible instructions but with
1362     /// different number of external uses. Allows better selection of the
1363     /// instructions with less external uses.
1364     static const int ScoreScaleFactor = 10;
1365 
1366     /// \Returns the look-ahead score, which tells us how much the sub-trees
1367     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1368     /// score. This helps break ties in an informed way when we cannot decide on
1369     /// the order of the operands by just considering the immediate
1370     /// predecessors.
1371     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1372                           int Lane, unsigned OpIdx, unsigned Idx,
1373                           bool &IsUsed) {
1374       int Score =
1375           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1376       if (Score) {
1377         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1378         if (Score <= -SplatScore) {
1379           // Set the minimum score for splat-like sequence to avoid setting
1380           // failed state.
1381           Score = 1;
1382         } else {
1383           Score += SplatScore;
1384           // Scale score to see the difference between different operands
1385           // and similar operands but all vectorized/not all vectorized
1386           // uses. It does not affect actual selection of the best
1387           // compatible operand in general, just allows to select the
1388           // operand with all vectorized uses.
1389           Score *= ScoreScaleFactor;
1390           Score += getExternalUseScore(Lane, OpIdx, Idx);
1391           IsUsed = true;
1392         }
1393       }
1394       return Score;
1395     }
1396 
1397     /// Best defined scores per lanes between the passes. Used to choose the
1398     /// best operand (with the highest score) between the passes.
1399     /// The key - {Operand Index, Lane}.
1400     /// The value - the best score between the passes for the lane and the
1401     /// operand.
1402     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1403         BestScoresPerLanes;
1404 
1405     // Search all operands in Ops[*][Lane] for the one that matches best
1406     // Ops[OpIdx][LastLane] and return its opreand index.
1407     // If no good match can be found, return None.
1408     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1409                                       ArrayRef<ReorderingMode> ReorderingModes,
1410                                       ArrayRef<Value *> MainAltOps) {
1411       unsigned NumOperands = getNumOperands();
1412 
1413       // The operand of the previous lane at OpIdx.
1414       Value *OpLastLane = getData(OpIdx, LastLane).V;
1415 
1416       // Our strategy mode for OpIdx.
1417       ReorderingMode RMode = ReorderingModes[OpIdx];
1418       if (RMode == ReorderingMode::Failed)
1419         return None;
1420 
1421       // The linearized opcode of the operand at OpIdx, Lane.
1422       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1423 
1424       // The best operand index and its score.
1425       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1426       // are using the score to differentiate between the two.
1427       struct BestOpData {
1428         Optional<unsigned> Idx = None;
1429         unsigned Score = 0;
1430       } BestOp;
1431       BestOp.Score =
1432           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1433               .first->second;
1434 
1435       // Track if the operand must be marked as used. If the operand is set to
1436       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1437       // want to reestimate the operands again on the following iterations).
1438       bool IsUsed =
1439           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1440       // Iterate through all unused operands and look for the best.
1441       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1442         // Get the operand at Idx and Lane.
1443         OperandData &OpData = getData(Idx, Lane);
1444         Value *Op = OpData.V;
1445         bool OpAPO = OpData.APO;
1446 
1447         // Skip already selected operands.
1448         if (OpData.IsUsed)
1449           continue;
1450 
1451         // Skip if we are trying to move the operand to a position with a
1452         // different opcode in the linearized tree form. This would break the
1453         // semantics.
1454         if (OpAPO != OpIdxAPO)
1455           continue;
1456 
1457         // Look for an operand that matches the current mode.
1458         switch (RMode) {
1459         case ReorderingMode::Load:
1460         case ReorderingMode::Constant:
1461         case ReorderingMode::Opcode: {
1462           bool LeftToRight = Lane > LastLane;
1463           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1464           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1465           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1466                                         OpIdx, Idx, IsUsed);
1467           if (Score > static_cast<int>(BestOp.Score)) {
1468             BestOp.Idx = Idx;
1469             BestOp.Score = Score;
1470             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1471           }
1472           break;
1473         }
1474         case ReorderingMode::Splat:
1475           if (Op == OpLastLane)
1476             BestOp.Idx = Idx;
1477           break;
1478         case ReorderingMode::Failed:
1479           llvm_unreachable("Not expected Failed reordering mode.");
1480         }
1481       }
1482 
1483       if (BestOp.Idx) {
1484         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1485         return BestOp.Idx;
1486       }
1487       // If we could not find a good match return None.
1488       return None;
1489     }
1490 
1491     /// Helper for reorderOperandVecs.
1492     /// \returns the lane that we should start reordering from. This is the one
1493     /// which has the least number of operands that can freely move about or
1494     /// less profitable because it already has the most optimal set of operands.
1495     unsigned getBestLaneToStartReordering() const {
1496       unsigned Min = UINT_MAX;
1497       unsigned SameOpNumber = 0;
1498       // std::pair<unsigned, unsigned> is used to implement a simple voting
1499       // algorithm and choose the lane with the least number of operands that
1500       // can freely move about or less profitable because it already has the
1501       // most optimal set of operands. The first unsigned is a counter for
1502       // voting, the second unsigned is the counter of lanes with instructions
1503       // with same/alternate opcodes and same parent basic block.
1504       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1505       // Try to be closer to the original results, if we have multiple lanes
1506       // with same cost. If 2 lanes have the same cost, use the one with the
1507       // lowest index.
1508       for (int I = getNumLanes(); I > 0; --I) {
1509         unsigned Lane = I - 1;
1510         OperandsOrderData NumFreeOpsHash =
1511             getMaxNumOperandsThatCanBeReordered(Lane);
1512         // Compare the number of operands that can move and choose the one with
1513         // the least number.
1514         if (NumFreeOpsHash.NumOfAPOs < Min) {
1515           Min = NumFreeOpsHash.NumOfAPOs;
1516           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1517           HashMap.clear();
1518           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1519         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1520                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1521           // Select the most optimal lane in terms of number of operands that
1522           // should be moved around.
1523           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1524           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1526                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1527           auto It = HashMap.find(NumFreeOpsHash.Hash);
1528           if (It == HashMap.end())
1529             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1530           else
1531             ++It->second.first;
1532         }
1533       }
1534       // Select the lane with the minimum counter.
1535       unsigned BestLane = 0;
1536       unsigned CntMin = UINT_MAX;
1537       for (const auto &Data : reverse(HashMap)) {
1538         if (Data.second.first < CntMin) {
1539           CntMin = Data.second.first;
1540           BestLane = Data.second.second;
1541         }
1542       }
1543       return BestLane;
1544     }
1545 
1546     /// Data structure that helps to reorder operands.
1547     struct OperandsOrderData {
1548       /// The best number of operands with the same APOs, which can be
1549       /// reordered.
1550       unsigned NumOfAPOs = UINT_MAX;
1551       /// Number of operands with the same/alternate instruction opcode and
1552       /// parent.
1553       unsigned NumOpsWithSameOpcodeParent = 0;
1554       /// Hash for the actual operands ordering.
1555       /// Used to count operands, actually their position id and opcode
1556       /// value. It is used in the voting mechanism to find the lane with the
1557       /// least number of operands that can freely move about or less profitable
1558       /// because it already has the most optimal set of operands. Can be
1559       /// replaced with SmallVector<unsigned> instead but hash code is faster
1560       /// and requires less memory.
1561       unsigned Hash = 0;
1562     };
1563     /// \returns the maximum number of operands that are allowed to be reordered
1564     /// for \p Lane and the number of compatible instructions(with the same
1565     /// parent/opcode). This is used as a heuristic for selecting the first lane
1566     /// to start operand reordering.
1567     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1568       unsigned CntTrue = 0;
1569       unsigned NumOperands = getNumOperands();
1570       // Operands with the same APO can be reordered. We therefore need to count
1571       // how many of them we have for each APO, like this: Cnt[APO] = x.
1572       // Since we only have two APOs, namely true and false, we can avoid using
1573       // a map. Instead we can simply count the number of operands that
1574       // correspond to one of them (in this case the 'true' APO), and calculate
1575       // the other by subtracting it from the total number of operands.
1576       // Operands with the same instruction opcode and parent are more
1577       // profitable since we don't need to move them in many cases, with a high
1578       // probability such lane already can be vectorized effectively.
1579       bool AllUndefs = true;
1580       unsigned NumOpsWithSameOpcodeParent = 0;
1581       Instruction *OpcodeI = nullptr;
1582       BasicBlock *Parent = nullptr;
1583       unsigned Hash = 0;
1584       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1585         const OperandData &OpData = getData(OpIdx, Lane);
1586         if (OpData.APO)
1587           ++CntTrue;
1588         // Use Boyer-Moore majority voting for finding the majority opcode and
1589         // the number of times it occurs.
1590         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1591           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1592               I->getParent() != Parent) {
1593             if (NumOpsWithSameOpcodeParent == 0) {
1594               NumOpsWithSameOpcodeParent = 1;
1595               OpcodeI = I;
1596               Parent = I->getParent();
1597             } else {
1598               --NumOpsWithSameOpcodeParent;
1599             }
1600           } else {
1601             ++NumOpsWithSameOpcodeParent;
1602           }
1603         }
1604         Hash = hash_combine(
1605             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1606         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1607       }
1608       if (AllUndefs)
1609         return {};
1610       OperandsOrderData Data;
1611       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1612       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1613       Data.Hash = Hash;
1614       return Data;
1615     }
1616 
1617     /// Go through the instructions in VL and append their operands.
1618     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1619       assert(!VL.empty() && "Bad VL");
1620       assert((empty() || VL.size() == getNumLanes()) &&
1621              "Expected same number of lanes");
1622       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1623       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1624       OpsVec.resize(NumOperands);
1625       unsigned NumLanes = VL.size();
1626       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1627         OpsVec[OpIdx].resize(NumLanes);
1628         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1629           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1630           // Our tree has just 3 nodes: the root and two operands.
1631           // It is therefore trivial to get the APO. We only need to check the
1632           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1633           // RHS operand. The LHS operand of both add and sub is never attached
1634           // to an inversese operation in the linearized form, therefore its APO
1635           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1636 
1637           // Since operand reordering is performed on groups of commutative
1638           // operations or alternating sequences (e.g., +, -), we can safely
1639           // tell the inverse operations by checking commutativity.
1640           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1641           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1642           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1643                                  APO, false};
1644         }
1645       }
1646     }
1647 
1648     /// \returns the number of operands.
1649     unsigned getNumOperands() const { return OpsVec.size(); }
1650 
1651     /// \returns the number of lanes.
1652     unsigned getNumLanes() const { return OpsVec[0].size(); }
1653 
1654     /// \returns the operand value at \p OpIdx and \p Lane.
1655     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1656       return getData(OpIdx, Lane).V;
1657     }
1658 
1659     /// \returns true if the data structure is empty.
1660     bool empty() const { return OpsVec.empty(); }
1661 
1662     /// Clears the data.
1663     void clear() { OpsVec.clear(); }
1664 
1665     /// \Returns true if there are enough operands identical to \p Op to fill
1666     /// the whole vector.
1667     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1668     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1669       bool OpAPO = getData(OpIdx, Lane).APO;
1670       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1671         if (Ln == Lane)
1672           continue;
1673         // This is set to true if we found a candidate for broadcast at Lane.
1674         bool FoundCandidate = false;
1675         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1676           OperandData &Data = getData(OpI, Ln);
1677           if (Data.APO != OpAPO || Data.IsUsed)
1678             continue;
1679           if (Data.V == Op) {
1680             FoundCandidate = true;
1681             Data.IsUsed = true;
1682             break;
1683           }
1684         }
1685         if (!FoundCandidate)
1686           return false;
1687       }
1688       return true;
1689     }
1690 
1691   public:
1692     /// Initialize with all the operands of the instruction vector \p RootVL.
1693     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1694                ScalarEvolution &SE, const BoUpSLP &R)
1695         : DL(DL), SE(SE), R(R) {
1696       // Append all the operands of RootVL.
1697       appendOperandsOfVL(RootVL);
1698     }
1699 
1700     /// \Returns a value vector with the operands across all lanes for the
1701     /// opearnd at \p OpIdx.
1702     ValueList getVL(unsigned OpIdx) const {
1703       ValueList OpVL(OpsVec[OpIdx].size());
1704       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1705              "Expected same num of lanes across all operands");
1706       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1707         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1708       return OpVL;
1709     }
1710 
1711     // Performs operand reordering for 2 or more operands.
1712     // The original operands are in OrigOps[OpIdx][Lane].
1713     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1714     void reorder() {
1715       unsigned NumOperands = getNumOperands();
1716       unsigned NumLanes = getNumLanes();
1717       // Each operand has its own mode. We are using this mode to help us select
1718       // the instructions for each lane, so that they match best with the ones
1719       // we have selected so far.
1720       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1721 
1722       // This is a greedy single-pass algorithm. We are going over each lane
1723       // once and deciding on the best order right away with no back-tracking.
1724       // However, in order to increase its effectiveness, we start with the lane
1725       // that has operands that can move the least. For example, given the
1726       // following lanes:
1727       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1728       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1729       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1730       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1731       // we will start at Lane 1, since the operands of the subtraction cannot
1732       // be reordered. Then we will visit the rest of the lanes in a circular
1733       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1734 
1735       // Find the first lane that we will start our search from.
1736       unsigned FirstLane = getBestLaneToStartReordering();
1737 
1738       // Initialize the modes.
1739       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1740         Value *OpLane0 = getValue(OpIdx, FirstLane);
1741         // Keep track if we have instructions with all the same opcode on one
1742         // side.
1743         if (isa<LoadInst>(OpLane0))
1744           ReorderingModes[OpIdx] = ReorderingMode::Load;
1745         else if (isa<Instruction>(OpLane0)) {
1746           // Check if OpLane0 should be broadcast.
1747           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1748             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1749           else
1750             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1751         }
1752         else if (isa<Constant>(OpLane0))
1753           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1754         else if (isa<Argument>(OpLane0))
1755           // Our best hope is a Splat. It may save some cost in some cases.
1756           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1757         else
1758           // NOTE: This should be unreachable.
1759           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1760       }
1761 
1762       // Check that we don't have same operands. No need to reorder if operands
1763       // are just perfect diamond or shuffled diamond match. Do not do it only
1764       // for possible broadcasts or non-power of 2 number of scalars (just for
1765       // now).
1766       auto &&SkipReordering = [this]() {
1767         SmallPtrSet<Value *, 4> UniqueValues;
1768         ArrayRef<OperandData> Op0 = OpsVec.front();
1769         for (const OperandData &Data : Op0)
1770           UniqueValues.insert(Data.V);
1771         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1772           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1773                 return !UniqueValues.contains(Data.V);
1774               }))
1775             return false;
1776         }
1777         // TODO: Check if we can remove a check for non-power-2 number of
1778         // scalars after full support of non-power-2 vectorization.
1779         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1780       };
1781 
1782       // If the initial strategy fails for any of the operand indexes, then we
1783       // perform reordering again in a second pass. This helps avoid assigning
1784       // high priority to the failed strategy, and should improve reordering for
1785       // the non-failed operand indexes.
1786       for (int Pass = 0; Pass != 2; ++Pass) {
1787         // Check if no need to reorder operands since they're are perfect or
1788         // shuffled diamond match.
1789         // Need to to do it to avoid extra external use cost counting for
1790         // shuffled matches, which may cause regressions.
1791         if (SkipReordering())
1792           break;
1793         // Skip the second pass if the first pass did not fail.
1794         bool StrategyFailed = false;
1795         // Mark all operand data as free to use.
1796         clearUsed();
1797         // We keep the original operand order for the FirstLane, so reorder the
1798         // rest of the lanes. We are visiting the nodes in a circular fashion,
1799         // using FirstLane as the center point and increasing the radius
1800         // distance.
1801         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1802         for (unsigned I = 0; I < NumOperands; ++I)
1803           MainAltOps[I].push_back(getData(I, FirstLane).V);
1804 
1805         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1806           // Visit the lane on the right and then the lane on the left.
1807           for (int Direction : {+1, -1}) {
1808             int Lane = FirstLane + Direction * Distance;
1809             if (Lane < 0 || Lane >= (int)NumLanes)
1810               continue;
1811             int LastLane = Lane - Direction;
1812             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1813                    "Out of bounds");
1814             // Look for a good match for each operand.
1815             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1816               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1817               Optional<unsigned> BestIdx = getBestOperand(
1818                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1819               // By not selecting a value, we allow the operands that follow to
1820               // select a better matching value. We will get a non-null value in
1821               // the next run of getBestOperand().
1822               if (BestIdx) {
1823                 // Swap the current operand with the one returned by
1824                 // getBestOperand().
1825                 swap(OpIdx, BestIdx.getValue(), Lane);
1826               } else {
1827                 // We failed to find a best operand, set mode to 'Failed'.
1828                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1829                 // Enable the second pass.
1830                 StrategyFailed = true;
1831               }
1832               // Try to get the alternate opcode and follow it during analysis.
1833               if (MainAltOps[OpIdx].size() != 2) {
1834                 OperandData &AltOp = getData(OpIdx, Lane);
1835                 InstructionsState OpS =
1836                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1837                 if (OpS.getOpcode() && OpS.isAltShuffle())
1838                   MainAltOps[OpIdx].push_back(AltOp.V);
1839               }
1840             }
1841           }
1842         }
1843         // Skip second pass if the strategy did not fail.
1844         if (!StrategyFailed)
1845           break;
1846       }
1847     }
1848 
1849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1850     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1851       switch (RMode) {
1852       case ReorderingMode::Load:
1853         return "Load";
1854       case ReorderingMode::Opcode:
1855         return "Opcode";
1856       case ReorderingMode::Constant:
1857         return "Constant";
1858       case ReorderingMode::Splat:
1859         return "Splat";
1860       case ReorderingMode::Failed:
1861         return "Failed";
1862       }
1863       llvm_unreachable("Unimplemented Reordering Type");
1864     }
1865 
1866     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1867                                                    raw_ostream &OS) {
1868       return OS << getModeStr(RMode);
1869     }
1870 
1871     /// Debug print.
1872     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1873       printMode(RMode, dbgs());
1874     }
1875 
1876     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1877       return printMode(RMode, OS);
1878     }
1879 
1880     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1881       const unsigned Indent = 2;
1882       unsigned Cnt = 0;
1883       for (const OperandDataVec &OpDataVec : OpsVec) {
1884         OS << "Operand " << Cnt++ << "\n";
1885         for (const OperandData &OpData : OpDataVec) {
1886           OS.indent(Indent) << "{";
1887           if (Value *V = OpData.V)
1888             OS << *V;
1889           else
1890             OS << "null";
1891           OS << ", APO:" << OpData.APO << "}\n";
1892         }
1893         OS << "\n";
1894       }
1895       return OS;
1896     }
1897 
1898     /// Debug print.
1899     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1900 #endif
1901   };
1902 
1903   /// Checks if the instruction is marked for deletion.
1904   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1905 
1906   /// Marks values operands for later deletion by replacing them with Undefs.
1907   void eraseInstructions(ArrayRef<Value *> AV);
1908 
1909   ~BoUpSLP();
1910 
1911 private:
1912   /// Checks if all users of \p I are the part of the vectorization tree.
1913   bool areAllUsersVectorized(Instruction *I,
1914                              ArrayRef<Value *> VectorizedVals) const;
1915 
1916   /// \returns the cost of the vectorizable entry.
1917   InstructionCost getEntryCost(const TreeEntry *E,
1918                                ArrayRef<Value *> VectorizedVals);
1919 
1920   /// This is the recursive part of buildTree.
1921   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1922                      const EdgeInfo &EI);
1923 
1924   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1925   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1926   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1927   /// returns false, setting \p CurrentOrder to either an empty vector or a
1928   /// non-identity permutation that allows to reuse extract instructions.
1929   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1930                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1931 
1932   /// Vectorize a single entry in the tree.
1933   Value *vectorizeTree(TreeEntry *E);
1934 
1935   /// Vectorize a single entry in the tree, starting in \p VL.
1936   Value *vectorizeTree(ArrayRef<Value *> VL);
1937 
1938   /// \returns the scalarization cost for this type. Scalarization in this
1939   /// context means the creation of vectors from a group of scalars. If \p
1940   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1941   /// vector elements.
1942   InstructionCost getGatherCost(FixedVectorType *Ty,
1943                                 const DenseSet<unsigned> &ShuffledIndices,
1944                                 bool NeedToShuffle) const;
1945 
1946   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1947   /// tree entries.
1948   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1949   /// previous tree entries. \p Mask is filled with the shuffle mask.
1950   Optional<TargetTransformInfo::ShuffleKind>
1951   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1952                         SmallVectorImpl<const TreeEntry *> &Entries);
1953 
1954   /// \returns the scalarization cost for this list of values. Assuming that
1955   /// this subtree gets vectorized, we may need to extract the values from the
1956   /// roots. This method calculates the cost of extracting the values.
1957   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1958 
1959   /// Set the Builder insert point to one after the last instruction in
1960   /// the bundle
1961   void setInsertPointAfterBundle(const TreeEntry *E);
1962 
1963   /// \returns a vector from a collection of scalars in \p VL.
1964   Value *gather(ArrayRef<Value *> VL);
1965 
1966   /// \returns whether the VectorizableTree is fully vectorizable and will
1967   /// be beneficial even the tree height is tiny.
1968   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1969 
1970   /// Reorder commutative or alt operands to get better probability of
1971   /// generating vectorized code.
1972   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1973                                              SmallVectorImpl<Value *> &Left,
1974                                              SmallVectorImpl<Value *> &Right,
1975                                              const DataLayout &DL,
1976                                              ScalarEvolution &SE,
1977                                              const BoUpSLP &R);
1978   struct TreeEntry {
1979     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1980     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1981 
1982     /// \returns true if the scalars in VL are equal to this entry.
1983     bool isSame(ArrayRef<Value *> VL) const {
1984       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1985         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1986           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1987         return VL.size() == Mask.size() &&
1988                std::equal(VL.begin(), VL.end(), Mask.begin(),
1989                           [Scalars](Value *V, int Idx) {
1990                             return (isa<UndefValue>(V) &&
1991                                     Idx == UndefMaskElem) ||
1992                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1993                           });
1994       };
1995       if (!ReorderIndices.empty()) {
1996         // TODO: implement matching if the nodes are just reordered, still can
1997         // treat the vector as the same if the list of scalars matches VL
1998         // directly, without reordering.
1999         SmallVector<int> Mask;
2000         inversePermutation(ReorderIndices, Mask);
2001         if (VL.size() == Scalars.size())
2002           return IsSame(Scalars, Mask);
2003         if (VL.size() == ReuseShuffleIndices.size()) {
2004           ::addMask(Mask, ReuseShuffleIndices);
2005           return IsSame(Scalars, Mask);
2006         }
2007         return false;
2008       }
2009       return IsSame(Scalars, ReuseShuffleIndices);
2010     }
2011 
2012     /// \returns true if current entry has same operands as \p TE.
2013     bool hasEqualOperands(const TreeEntry &TE) const {
2014       if (TE.getNumOperands() != getNumOperands())
2015         return false;
2016       SmallBitVector Used(getNumOperands());
2017       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2018         unsigned PrevCount = Used.count();
2019         for (unsigned K = 0; K < E; ++K) {
2020           if (Used.test(K))
2021             continue;
2022           if (getOperand(K) == TE.getOperand(I)) {
2023             Used.set(K);
2024             break;
2025           }
2026         }
2027         // Check if we actually found the matching operand.
2028         if (PrevCount == Used.count())
2029           return false;
2030       }
2031       return true;
2032     }
2033 
2034     /// \return Final vectorization factor for the node. Defined by the total
2035     /// number of vectorized scalars, including those, used several times in the
2036     /// entry and counted in the \a ReuseShuffleIndices, if any.
2037     unsigned getVectorFactor() const {
2038       if (!ReuseShuffleIndices.empty())
2039         return ReuseShuffleIndices.size();
2040       return Scalars.size();
2041     };
2042 
2043     /// A vector of scalars.
2044     ValueList Scalars;
2045 
2046     /// The Scalars are vectorized into this value. It is initialized to Null.
2047     Value *VectorizedValue = nullptr;
2048 
2049     /// Do we need to gather this sequence or vectorize it
2050     /// (either with vector instruction or with scatter/gather
2051     /// intrinsics for store/load)?
2052     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2053     EntryState State;
2054 
2055     /// Does this sequence require some shuffling?
2056     SmallVector<int, 4> ReuseShuffleIndices;
2057 
2058     /// Does this entry require reordering?
2059     SmallVector<unsigned, 4> ReorderIndices;
2060 
2061     /// Points back to the VectorizableTree.
2062     ///
2063     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2064     /// to be a pointer and needs to be able to initialize the child iterator.
2065     /// Thus we need a reference back to the container to translate the indices
2066     /// to entries.
2067     VecTreeTy &Container;
2068 
2069     /// The TreeEntry index containing the user of this entry.  We can actually
2070     /// have multiple users so the data structure is not truly a tree.
2071     SmallVector<EdgeInfo, 1> UserTreeIndices;
2072 
2073     /// The index of this treeEntry in VectorizableTree.
2074     int Idx = -1;
2075 
2076   private:
2077     /// The operands of each instruction in each lane Operands[op_index][lane].
2078     /// Note: This helps avoid the replication of the code that performs the
2079     /// reordering of operands during buildTree_rec() and vectorizeTree().
2080     SmallVector<ValueList, 2> Operands;
2081 
2082     /// The main/alternate instruction.
2083     Instruction *MainOp = nullptr;
2084     Instruction *AltOp = nullptr;
2085 
2086   public:
2087     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2088     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2089       if (Operands.size() < OpIdx + 1)
2090         Operands.resize(OpIdx + 1);
2091       assert(Operands[OpIdx].empty() && "Already resized?");
2092       assert(OpVL.size() <= Scalars.size() &&
2093              "Number of operands is greater than the number of scalars.");
2094       Operands[OpIdx].resize(OpVL.size());
2095       copy(OpVL, Operands[OpIdx].begin());
2096     }
2097 
2098     /// Set the operands of this bundle in their original order.
2099     void setOperandsInOrder() {
2100       assert(Operands.empty() && "Already initialized?");
2101       auto *I0 = cast<Instruction>(Scalars[0]);
2102       Operands.resize(I0->getNumOperands());
2103       unsigned NumLanes = Scalars.size();
2104       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2105            OpIdx != NumOperands; ++OpIdx) {
2106         Operands[OpIdx].resize(NumLanes);
2107         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2108           auto *I = cast<Instruction>(Scalars[Lane]);
2109           assert(I->getNumOperands() == NumOperands &&
2110                  "Expected same number of operands");
2111           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2112         }
2113       }
2114     }
2115 
2116     /// Reorders operands of the node to the given mask \p Mask.
2117     void reorderOperands(ArrayRef<int> Mask) {
2118       for (ValueList &Operand : Operands)
2119         reorderScalars(Operand, Mask);
2120     }
2121 
2122     /// \returns the \p OpIdx operand of this TreeEntry.
2123     ValueList &getOperand(unsigned OpIdx) {
2124       assert(OpIdx < Operands.size() && "Off bounds");
2125       return Operands[OpIdx];
2126     }
2127 
2128     /// \returns the \p OpIdx operand of this TreeEntry.
2129     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2130       assert(OpIdx < Operands.size() && "Off bounds");
2131       return Operands[OpIdx];
2132     }
2133 
2134     /// \returns the number of operands.
2135     unsigned getNumOperands() const { return Operands.size(); }
2136 
2137     /// \return the single \p OpIdx operand.
2138     Value *getSingleOperand(unsigned OpIdx) const {
2139       assert(OpIdx < Operands.size() && "Off bounds");
2140       assert(!Operands[OpIdx].empty() && "No operand available");
2141       return Operands[OpIdx][0];
2142     }
2143 
2144     /// Some of the instructions in the list have alternate opcodes.
2145     bool isAltShuffle() const { return MainOp != AltOp; }
2146 
2147     bool isOpcodeOrAlt(Instruction *I) const {
2148       unsigned CheckedOpcode = I->getOpcode();
2149       return (getOpcode() == CheckedOpcode ||
2150               getAltOpcode() == CheckedOpcode);
2151     }
2152 
2153     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2154     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2155     /// \p OpValue.
2156     Value *isOneOf(Value *Op) const {
2157       auto *I = dyn_cast<Instruction>(Op);
2158       if (I && isOpcodeOrAlt(I))
2159         return Op;
2160       return MainOp;
2161     }
2162 
2163     void setOperations(const InstructionsState &S) {
2164       MainOp = S.MainOp;
2165       AltOp = S.AltOp;
2166     }
2167 
2168     Instruction *getMainOp() const {
2169       return MainOp;
2170     }
2171 
2172     Instruction *getAltOp() const {
2173       return AltOp;
2174     }
2175 
2176     /// The main/alternate opcodes for the list of instructions.
2177     unsigned getOpcode() const {
2178       return MainOp ? MainOp->getOpcode() : 0;
2179     }
2180 
2181     unsigned getAltOpcode() const {
2182       return AltOp ? AltOp->getOpcode() : 0;
2183     }
2184 
2185     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2186     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2187     int findLaneForValue(Value *V) const {
2188       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2189       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2190       if (!ReorderIndices.empty())
2191         FoundLane = ReorderIndices[FoundLane];
2192       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2193       if (!ReuseShuffleIndices.empty()) {
2194         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2195                                   find(ReuseShuffleIndices, FoundLane));
2196       }
2197       return FoundLane;
2198     }
2199 
2200 #ifndef NDEBUG
2201     /// Debug printer.
2202     LLVM_DUMP_METHOD void dump() const {
2203       dbgs() << Idx << ".\n";
2204       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2205         dbgs() << "Operand " << OpI << ":\n";
2206         for (const Value *V : Operands[OpI])
2207           dbgs().indent(2) << *V << "\n";
2208       }
2209       dbgs() << "Scalars: \n";
2210       for (Value *V : Scalars)
2211         dbgs().indent(2) << *V << "\n";
2212       dbgs() << "State: ";
2213       switch (State) {
2214       case Vectorize:
2215         dbgs() << "Vectorize\n";
2216         break;
2217       case ScatterVectorize:
2218         dbgs() << "ScatterVectorize\n";
2219         break;
2220       case NeedToGather:
2221         dbgs() << "NeedToGather\n";
2222         break;
2223       }
2224       dbgs() << "MainOp: ";
2225       if (MainOp)
2226         dbgs() << *MainOp << "\n";
2227       else
2228         dbgs() << "NULL\n";
2229       dbgs() << "AltOp: ";
2230       if (AltOp)
2231         dbgs() << *AltOp << "\n";
2232       else
2233         dbgs() << "NULL\n";
2234       dbgs() << "VectorizedValue: ";
2235       if (VectorizedValue)
2236         dbgs() << *VectorizedValue << "\n";
2237       else
2238         dbgs() << "NULL\n";
2239       dbgs() << "ReuseShuffleIndices: ";
2240       if (ReuseShuffleIndices.empty())
2241         dbgs() << "Empty";
2242       else
2243         for (int ReuseIdx : ReuseShuffleIndices)
2244           dbgs() << ReuseIdx << ", ";
2245       dbgs() << "\n";
2246       dbgs() << "ReorderIndices: ";
2247       for (unsigned ReorderIdx : ReorderIndices)
2248         dbgs() << ReorderIdx << ", ";
2249       dbgs() << "\n";
2250       dbgs() << "UserTreeIndices: ";
2251       for (const auto &EInfo : UserTreeIndices)
2252         dbgs() << EInfo << ", ";
2253       dbgs() << "\n";
2254     }
2255 #endif
2256   };
2257 
2258 #ifndef NDEBUG
2259   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2260                      InstructionCost VecCost,
2261                      InstructionCost ScalarCost) const {
2262     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2263     dbgs() << "SLP: Costs:\n";
2264     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2265     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2266     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2267     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2268                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2269   }
2270 #endif
2271 
2272   /// Create a new VectorizableTree entry.
2273   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2274                           const InstructionsState &S,
2275                           const EdgeInfo &UserTreeIdx,
2276                           ArrayRef<int> ReuseShuffleIndices = None,
2277                           ArrayRef<unsigned> ReorderIndices = None) {
2278     TreeEntry::EntryState EntryState =
2279         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2280     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2281                         ReuseShuffleIndices, ReorderIndices);
2282   }
2283 
2284   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2285                           TreeEntry::EntryState EntryState,
2286                           Optional<ScheduleData *> Bundle,
2287                           const InstructionsState &S,
2288                           const EdgeInfo &UserTreeIdx,
2289                           ArrayRef<int> ReuseShuffleIndices = None,
2290                           ArrayRef<unsigned> ReorderIndices = None) {
2291     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2292             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2293            "Need to vectorize gather entry?");
2294     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2295     TreeEntry *Last = VectorizableTree.back().get();
2296     Last->Idx = VectorizableTree.size() - 1;
2297     Last->State = EntryState;
2298     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2299                                      ReuseShuffleIndices.end());
2300     if (ReorderIndices.empty()) {
2301       Last->Scalars.assign(VL.begin(), VL.end());
2302       Last->setOperations(S);
2303     } else {
2304       // Reorder scalars and build final mask.
2305       Last->Scalars.assign(VL.size(), nullptr);
2306       transform(ReorderIndices, Last->Scalars.begin(),
2307                 [VL](unsigned Idx) -> Value * {
2308                   if (Idx >= VL.size())
2309                     return UndefValue::get(VL.front()->getType());
2310                   return VL[Idx];
2311                 });
2312       InstructionsState S = getSameOpcode(Last->Scalars);
2313       Last->setOperations(S);
2314       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2315     }
2316     if (Last->State != TreeEntry::NeedToGather) {
2317       for (Value *V : VL) {
2318         assert(!getTreeEntry(V) && "Scalar already in tree!");
2319         ScalarToTreeEntry[V] = Last;
2320       }
2321       // Update the scheduler bundle to point to this TreeEntry.
2322       unsigned Lane = 0;
2323       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2324            BundleMember = BundleMember->NextInBundle) {
2325         BundleMember->TE = Last;
2326         BundleMember->Lane = Lane;
2327         ++Lane;
2328       }
2329       assert((!Bundle.getValue() || Lane == VL.size()) &&
2330              "Bundle and VL out of sync");
2331     } else {
2332       MustGather.insert(VL.begin(), VL.end());
2333     }
2334 
2335     if (UserTreeIdx.UserTE)
2336       Last->UserTreeIndices.push_back(UserTreeIdx);
2337 
2338     return Last;
2339   }
2340 
2341   /// -- Vectorization State --
2342   /// Holds all of the tree entries.
2343   TreeEntry::VecTreeTy VectorizableTree;
2344 
2345 #ifndef NDEBUG
2346   /// Debug printer.
2347   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2348     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2349       VectorizableTree[Id]->dump();
2350       dbgs() << "\n";
2351     }
2352   }
2353 #endif
2354 
2355   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2356 
2357   const TreeEntry *getTreeEntry(Value *V) const {
2358     return ScalarToTreeEntry.lookup(V);
2359   }
2360 
2361   /// Maps a specific scalar to its tree entry.
2362   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2363 
2364   /// Maps a value to the proposed vectorizable size.
2365   SmallDenseMap<Value *, unsigned> InstrElementSize;
2366 
2367   /// A list of scalars that we found that we need to keep as scalars.
2368   ValueSet MustGather;
2369 
2370   /// This POD struct describes one external user in the vectorized tree.
2371   struct ExternalUser {
2372     ExternalUser(Value *S, llvm::User *U, int L)
2373         : Scalar(S), User(U), Lane(L) {}
2374 
2375     // Which scalar in our function.
2376     Value *Scalar;
2377 
2378     // Which user that uses the scalar.
2379     llvm::User *User;
2380 
2381     // Which lane does the scalar belong to.
2382     int Lane;
2383   };
2384   using UserList = SmallVector<ExternalUser, 16>;
2385 
2386   /// Checks if two instructions may access the same memory.
2387   ///
2388   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2389   /// is invariant in the calling loop.
2390   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2391                  Instruction *Inst2) {
2392     // First check if the result is already in the cache.
2393     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2394     Optional<bool> &result = AliasCache[key];
2395     if (result.hasValue()) {
2396       return result.getValue();
2397     }
2398     bool aliased = true;
2399     if (Loc1.Ptr && isSimple(Inst1))
2400       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2401     // Store the result in the cache.
2402     result = aliased;
2403     return aliased;
2404   }
2405 
2406   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2407 
2408   /// Cache for alias results.
2409   /// TODO: consider moving this to the AliasAnalysis itself.
2410   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2411 
2412   /// Removes an instruction from its block and eventually deletes it.
2413   /// It's like Instruction::eraseFromParent() except that the actual deletion
2414   /// is delayed until BoUpSLP is destructed.
2415   /// This is required to ensure that there are no incorrect collisions in the
2416   /// AliasCache, which can happen if a new instruction is allocated at the
2417   /// same address as a previously deleted instruction.
2418   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2419     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2420     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2421   }
2422 
2423   /// Temporary store for deleted instructions. Instructions will be deleted
2424   /// eventually when the BoUpSLP is destructed.
2425   DenseMap<Instruction *, bool> DeletedInstructions;
2426 
2427   /// A list of values that need to extracted out of the tree.
2428   /// This list holds pairs of (Internal Scalar : External User). External User
2429   /// can be nullptr, it means that this Internal Scalar will be used later,
2430   /// after vectorization.
2431   UserList ExternalUses;
2432 
2433   /// Values used only by @llvm.assume calls.
2434   SmallPtrSet<const Value *, 32> EphValues;
2435 
2436   /// Holds all of the instructions that we gathered.
2437   SetVector<Instruction *> GatherShuffleSeq;
2438 
2439   /// A list of blocks that we are going to CSE.
2440   SetVector<BasicBlock *> CSEBlocks;
2441 
2442   /// Contains all scheduling relevant data for an instruction.
2443   /// A ScheduleData either represents a single instruction or a member of an
2444   /// instruction bundle (= a group of instructions which is combined into a
2445   /// vector instruction).
2446   struct ScheduleData {
2447     // The initial value for the dependency counters. It means that the
2448     // dependencies are not calculated yet.
2449     enum { InvalidDeps = -1 };
2450 
2451     ScheduleData() = default;
2452 
2453     void init(int BlockSchedulingRegionID, Value *OpVal) {
2454       FirstInBundle = this;
2455       NextInBundle = nullptr;
2456       NextLoadStore = nullptr;
2457       IsScheduled = false;
2458       SchedulingRegionID = BlockSchedulingRegionID;
2459       UnscheduledDepsInBundle = UnscheduledDeps;
2460       clearDependencies();
2461       OpValue = OpVal;
2462       TE = nullptr;
2463       Lane = -1;
2464     }
2465 
2466     /// Verify basic self consistency properties
2467     void verify() {
2468       if (hasValidDependencies()) {
2469         assert(UnscheduledDeps <= Dependencies && "invariant");
2470         assert(UnscheduledDeps <= FirstInBundle->UnscheduledDepsInBundle &&
2471                "bundle must have at least as many dependencies as member");
2472       }
2473 
2474       if (IsScheduled) {
2475         assert(isSchedulingEntity() && hasValidDependencies() &&
2476                UnscheduledDeps == 0 &&
2477                "unexpected scheduled state");
2478       }
2479     }
2480 
2481     /// Returns true if the dependency information has been calculated.
2482     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2483 
2484     /// Returns true for single instructions and for bundle representatives
2485     /// (= the head of a bundle).
2486     bool isSchedulingEntity() const { return FirstInBundle == this; }
2487 
2488     /// Returns true if it represents an instruction bundle and not only a
2489     /// single instruction.
2490     bool isPartOfBundle() const {
2491       return NextInBundle != nullptr || FirstInBundle != this;
2492     }
2493 
2494     /// Returns true if it is ready for scheduling, i.e. it has no more
2495     /// unscheduled depending instructions/bundles.
2496     bool isReady() const {
2497       assert(isSchedulingEntity() &&
2498              "can't consider non-scheduling entity for ready list");
2499       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2500     }
2501 
2502     /// Modifies the number of unscheduled dependencies, also updating it for
2503     /// the whole bundle.
2504     int incrementUnscheduledDeps(int Incr) {
2505       UnscheduledDeps += Incr;
2506       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2507     }
2508 
2509     /// Sets the number of unscheduled dependencies to the number of
2510     /// dependencies.
2511     void resetUnscheduledDeps() {
2512       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2513     }
2514 
2515     /// Clears all dependency information.
2516     void clearDependencies() {
2517       Dependencies = InvalidDeps;
2518       resetUnscheduledDeps();
2519       MemoryDependencies.clear();
2520     }
2521 
2522     void dump(raw_ostream &os) const {
2523       if (!isSchedulingEntity()) {
2524         os << "/ " << *Inst;
2525       } else if (NextInBundle) {
2526         os << '[' << *Inst;
2527         ScheduleData *SD = NextInBundle;
2528         while (SD) {
2529           os << ';' << *SD->Inst;
2530           SD = SD->NextInBundle;
2531         }
2532         os << ']';
2533       } else {
2534         os << *Inst;
2535       }
2536     }
2537 
2538     Instruction *Inst = nullptr;
2539 
2540     /// Points to the head in an instruction bundle (and always to this for
2541     /// single instructions).
2542     ScheduleData *FirstInBundle = nullptr;
2543 
2544     /// Single linked list of all instructions in a bundle. Null if it is a
2545     /// single instruction.
2546     ScheduleData *NextInBundle = nullptr;
2547 
2548     /// Single linked list of all memory instructions (e.g. load, store, call)
2549     /// in the block - until the end of the scheduling region.
2550     ScheduleData *NextLoadStore = nullptr;
2551 
2552     /// The dependent memory instructions.
2553     /// This list is derived on demand in calculateDependencies().
2554     SmallVector<ScheduleData *, 4> MemoryDependencies;
2555 
2556     /// This ScheduleData is in the current scheduling region if this matches
2557     /// the current SchedulingRegionID of BlockScheduling.
2558     int SchedulingRegionID = 0;
2559 
2560     /// Used for getting a "good" final ordering of instructions.
2561     int SchedulingPriority = 0;
2562 
2563     /// The number of dependencies. Constitutes of the number of users of the
2564     /// instruction plus the number of dependent memory instructions (if any).
2565     /// This value is calculated on demand.
2566     /// If InvalidDeps, the number of dependencies is not calculated yet.
2567     int Dependencies = InvalidDeps;
2568 
2569     /// The number of dependencies minus the number of dependencies of scheduled
2570     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2571     /// for scheduling.
2572     /// Note that this is negative as long as Dependencies is not calculated.
2573     int UnscheduledDeps = InvalidDeps;
2574 
2575     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2576     /// single instructions.
2577     int UnscheduledDepsInBundle = InvalidDeps;
2578 
2579     /// True if this instruction is scheduled (or considered as scheduled in the
2580     /// dry-run).
2581     bool IsScheduled = false;
2582 
2583     /// Opcode of the current instruction in the schedule data.
2584     Value *OpValue = nullptr;
2585 
2586     /// The TreeEntry that this instruction corresponds to.
2587     TreeEntry *TE = nullptr;
2588 
2589     /// The lane of this node in the TreeEntry.
2590     int Lane = -1;
2591   };
2592 
2593 #ifndef NDEBUG
2594   friend inline raw_ostream &operator<<(raw_ostream &os,
2595                                         const BoUpSLP::ScheduleData &SD) {
2596     SD.dump(os);
2597     return os;
2598   }
2599 #endif
2600 
2601   friend struct GraphTraits<BoUpSLP *>;
2602   friend struct DOTGraphTraits<BoUpSLP *>;
2603 
2604   /// Contains all scheduling data for a basic block.
2605   struct BlockScheduling {
2606     BlockScheduling(BasicBlock *BB)
2607         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2608 
2609     void clear() {
2610       ReadyInsts.clear();
2611       ScheduleStart = nullptr;
2612       ScheduleEnd = nullptr;
2613       FirstLoadStoreInRegion = nullptr;
2614       LastLoadStoreInRegion = nullptr;
2615 
2616       // Reduce the maximum schedule region size by the size of the
2617       // previous scheduling run.
2618       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2619       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2620         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2621       ScheduleRegionSize = 0;
2622 
2623       // Make a new scheduling region, i.e. all existing ScheduleData is not
2624       // in the new region yet.
2625       ++SchedulingRegionID;
2626     }
2627 
2628     ScheduleData *getScheduleData(Value *V) {
2629       ScheduleData *SD = ScheduleDataMap[V];
2630       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2631         return SD;
2632       return nullptr;
2633     }
2634 
2635     ScheduleData *getScheduleData(Value *V, Value *Key) {
2636       if (V == Key)
2637         return getScheduleData(V);
2638       auto I = ExtraScheduleDataMap.find(V);
2639       if (I != ExtraScheduleDataMap.end()) {
2640         ScheduleData *SD = I->second[Key];
2641         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2642           return SD;
2643       }
2644       return nullptr;
2645     }
2646 
2647     bool isInSchedulingRegion(ScheduleData *SD) const {
2648       return SD->SchedulingRegionID == SchedulingRegionID;
2649     }
2650 
2651     /// Marks an instruction as scheduled and puts all dependent ready
2652     /// instructions into the ready-list.
2653     template <typename ReadyListType>
2654     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2655       SD->IsScheduled = true;
2656       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2657 
2658       for (ScheduleData *BundleMember = SD; BundleMember;
2659            BundleMember = BundleMember->NextInBundle) {
2660         if (BundleMember->Inst != BundleMember->OpValue)
2661           continue;
2662 
2663         // Handle the def-use chain dependencies.
2664 
2665         // Decrement the unscheduled counter and insert to ready list if ready.
2666         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2667           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2668             if (OpDef && OpDef->hasValidDependencies() &&
2669                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2670               // There are no more unscheduled dependencies after
2671               // decrementing, so we can put the dependent instruction
2672               // into the ready list.
2673               ScheduleData *DepBundle = OpDef->FirstInBundle;
2674               assert(!DepBundle->IsScheduled &&
2675                      "already scheduled bundle gets ready");
2676               ReadyList.insert(DepBundle);
2677               LLVM_DEBUG(dbgs()
2678                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2679             }
2680           });
2681         };
2682 
2683         // If BundleMember is a vector bundle, its operands may have been
2684         // reordered during buildTree(). We therefore need to get its operands
2685         // through the TreeEntry.
2686         if (TreeEntry *TE = BundleMember->TE) {
2687           int Lane = BundleMember->Lane;
2688           assert(Lane >= 0 && "Lane not set");
2689 
2690           // Since vectorization tree is being built recursively this assertion
2691           // ensures that the tree entry has all operands set before reaching
2692           // this code. Couple of exceptions known at the moment are extracts
2693           // where their second (immediate) operand is not added. Since
2694           // immediates do not affect scheduler behavior this is considered
2695           // okay.
2696           auto *In = TE->getMainOp();
2697           assert(In &&
2698                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2699                   In->getNumOperands() == TE->getNumOperands()) &&
2700                  "Missed TreeEntry operands?");
2701           (void)In; // fake use to avoid build failure when assertions disabled
2702 
2703           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2704                OpIdx != NumOperands; ++OpIdx)
2705             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2706               DecrUnsched(I);
2707         } else {
2708           // If BundleMember is a stand-alone instruction, no operand reordering
2709           // has taken place, so we directly access its operands.
2710           for (Use &U : BundleMember->Inst->operands())
2711             if (auto *I = dyn_cast<Instruction>(U.get()))
2712               DecrUnsched(I);
2713         }
2714         // Handle the memory dependencies.
2715         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2716           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2717             // There are no more unscheduled dependencies after decrementing,
2718             // so we can put the dependent instruction into the ready list.
2719             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2720             assert(!DepBundle->IsScheduled &&
2721                    "already scheduled bundle gets ready");
2722             ReadyList.insert(DepBundle);
2723             LLVM_DEBUG(dbgs()
2724                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2725           }
2726         }
2727       }
2728     }
2729 
2730     /// Verify basic self consistency properties of the data structure.
2731     void verify() {
2732       if (!ScheduleStart)
2733         return;
2734 
2735       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2736              ScheduleStart->comesBefore(ScheduleEnd) &&
2737              "Not a valid scheduling region?");
2738 
2739       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2740         auto *SD = getScheduleData(I);
2741         assert(SD && "primary scheduledata must exist in window");
2742         assert(isInSchedulingRegion(SD) &&
2743                "primary schedule data not in window?");
2744         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2745       }
2746     }
2747 
2748     void doForAllOpcodes(Value *V,
2749                          function_ref<void(ScheduleData *SD)> Action) {
2750       if (ScheduleData *SD = getScheduleData(V))
2751         Action(SD);
2752       auto I = ExtraScheduleDataMap.find(V);
2753       if (I != ExtraScheduleDataMap.end())
2754         for (auto &P : I->second)
2755           if (P.second->SchedulingRegionID == SchedulingRegionID)
2756             Action(P.second);
2757     }
2758 
2759     /// Put all instructions into the ReadyList which are ready for scheduling.
2760     template <typename ReadyListType>
2761     void initialFillReadyList(ReadyListType &ReadyList) {
2762       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2763         doForAllOpcodes(I, [&](ScheduleData *SD) {
2764           if (SD->isSchedulingEntity() && SD->isReady()) {
2765             ReadyList.insert(SD);
2766             LLVM_DEBUG(dbgs()
2767                        << "SLP:    initially in ready list: " << *I << "\n");
2768           }
2769         });
2770       }
2771     }
2772 
2773     /// Build a bundle from the ScheduleData nodes corresponding to the
2774     /// scalar instruction for each lane.
2775     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2776 
2777     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2778     /// cyclic dependencies. This is only a dry-run, no instructions are
2779     /// actually moved at this stage.
2780     /// \returns the scheduling bundle. The returned Optional value is non-None
2781     /// if \p VL is allowed to be scheduled.
2782     Optional<ScheduleData *>
2783     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2784                       const InstructionsState &S);
2785 
2786     /// Un-bundles a group of instructions.
2787     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2788 
2789     /// Allocates schedule data chunk.
2790     ScheduleData *allocateScheduleDataChunks();
2791 
2792     /// Extends the scheduling region so that V is inside the region.
2793     /// \returns true if the region size is within the limit.
2794     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2795 
2796     /// Initialize the ScheduleData structures for new instructions in the
2797     /// scheduling region.
2798     void initScheduleData(Instruction *FromI, Instruction *ToI,
2799                           ScheduleData *PrevLoadStore,
2800                           ScheduleData *NextLoadStore);
2801 
2802     /// Updates the dependency information of a bundle and of all instructions/
2803     /// bundles which depend on the original bundle.
2804     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2805                                BoUpSLP *SLP);
2806 
2807     /// Sets all instruction in the scheduling region to un-scheduled.
2808     void resetSchedule();
2809 
2810     BasicBlock *BB;
2811 
2812     /// Simple memory allocation for ScheduleData.
2813     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2814 
2815     /// The size of a ScheduleData array in ScheduleDataChunks.
2816     int ChunkSize;
2817 
2818     /// The allocator position in the current chunk, which is the last entry
2819     /// of ScheduleDataChunks.
2820     int ChunkPos;
2821 
2822     /// Attaches ScheduleData to Instruction.
2823     /// Note that the mapping survives during all vectorization iterations, i.e.
2824     /// ScheduleData structures are recycled.
2825     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2826 
2827     /// Attaches ScheduleData to Instruction with the leading key.
2828     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2829         ExtraScheduleDataMap;
2830 
2831     struct ReadyList : SmallVector<ScheduleData *, 8> {
2832       void insert(ScheduleData *SD) { push_back(SD); }
2833     };
2834 
2835     /// The ready-list for scheduling (only used for the dry-run).
2836     ReadyList ReadyInsts;
2837 
2838     /// The first instruction of the scheduling region.
2839     Instruction *ScheduleStart = nullptr;
2840 
2841     /// The first instruction _after_ the scheduling region.
2842     Instruction *ScheduleEnd = nullptr;
2843 
2844     /// The first memory accessing instruction in the scheduling region
2845     /// (can be null).
2846     ScheduleData *FirstLoadStoreInRegion = nullptr;
2847 
2848     /// The last memory accessing instruction in the scheduling region
2849     /// (can be null).
2850     ScheduleData *LastLoadStoreInRegion = nullptr;
2851 
2852     /// The current size of the scheduling region.
2853     int ScheduleRegionSize = 0;
2854 
2855     /// The maximum size allowed for the scheduling region.
2856     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2857 
2858     /// The ID of the scheduling region. For a new vectorization iteration this
2859     /// is incremented which "removes" all ScheduleData from the region.
2860     // Make sure that the initial SchedulingRegionID is greater than the
2861     // initial SchedulingRegionID in ScheduleData (which is 0).
2862     int SchedulingRegionID = 1;
2863   };
2864 
2865   /// Attaches the BlockScheduling structures to basic blocks.
2866   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2867 
2868   /// Performs the "real" scheduling. Done before vectorization is actually
2869   /// performed in a basic block.
2870   void scheduleBlock(BlockScheduling *BS);
2871 
2872   /// List of users to ignore during scheduling and that don't need extracting.
2873   ArrayRef<Value *> UserIgnoreList;
2874 
2875   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2876   /// sorted SmallVectors of unsigned.
2877   struct OrdersTypeDenseMapInfo {
2878     static OrdersType getEmptyKey() {
2879       OrdersType V;
2880       V.push_back(~1U);
2881       return V;
2882     }
2883 
2884     static OrdersType getTombstoneKey() {
2885       OrdersType V;
2886       V.push_back(~2U);
2887       return V;
2888     }
2889 
2890     static unsigned getHashValue(const OrdersType &V) {
2891       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2892     }
2893 
2894     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2895       return LHS == RHS;
2896     }
2897   };
2898 
2899   // Analysis and block reference.
2900   Function *F;
2901   ScalarEvolution *SE;
2902   TargetTransformInfo *TTI;
2903   TargetLibraryInfo *TLI;
2904   AAResults *AA;
2905   LoopInfo *LI;
2906   DominatorTree *DT;
2907   AssumptionCache *AC;
2908   DemandedBits *DB;
2909   const DataLayout *DL;
2910   OptimizationRemarkEmitter *ORE;
2911 
2912   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2913   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2914 
2915   /// Instruction builder to construct the vectorized tree.
2916   IRBuilder<> Builder;
2917 
2918   /// A map of scalar integer values to the smallest bit width with which they
2919   /// can legally be represented. The values map to (width, signed) pairs,
2920   /// where "width" indicates the minimum bit width and "signed" is True if the
2921   /// value must be signed-extended, rather than zero-extended, back to its
2922   /// original width.
2923   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2924 };
2925 
2926 } // end namespace slpvectorizer
2927 
2928 template <> struct GraphTraits<BoUpSLP *> {
2929   using TreeEntry = BoUpSLP::TreeEntry;
2930 
2931   /// NodeRef has to be a pointer per the GraphWriter.
2932   using NodeRef = TreeEntry *;
2933 
2934   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2935 
2936   /// Add the VectorizableTree to the index iterator to be able to return
2937   /// TreeEntry pointers.
2938   struct ChildIteratorType
2939       : public iterator_adaptor_base<
2940             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2941     ContainerTy &VectorizableTree;
2942 
2943     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2944                       ContainerTy &VT)
2945         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2946 
2947     NodeRef operator*() { return I->UserTE; }
2948   };
2949 
2950   static NodeRef getEntryNode(BoUpSLP &R) {
2951     return R.VectorizableTree[0].get();
2952   }
2953 
2954   static ChildIteratorType child_begin(NodeRef N) {
2955     return {N->UserTreeIndices.begin(), N->Container};
2956   }
2957 
2958   static ChildIteratorType child_end(NodeRef N) {
2959     return {N->UserTreeIndices.end(), N->Container};
2960   }
2961 
2962   /// For the node iterator we just need to turn the TreeEntry iterator into a
2963   /// TreeEntry* iterator so that it dereferences to NodeRef.
2964   class nodes_iterator {
2965     using ItTy = ContainerTy::iterator;
2966     ItTy It;
2967 
2968   public:
2969     nodes_iterator(const ItTy &It2) : It(It2) {}
2970     NodeRef operator*() { return It->get(); }
2971     nodes_iterator operator++() {
2972       ++It;
2973       return *this;
2974     }
2975     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2976   };
2977 
2978   static nodes_iterator nodes_begin(BoUpSLP *R) {
2979     return nodes_iterator(R->VectorizableTree.begin());
2980   }
2981 
2982   static nodes_iterator nodes_end(BoUpSLP *R) {
2983     return nodes_iterator(R->VectorizableTree.end());
2984   }
2985 
2986   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2987 };
2988 
2989 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2990   using TreeEntry = BoUpSLP::TreeEntry;
2991 
2992   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2993 
2994   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2995     std::string Str;
2996     raw_string_ostream OS(Str);
2997     if (isSplat(Entry->Scalars))
2998       OS << "<splat> ";
2999     for (auto V : Entry->Scalars) {
3000       OS << *V;
3001       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3002             return EU.Scalar == V;
3003           }))
3004         OS << " <extract>";
3005       OS << "\n";
3006     }
3007     return Str;
3008   }
3009 
3010   static std::string getNodeAttributes(const TreeEntry *Entry,
3011                                        const BoUpSLP *) {
3012     if (Entry->State == TreeEntry::NeedToGather)
3013       return "color=red";
3014     return "";
3015   }
3016 };
3017 
3018 } // end namespace llvm
3019 
3020 BoUpSLP::~BoUpSLP() {
3021   for (const auto &Pair : DeletedInstructions) {
3022     // Replace operands of ignored instructions with Undefs in case if they were
3023     // marked for deletion.
3024     if (Pair.getSecond()) {
3025       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3026       Pair.getFirst()->replaceAllUsesWith(Undef);
3027     }
3028     Pair.getFirst()->dropAllReferences();
3029   }
3030   for (const auto &Pair : DeletedInstructions) {
3031     assert(Pair.getFirst()->use_empty() &&
3032            "trying to erase instruction with users.");
3033     Pair.getFirst()->eraseFromParent();
3034   }
3035 #ifdef EXPENSIVE_CHECKS
3036   // If we could guarantee that this call is not extremely slow, we could
3037   // remove the ifdef limitation (see PR47712).
3038   assert(!verifyFunction(*F, &dbgs()));
3039 #endif
3040 }
3041 
3042 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3043   for (auto *V : AV) {
3044     if (auto *I = dyn_cast<Instruction>(V))
3045       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3046   };
3047 }
3048 
3049 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3050 /// contains original mask for the scalars reused in the node. Procedure
3051 /// transform this mask in accordance with the given \p Mask.
3052 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3053   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3054          "Expected non-empty mask.");
3055   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3056   Prev.swap(Reuses);
3057   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3058     if (Mask[I] != UndefMaskElem)
3059       Reuses[Mask[I]] = Prev[I];
3060 }
3061 
3062 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3063 /// the original order of the scalars. Procedure transforms the provided order
3064 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3065 /// identity order, \p Order is cleared.
3066 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3067   assert(!Mask.empty() && "Expected non-empty mask.");
3068   SmallVector<int> MaskOrder;
3069   if (Order.empty()) {
3070     MaskOrder.resize(Mask.size());
3071     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3072   } else {
3073     inversePermutation(Order, MaskOrder);
3074   }
3075   reorderReuses(MaskOrder, Mask);
3076   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3077     Order.clear();
3078     return;
3079   }
3080   Order.assign(Mask.size(), Mask.size());
3081   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3082     if (MaskOrder[I] != UndefMaskElem)
3083       Order[MaskOrder[I]] = I;
3084   fixupOrderingIndices(Order);
3085 }
3086 
3087 Optional<BoUpSLP::OrdersType>
3088 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3089   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3090   unsigned NumScalars = TE.Scalars.size();
3091   OrdersType CurrentOrder(NumScalars, NumScalars);
3092   SmallVector<int> Positions;
3093   SmallBitVector UsedPositions(NumScalars);
3094   const TreeEntry *STE = nullptr;
3095   // Try to find all gathered scalars that are gets vectorized in other
3096   // vectorize node. Here we can have only one single tree vector node to
3097   // correctly identify order of the gathered scalars.
3098   for (unsigned I = 0; I < NumScalars; ++I) {
3099     Value *V = TE.Scalars[I];
3100     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3101       continue;
3102     if (const auto *LocalSTE = getTreeEntry(V)) {
3103       if (!STE)
3104         STE = LocalSTE;
3105       else if (STE != LocalSTE)
3106         // Take the order only from the single vector node.
3107         return None;
3108       unsigned Lane =
3109           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3110       if (Lane >= NumScalars)
3111         return None;
3112       if (CurrentOrder[Lane] != NumScalars) {
3113         if (Lane != I)
3114           continue;
3115         UsedPositions.reset(CurrentOrder[Lane]);
3116       }
3117       // The partial identity (where only some elements of the gather node are
3118       // in the identity order) is good.
3119       CurrentOrder[Lane] = I;
3120       UsedPositions.set(I);
3121     }
3122   }
3123   // Need to keep the order if we have a vector entry and at least 2 scalars or
3124   // the vectorized entry has just 2 scalars.
3125   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3126     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3127       for (unsigned I = 0; I < NumScalars; ++I)
3128         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3129           return false;
3130       return true;
3131     };
3132     if (IsIdentityOrder(CurrentOrder)) {
3133       CurrentOrder.clear();
3134       return CurrentOrder;
3135     }
3136     auto *It = CurrentOrder.begin();
3137     for (unsigned I = 0; I < NumScalars;) {
3138       if (UsedPositions.test(I)) {
3139         ++I;
3140         continue;
3141       }
3142       if (*It == NumScalars) {
3143         *It = I;
3144         ++I;
3145       }
3146       ++It;
3147     }
3148     return CurrentOrder;
3149   }
3150   return None;
3151 }
3152 
3153 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3154                                                          bool TopToBottom) {
3155   // No need to reorder if need to shuffle reuses, still need to shuffle the
3156   // node.
3157   if (!TE.ReuseShuffleIndices.empty())
3158     return None;
3159   if (TE.State == TreeEntry::Vectorize &&
3160       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3161        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3162       !TE.isAltShuffle())
3163     return TE.ReorderIndices;
3164   if (TE.State == TreeEntry::NeedToGather) {
3165     // TODO: add analysis of other gather nodes with extractelement
3166     // instructions and other values/instructions, not only undefs.
3167     if (((TE.getOpcode() == Instruction::ExtractElement &&
3168           !TE.isAltShuffle()) ||
3169          (all_of(TE.Scalars,
3170                  [](Value *V) {
3171                    return isa<UndefValue, ExtractElementInst>(V);
3172                  }) &&
3173           any_of(TE.Scalars,
3174                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3175         all_of(TE.Scalars,
3176                [](Value *V) {
3177                  auto *EE = dyn_cast<ExtractElementInst>(V);
3178                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3179                }) &&
3180         allSameType(TE.Scalars)) {
3181       // Check that gather of extractelements can be represented as
3182       // just a shuffle of a single vector.
3183       OrdersType CurrentOrder;
3184       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3185       if (Reuse || !CurrentOrder.empty()) {
3186         if (!CurrentOrder.empty())
3187           fixupOrderingIndices(CurrentOrder);
3188         return CurrentOrder;
3189       }
3190     }
3191     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3192       return CurrentOrder;
3193   }
3194   return None;
3195 }
3196 
3197 void BoUpSLP::reorderTopToBottom() {
3198   // Maps VF to the graph nodes.
3199   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3200   // ExtractElement gather nodes which can be vectorized and need to handle
3201   // their ordering.
3202   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3203   // Find all reorderable nodes with the given VF.
3204   // Currently the are vectorized stores,loads,extracts + some gathering of
3205   // extracts.
3206   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3207                                  const std::unique_ptr<TreeEntry> &TE) {
3208     if (Optional<OrdersType> CurrentOrder =
3209             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3210       // Do not include ordering for nodes used in the alt opcode vectorization,
3211       // better to reorder them during bottom-to-top stage. If follow the order
3212       // here, it causes reordering of the whole graph though actually it is
3213       // profitable just to reorder the subgraph that starts from the alternate
3214       // opcode vectorization node. Such nodes already end-up with the shuffle
3215       // instruction and it is just enough to change this shuffle rather than
3216       // rotate the scalars for the whole graph.
3217       unsigned Cnt = 0;
3218       const TreeEntry *UserTE = TE.get();
3219       while (UserTE && Cnt < RecursionMaxDepth) {
3220         if (UserTE->UserTreeIndices.size() != 1)
3221           break;
3222         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3223               return EI.UserTE->State == TreeEntry::Vectorize &&
3224                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3225             }))
3226           return;
3227         if (UserTE->UserTreeIndices.empty())
3228           UserTE = nullptr;
3229         else
3230           UserTE = UserTE->UserTreeIndices.back().UserTE;
3231         ++Cnt;
3232       }
3233       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3234       if (TE->State != TreeEntry::Vectorize)
3235         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3236     }
3237   });
3238 
3239   // Reorder the graph nodes according to their vectorization factor.
3240   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3241        VF /= 2) {
3242     auto It = VFToOrderedEntries.find(VF);
3243     if (It == VFToOrderedEntries.end())
3244       continue;
3245     // Try to find the most profitable order. We just are looking for the most
3246     // used order and reorder scalar elements in the nodes according to this
3247     // mostly used order.
3248     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3249     // All operands are reordered and used only in this node - propagate the
3250     // most used order to the user node.
3251     MapVector<OrdersType, unsigned,
3252               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3253         OrdersUses;
3254     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3255     for (const TreeEntry *OpTE : OrderedEntries) {
3256       // No need to reorder this nodes, still need to extend and to use shuffle,
3257       // just need to merge reordering shuffle and the reuse shuffle.
3258       if (!OpTE->ReuseShuffleIndices.empty())
3259         continue;
3260       // Count number of orders uses.
3261       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3262         if (OpTE->State == TreeEntry::NeedToGather)
3263           return GathersToOrders.find(OpTE)->second;
3264         return OpTE->ReorderIndices;
3265       }();
3266       // Stores actually store the mask, not the order, need to invert.
3267       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3268           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3269         SmallVector<int> Mask;
3270         inversePermutation(Order, Mask);
3271         unsigned E = Order.size();
3272         OrdersType CurrentOrder(E, E);
3273         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3274           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3275         });
3276         fixupOrderingIndices(CurrentOrder);
3277         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3278       } else {
3279         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3280       }
3281     }
3282     // Set order of the user node.
3283     if (OrdersUses.empty())
3284       continue;
3285     // Choose the most used order.
3286     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3287     unsigned Cnt = OrdersUses.front().second;
3288     for (const auto &Pair : drop_begin(OrdersUses)) {
3289       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3290         BestOrder = Pair.first;
3291         Cnt = Pair.second;
3292       }
3293     }
3294     // Set order of the user node.
3295     if (BestOrder.empty())
3296       continue;
3297     SmallVector<int> Mask;
3298     inversePermutation(BestOrder, Mask);
3299     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3300     unsigned E = BestOrder.size();
3301     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3302       return I < E ? static_cast<int>(I) : UndefMaskElem;
3303     });
3304     // Do an actual reordering, if profitable.
3305     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3306       // Just do the reordering for the nodes with the given VF.
3307       if (TE->Scalars.size() != VF) {
3308         if (TE->ReuseShuffleIndices.size() == VF) {
3309           // Need to reorder the reuses masks of the operands with smaller VF to
3310           // be able to find the match between the graph nodes and scalar
3311           // operands of the given node during vectorization/cost estimation.
3312           assert(all_of(TE->UserTreeIndices,
3313                         [VF, &TE](const EdgeInfo &EI) {
3314                           return EI.UserTE->Scalars.size() == VF ||
3315                                  EI.UserTE->Scalars.size() ==
3316                                      TE->Scalars.size();
3317                         }) &&
3318                  "All users must be of VF size.");
3319           // Update ordering of the operands with the smaller VF than the given
3320           // one.
3321           reorderReuses(TE->ReuseShuffleIndices, Mask);
3322         }
3323         continue;
3324       }
3325       if (TE->State == TreeEntry::Vectorize &&
3326           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3327               InsertElementInst>(TE->getMainOp()) &&
3328           !TE->isAltShuffle()) {
3329         // Build correct orders for extract{element,value}, loads and
3330         // stores.
3331         reorderOrder(TE->ReorderIndices, Mask);
3332         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3333           TE->reorderOperands(Mask);
3334       } else {
3335         // Reorder the node and its operands.
3336         TE->reorderOperands(Mask);
3337         assert(TE->ReorderIndices.empty() &&
3338                "Expected empty reorder sequence.");
3339         reorderScalars(TE->Scalars, Mask);
3340       }
3341       if (!TE->ReuseShuffleIndices.empty()) {
3342         // Apply reversed order to keep the original ordering of the reused
3343         // elements to avoid extra reorder indices shuffling.
3344         OrdersType CurrentOrder;
3345         reorderOrder(CurrentOrder, MaskOrder);
3346         SmallVector<int> NewReuses;
3347         inversePermutation(CurrentOrder, NewReuses);
3348         addMask(NewReuses, TE->ReuseShuffleIndices);
3349         TE->ReuseShuffleIndices.swap(NewReuses);
3350       }
3351     }
3352   }
3353 }
3354 
3355 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3356   SetVector<TreeEntry *> OrderedEntries;
3357   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3358   // Find all reorderable leaf nodes with the given VF.
3359   // Currently the are vectorized loads,extracts without alternate operands +
3360   // some gathering of extracts.
3361   SmallVector<TreeEntry *> NonVectorized;
3362   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3363                               &NonVectorized](
3364                                  const std::unique_ptr<TreeEntry> &TE) {
3365     if (TE->State != TreeEntry::Vectorize)
3366       NonVectorized.push_back(TE.get());
3367     if (Optional<OrdersType> CurrentOrder =
3368             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3369       OrderedEntries.insert(TE.get());
3370       if (TE->State != TreeEntry::Vectorize)
3371         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3372     }
3373   });
3374 
3375   // Checks if the operands of the users are reordarable and have only single
3376   // use.
3377   auto &&CheckOperands =
3378       [this, &NonVectorized](const auto &Data,
3379                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3380         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3381           if (any_of(Data.second,
3382                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3383                        return OpData.first == I &&
3384                               OpData.second->State == TreeEntry::Vectorize;
3385                      }))
3386             continue;
3387           ArrayRef<Value *> VL = Data.first->getOperand(I);
3388           const TreeEntry *TE = nullptr;
3389           const auto *It = find_if(VL, [this, &TE](Value *V) {
3390             TE = getTreeEntry(V);
3391             return TE;
3392           });
3393           if (It != VL.end() && TE->isSame(VL))
3394             return false;
3395           TreeEntry *Gather = nullptr;
3396           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3397                 assert(TE->State != TreeEntry::Vectorize &&
3398                        "Only non-vectorized nodes are expected.");
3399                 if (TE->isSame(VL)) {
3400                   Gather = TE;
3401                   return true;
3402                 }
3403                 return false;
3404               }) > 1)
3405             return false;
3406           if (Gather)
3407             GatherOps.push_back(Gather);
3408         }
3409         return true;
3410       };
3411   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3412   // I.e., if the node has operands, that are reordered, try to make at least
3413   // one operand order in the natural order and reorder others + reorder the
3414   // user node itself.
3415   SmallPtrSet<const TreeEntry *, 4> Visited;
3416   while (!OrderedEntries.empty()) {
3417     // 1. Filter out only reordered nodes.
3418     // 2. If the entry has multiple uses - skip it and jump to the next node.
3419     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3420     SmallVector<TreeEntry *> Filtered;
3421     for (TreeEntry *TE : OrderedEntries) {
3422       if (!(TE->State == TreeEntry::Vectorize ||
3423             (TE->State == TreeEntry::NeedToGather &&
3424              GathersToOrders.count(TE))) ||
3425           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3426           !all_of(drop_begin(TE->UserTreeIndices),
3427                   [TE](const EdgeInfo &EI) {
3428                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3429                   }) ||
3430           !Visited.insert(TE).second) {
3431         Filtered.push_back(TE);
3432         continue;
3433       }
3434       // Build a map between user nodes and their operands order to speedup
3435       // search. The graph currently does not provide this dependency directly.
3436       for (EdgeInfo &EI : TE->UserTreeIndices) {
3437         TreeEntry *UserTE = EI.UserTE;
3438         auto It = Users.find(UserTE);
3439         if (It == Users.end())
3440           It = Users.insert({UserTE, {}}).first;
3441         It->second.emplace_back(EI.EdgeIdx, TE);
3442       }
3443     }
3444     // Erase filtered entries.
3445     for_each(Filtered,
3446              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3447     for (const auto &Data : Users) {
3448       // Check that operands are used only in the User node.
3449       SmallVector<TreeEntry *> GatherOps;
3450       if (!CheckOperands(Data, GatherOps)) {
3451         for_each(Data.second,
3452                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3453                    OrderedEntries.remove(Op.second);
3454                  });
3455         continue;
3456       }
3457       // All operands are reordered and used only in this node - propagate the
3458       // most used order to the user node.
3459       MapVector<OrdersType, unsigned,
3460                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3461           OrdersUses;
3462       // Do the analysis for each tree entry only once, otherwise the order of
3463       // the same node my be considered several times, though might be not
3464       // profitable.
3465       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3466       for (const auto &Op : Data.second) {
3467         TreeEntry *OpTE = Op.second;
3468         if (!VisitedOps.insert(OpTE).second)
3469           continue;
3470         if (!OpTE->ReuseShuffleIndices.empty() ||
3471             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3472           continue;
3473         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3474           if (OpTE->State == TreeEntry::NeedToGather)
3475             return GathersToOrders.find(OpTE)->second;
3476           return OpTE->ReorderIndices;
3477         }();
3478         // Stores actually store the mask, not the order, need to invert.
3479         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3480             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3481           SmallVector<int> Mask;
3482           inversePermutation(Order, Mask);
3483           unsigned E = Order.size();
3484           OrdersType CurrentOrder(E, E);
3485           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3486             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3487           });
3488           fixupOrderingIndices(CurrentOrder);
3489           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3490         } else {
3491           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3492         }
3493         OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3494             OpTE->UserTreeIndices.size();
3495         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3496         --OrdersUses[{}];
3497       }
3498       // If no orders - skip current nodes and jump to the next one, if any.
3499       if (OrdersUses.empty()) {
3500         for_each(Data.second,
3501                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3502                    OrderedEntries.remove(Op.second);
3503                  });
3504         continue;
3505       }
3506       // Choose the best order.
3507       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3508       unsigned Cnt = OrdersUses.front().second;
3509       for (const auto &Pair : drop_begin(OrdersUses)) {
3510         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3511           BestOrder = Pair.first;
3512           Cnt = Pair.second;
3513         }
3514       }
3515       // Set order of the user node (reordering of operands and user nodes).
3516       if (BestOrder.empty()) {
3517         for_each(Data.second,
3518                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3519                    OrderedEntries.remove(Op.second);
3520                  });
3521         continue;
3522       }
3523       // Erase operands from OrderedEntries list and adjust their orders.
3524       VisitedOps.clear();
3525       SmallVector<int> Mask;
3526       inversePermutation(BestOrder, Mask);
3527       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3528       unsigned E = BestOrder.size();
3529       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3530         return I < E ? static_cast<int>(I) : UndefMaskElem;
3531       });
3532       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3533         TreeEntry *TE = Op.second;
3534         OrderedEntries.remove(TE);
3535         if (!VisitedOps.insert(TE).second)
3536           continue;
3537         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3538           // Just reorder reuses indices.
3539           reorderReuses(TE->ReuseShuffleIndices, Mask);
3540           continue;
3541         }
3542         // Gathers are processed separately.
3543         if (TE->State != TreeEntry::Vectorize)
3544           continue;
3545         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3546                 TE->ReorderIndices.empty()) &&
3547                "Non-matching sizes of user/operand entries.");
3548         reorderOrder(TE->ReorderIndices, Mask);
3549       }
3550       // For gathers just need to reorder its scalars.
3551       for (TreeEntry *Gather : GatherOps) {
3552         assert(Gather->ReorderIndices.empty() &&
3553                "Unexpected reordering of gathers.");
3554         if (!Gather->ReuseShuffleIndices.empty()) {
3555           // Just reorder reuses indices.
3556           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3557           continue;
3558         }
3559         reorderScalars(Gather->Scalars, Mask);
3560         OrderedEntries.remove(Gather);
3561       }
3562       // Reorder operands of the user node and set the ordering for the user
3563       // node itself.
3564       if (Data.first->State != TreeEntry::Vectorize ||
3565           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3566               Data.first->getMainOp()) ||
3567           Data.first->isAltShuffle())
3568         Data.first->reorderOperands(Mask);
3569       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3570           Data.first->isAltShuffle()) {
3571         reorderScalars(Data.first->Scalars, Mask);
3572         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3573         if (Data.first->ReuseShuffleIndices.empty() &&
3574             !Data.first->ReorderIndices.empty() &&
3575             !Data.first->isAltShuffle()) {
3576           // Insert user node to the list to try to sink reordering deeper in
3577           // the graph.
3578           OrderedEntries.insert(Data.first);
3579         }
3580       } else {
3581         reorderOrder(Data.first->ReorderIndices, Mask);
3582       }
3583     }
3584   }
3585   // If the reordering is unnecessary, just remove the reorder.
3586   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3587       VectorizableTree.front()->ReuseShuffleIndices.empty())
3588     VectorizableTree.front()->ReorderIndices.clear();
3589 }
3590 
3591 void BoUpSLP::buildExternalUses(
3592     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3593   // Collect the values that we need to extract from the tree.
3594   for (auto &TEPtr : VectorizableTree) {
3595     TreeEntry *Entry = TEPtr.get();
3596 
3597     // No need to handle users of gathered values.
3598     if (Entry->State == TreeEntry::NeedToGather)
3599       continue;
3600 
3601     // For each lane:
3602     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3603       Value *Scalar = Entry->Scalars[Lane];
3604       int FoundLane = Entry->findLaneForValue(Scalar);
3605 
3606       // Check if the scalar is externally used as an extra arg.
3607       auto ExtI = ExternallyUsedValues.find(Scalar);
3608       if (ExtI != ExternallyUsedValues.end()) {
3609         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3610                           << Lane << " from " << *Scalar << ".\n");
3611         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3612       }
3613       for (User *U : Scalar->users()) {
3614         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3615 
3616         Instruction *UserInst = dyn_cast<Instruction>(U);
3617         if (!UserInst)
3618           continue;
3619 
3620         if (isDeleted(UserInst))
3621           continue;
3622 
3623         // Skip in-tree scalars that become vectors
3624         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3625           Value *UseScalar = UseEntry->Scalars[0];
3626           // Some in-tree scalars will remain as scalar in vectorized
3627           // instructions. If that is the case, the one in Lane 0 will
3628           // be used.
3629           if (UseScalar != U ||
3630               UseEntry->State == TreeEntry::ScatterVectorize ||
3631               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3632             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3633                               << ".\n");
3634             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3635             continue;
3636           }
3637         }
3638 
3639         // Ignore users in the user ignore list.
3640         if (is_contained(UserIgnoreList, UserInst))
3641           continue;
3642 
3643         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3644                           << Lane << " from " << *Scalar << ".\n");
3645         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3646       }
3647     }
3648   }
3649 }
3650 
3651 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3652                         ArrayRef<Value *> UserIgnoreLst) {
3653   deleteTree();
3654   UserIgnoreList = UserIgnoreLst;
3655   if (!allSameType(Roots))
3656     return;
3657   buildTree_rec(Roots, 0, EdgeInfo());
3658 }
3659 
3660 namespace {
3661 /// Tracks the state we can represent the loads in the given sequence.
3662 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3663 } // anonymous namespace
3664 
3665 /// Checks if the given array of loads can be represented as a vectorized,
3666 /// scatter or just simple gather.
3667 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3668                                     const TargetTransformInfo &TTI,
3669                                     const DataLayout &DL, ScalarEvolution &SE,
3670                                     SmallVectorImpl<unsigned> &Order,
3671                                     SmallVectorImpl<Value *> &PointerOps) {
3672   // Check that a vectorized load would load the same memory as a scalar
3673   // load. For example, we don't want to vectorize loads that are smaller
3674   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3675   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3676   // from such a struct, we read/write packed bits disagreeing with the
3677   // unvectorized version.
3678   Type *ScalarTy = VL0->getType();
3679 
3680   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3681     return LoadsState::Gather;
3682 
3683   // Make sure all loads in the bundle are simple - we can't vectorize
3684   // atomic or volatile loads.
3685   PointerOps.clear();
3686   PointerOps.resize(VL.size());
3687   auto *POIter = PointerOps.begin();
3688   for (Value *V : VL) {
3689     auto *L = cast<LoadInst>(V);
3690     if (!L->isSimple())
3691       return LoadsState::Gather;
3692     *POIter = L->getPointerOperand();
3693     ++POIter;
3694   }
3695 
3696   Order.clear();
3697   // Check the order of pointer operands.
3698   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3699     Value *Ptr0;
3700     Value *PtrN;
3701     if (Order.empty()) {
3702       Ptr0 = PointerOps.front();
3703       PtrN = PointerOps.back();
3704     } else {
3705       Ptr0 = PointerOps[Order.front()];
3706       PtrN = PointerOps[Order.back()];
3707     }
3708     Optional<int> Diff =
3709         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3710     // Check that the sorted loads are consecutive.
3711     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3712       return LoadsState::Vectorize;
3713     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3714     for (Value *V : VL)
3715       CommonAlignment =
3716           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3717     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3718                                 CommonAlignment))
3719       return LoadsState::ScatterVectorize;
3720   }
3721 
3722   return LoadsState::Gather;
3723 }
3724 
3725 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3726                             const EdgeInfo &UserTreeIdx) {
3727   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3728 
3729   SmallVector<int> ReuseShuffleIndicies;
3730   SmallVector<Value *> UniqueValues;
3731   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3732                                 &UserTreeIdx,
3733                                 this](const InstructionsState &S) {
3734     // Check that every instruction appears once in this bundle.
3735     DenseMap<Value *, unsigned> UniquePositions;
3736     for (Value *V : VL) {
3737       if (isConstant(V)) {
3738         ReuseShuffleIndicies.emplace_back(
3739             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3740         UniqueValues.emplace_back(V);
3741         continue;
3742       }
3743       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3744       ReuseShuffleIndicies.emplace_back(Res.first->second);
3745       if (Res.second)
3746         UniqueValues.emplace_back(V);
3747     }
3748     size_t NumUniqueScalarValues = UniqueValues.size();
3749     if (NumUniqueScalarValues == VL.size()) {
3750       ReuseShuffleIndicies.clear();
3751     } else {
3752       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3753       if (NumUniqueScalarValues <= 1 ||
3754           (UniquePositions.size() == 1 && all_of(UniqueValues,
3755                                                  [](Value *V) {
3756                                                    return isa<UndefValue>(V) ||
3757                                                           !isConstant(V);
3758                                                  })) ||
3759           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3760         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3761         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3762         return false;
3763       }
3764       VL = UniqueValues;
3765     }
3766     return true;
3767   };
3768 
3769   InstructionsState S = getSameOpcode(VL);
3770   if (Depth == RecursionMaxDepth) {
3771     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3772     if (TryToFindDuplicates(S))
3773       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3774                    ReuseShuffleIndicies);
3775     return;
3776   }
3777 
3778   // Don't handle scalable vectors
3779   if (S.getOpcode() == Instruction::ExtractElement &&
3780       isa<ScalableVectorType>(
3781           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3782     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3783     if (TryToFindDuplicates(S))
3784       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3785                    ReuseShuffleIndicies);
3786     return;
3787   }
3788 
3789   // Don't handle vectors.
3790   if (S.OpValue->getType()->isVectorTy() &&
3791       !isa<InsertElementInst>(S.OpValue)) {
3792     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3793     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3794     return;
3795   }
3796 
3797   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3798     if (SI->getValueOperand()->getType()->isVectorTy()) {
3799       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3800       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3801       return;
3802     }
3803 
3804   // If all of the operands are identical or constant we have a simple solution.
3805   // If we deal with insert/extract instructions, they all must have constant
3806   // indices, otherwise we should gather them, not try to vectorize.
3807   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3808       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3809        !all_of(VL, isVectorLikeInstWithConstOps))) {
3810     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3811     if (TryToFindDuplicates(S))
3812       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3813                    ReuseShuffleIndicies);
3814     return;
3815   }
3816 
3817   // We now know that this is a vector of instructions of the same type from
3818   // the same block.
3819 
3820   // Don't vectorize ephemeral values.
3821   for (Value *V : VL) {
3822     if (EphValues.count(V)) {
3823       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3824                         << ") is ephemeral.\n");
3825       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3826       return;
3827     }
3828   }
3829 
3830   // Check if this is a duplicate of another entry.
3831   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3832     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3833     if (!E->isSame(VL)) {
3834       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3835       if (TryToFindDuplicates(S))
3836         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3837                      ReuseShuffleIndicies);
3838       return;
3839     }
3840     // Record the reuse of the tree node.  FIXME, currently this is only used to
3841     // properly draw the graph rather than for the actual vectorization.
3842     E->UserTreeIndices.push_back(UserTreeIdx);
3843     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3844                       << ".\n");
3845     return;
3846   }
3847 
3848   // Check that none of the instructions in the bundle are already in the tree.
3849   for (Value *V : VL) {
3850     auto *I = dyn_cast<Instruction>(V);
3851     if (!I)
3852       continue;
3853     if (getTreeEntry(I)) {
3854       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3855                         << ") is already in tree.\n");
3856       if (TryToFindDuplicates(S))
3857         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3858                      ReuseShuffleIndicies);
3859       return;
3860     }
3861   }
3862 
3863   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3864   for (Value *V : VL) {
3865     if (is_contained(UserIgnoreList, V)) {
3866       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3867       if (TryToFindDuplicates(S))
3868         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3869                      ReuseShuffleIndicies);
3870       return;
3871     }
3872   }
3873 
3874   // Check that all of the users of the scalars that we want to vectorize are
3875   // schedulable.
3876   auto *VL0 = cast<Instruction>(S.OpValue);
3877   BasicBlock *BB = VL0->getParent();
3878 
3879   if (!DT->isReachableFromEntry(BB)) {
3880     // Don't go into unreachable blocks. They may contain instructions with
3881     // dependency cycles which confuse the final scheduling.
3882     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3883     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3884     return;
3885   }
3886 
3887   // Check that every instruction appears once in this bundle.
3888   if (!TryToFindDuplicates(S))
3889     return;
3890 
3891   auto &BSRef = BlocksSchedules[BB];
3892   if (!BSRef)
3893     BSRef = std::make_unique<BlockScheduling>(BB);
3894 
3895   BlockScheduling &BS = *BSRef.get();
3896 
3897   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3898 #ifdef EXPENSIVE_CHECKS
3899   // Make sure we didn't break any internal invariants
3900   BS.verify();
3901 #endif
3902   if (!Bundle) {
3903     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3904     assert((!BS.getScheduleData(VL0) ||
3905             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3906            "tryScheduleBundle should cancelScheduling on failure");
3907     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3908                  ReuseShuffleIndicies);
3909     return;
3910   }
3911   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3912 
3913   unsigned ShuffleOrOp = S.isAltShuffle() ?
3914                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3915   switch (ShuffleOrOp) {
3916     case Instruction::PHI: {
3917       auto *PH = cast<PHINode>(VL0);
3918 
3919       // Check for terminator values (e.g. invoke).
3920       for (Value *V : VL)
3921         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3922           Instruction *Term = dyn_cast<Instruction>(
3923               cast<PHINode>(V)->getIncomingValueForBlock(
3924                   PH->getIncomingBlock(I)));
3925           if (Term && Term->isTerminator()) {
3926             LLVM_DEBUG(dbgs()
3927                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3928             BS.cancelScheduling(VL, VL0);
3929             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3930                          ReuseShuffleIndicies);
3931             return;
3932           }
3933         }
3934 
3935       TreeEntry *TE =
3936           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3937       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3938 
3939       // Keeps the reordered operands to avoid code duplication.
3940       SmallVector<ValueList, 2> OperandsVec;
3941       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3942         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3943           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3944           TE->setOperand(I, Operands);
3945           OperandsVec.push_back(Operands);
3946           continue;
3947         }
3948         ValueList Operands;
3949         // Prepare the operand vector.
3950         for (Value *V : VL)
3951           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3952               PH->getIncomingBlock(I)));
3953         TE->setOperand(I, Operands);
3954         OperandsVec.push_back(Operands);
3955       }
3956       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3957         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3958       return;
3959     }
3960     case Instruction::ExtractValue:
3961     case Instruction::ExtractElement: {
3962       OrdersType CurrentOrder;
3963       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3964       if (Reuse) {
3965         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3966         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3967                      ReuseShuffleIndicies);
3968         // This is a special case, as it does not gather, but at the same time
3969         // we are not extending buildTree_rec() towards the operands.
3970         ValueList Op0;
3971         Op0.assign(VL.size(), VL0->getOperand(0));
3972         VectorizableTree.back()->setOperand(0, Op0);
3973         return;
3974       }
3975       if (!CurrentOrder.empty()) {
3976         LLVM_DEBUG({
3977           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3978                     "with order";
3979           for (unsigned Idx : CurrentOrder)
3980             dbgs() << " " << Idx;
3981           dbgs() << "\n";
3982         });
3983         fixupOrderingIndices(CurrentOrder);
3984         // Insert new order with initial value 0, if it does not exist,
3985         // otherwise return the iterator to the existing one.
3986         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3987                      ReuseShuffleIndicies, CurrentOrder);
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       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3996       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3997                    ReuseShuffleIndicies);
3998       BS.cancelScheduling(VL, VL0);
3999       return;
4000     }
4001     case Instruction::InsertElement: {
4002       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4003 
4004       // Check that we have a buildvector and not a shuffle of 2 or more
4005       // different vectors.
4006       ValueSet SourceVectors;
4007       int MinIdx = std::numeric_limits<int>::max();
4008       for (Value *V : VL) {
4009         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4010         Optional<int> Idx = *getInsertIndex(V, 0);
4011         if (!Idx || *Idx == UndefMaskElem)
4012           continue;
4013         MinIdx = std::min(MinIdx, *Idx);
4014       }
4015 
4016       if (count_if(VL, [&SourceVectors](Value *V) {
4017             return !SourceVectors.contains(V);
4018           }) >= 2) {
4019         // Found 2nd source vector - cancel.
4020         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4021                              "different source vectors.\n");
4022         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4023         BS.cancelScheduling(VL, VL0);
4024         return;
4025       }
4026 
4027       auto OrdCompare = [](const std::pair<int, int> &P1,
4028                            const std::pair<int, int> &P2) {
4029         return P1.first > P2.first;
4030       };
4031       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4032                     decltype(OrdCompare)>
4033           Indices(OrdCompare);
4034       for (int I = 0, E = VL.size(); I < E; ++I) {
4035         Optional<int> Idx = *getInsertIndex(VL[I], 0);
4036         if (!Idx || *Idx == UndefMaskElem)
4037           continue;
4038         Indices.emplace(*Idx, I);
4039       }
4040       OrdersType CurrentOrder(VL.size(), VL.size());
4041       bool IsIdentity = true;
4042       for (int I = 0, E = VL.size(); I < E; ++I) {
4043         CurrentOrder[Indices.top().second] = I;
4044         IsIdentity &= Indices.top().second == I;
4045         Indices.pop();
4046       }
4047       if (IsIdentity)
4048         CurrentOrder.clear();
4049       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4050                                    None, CurrentOrder);
4051       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4052 
4053       constexpr int NumOps = 2;
4054       ValueList VectorOperands[NumOps];
4055       for (int I = 0; I < NumOps; ++I) {
4056         for (Value *V : VL)
4057           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4058 
4059         TE->setOperand(I, VectorOperands[I]);
4060       }
4061       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4062       return;
4063     }
4064     case Instruction::Load: {
4065       // Check that a vectorized load would load the same memory as a scalar
4066       // load. For example, we don't want to vectorize loads that are smaller
4067       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4068       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4069       // from such a struct, we read/write packed bits disagreeing with the
4070       // unvectorized version.
4071       SmallVector<Value *> PointerOps;
4072       OrdersType CurrentOrder;
4073       TreeEntry *TE = nullptr;
4074       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4075                                 PointerOps)) {
4076       case LoadsState::Vectorize:
4077         if (CurrentOrder.empty()) {
4078           // Original loads are consecutive and does not require reordering.
4079           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4080                             ReuseShuffleIndicies);
4081           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4082         } else {
4083           fixupOrderingIndices(CurrentOrder);
4084           // Need to reorder.
4085           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4086                             ReuseShuffleIndicies, CurrentOrder);
4087           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4088         }
4089         TE->setOperandsInOrder();
4090         break;
4091       case LoadsState::ScatterVectorize:
4092         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4093         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4094                           UserTreeIdx, ReuseShuffleIndicies);
4095         TE->setOperandsInOrder();
4096         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4097         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4098         break;
4099       case LoadsState::Gather:
4100         BS.cancelScheduling(VL, VL0);
4101         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4102                      ReuseShuffleIndicies);
4103 #ifndef NDEBUG
4104         Type *ScalarTy = VL0->getType();
4105         if (DL->getTypeSizeInBits(ScalarTy) !=
4106             DL->getTypeAllocSizeInBits(ScalarTy))
4107           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4108         else if (any_of(VL, [](Value *V) {
4109                    return !cast<LoadInst>(V)->isSimple();
4110                  }))
4111           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4112         else
4113           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4114 #endif // NDEBUG
4115         break;
4116       }
4117       return;
4118     }
4119     case Instruction::ZExt:
4120     case Instruction::SExt:
4121     case Instruction::FPToUI:
4122     case Instruction::FPToSI:
4123     case Instruction::FPExt:
4124     case Instruction::PtrToInt:
4125     case Instruction::IntToPtr:
4126     case Instruction::SIToFP:
4127     case Instruction::UIToFP:
4128     case Instruction::Trunc:
4129     case Instruction::FPTrunc:
4130     case Instruction::BitCast: {
4131       Type *SrcTy = VL0->getOperand(0)->getType();
4132       for (Value *V : VL) {
4133         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4134         if (Ty != SrcTy || !isValidElementType(Ty)) {
4135           BS.cancelScheduling(VL, VL0);
4136           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4137                        ReuseShuffleIndicies);
4138           LLVM_DEBUG(dbgs()
4139                      << "SLP: Gathering casts with different src types.\n");
4140           return;
4141         }
4142       }
4143       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4144                                    ReuseShuffleIndicies);
4145       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4146 
4147       TE->setOperandsInOrder();
4148       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4149         ValueList Operands;
4150         // Prepare the operand vector.
4151         for (Value *V : VL)
4152           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4153 
4154         buildTree_rec(Operands, Depth + 1, {TE, i});
4155       }
4156       return;
4157     }
4158     case Instruction::ICmp:
4159     case Instruction::FCmp: {
4160       // Check that all of the compares have the same predicate.
4161       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4162       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4163       Type *ComparedTy = VL0->getOperand(0)->getType();
4164       for (Value *V : VL) {
4165         CmpInst *Cmp = cast<CmpInst>(V);
4166         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4167             Cmp->getOperand(0)->getType() != ComparedTy) {
4168           BS.cancelScheduling(VL, VL0);
4169           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4170                        ReuseShuffleIndicies);
4171           LLVM_DEBUG(dbgs()
4172                      << "SLP: Gathering cmp with different predicate.\n");
4173           return;
4174         }
4175       }
4176 
4177       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4178                                    ReuseShuffleIndicies);
4179       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4180 
4181       ValueList Left, Right;
4182       if (cast<CmpInst>(VL0)->isCommutative()) {
4183         // Commutative predicate - collect + sort operands of the instructions
4184         // so that each side is more likely to have the same opcode.
4185         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4186         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4187       } else {
4188         // Collect operands - commute if it uses the swapped predicate.
4189         for (Value *V : VL) {
4190           auto *Cmp = cast<CmpInst>(V);
4191           Value *LHS = Cmp->getOperand(0);
4192           Value *RHS = Cmp->getOperand(1);
4193           if (Cmp->getPredicate() != P0)
4194             std::swap(LHS, RHS);
4195           Left.push_back(LHS);
4196           Right.push_back(RHS);
4197         }
4198       }
4199       TE->setOperand(0, Left);
4200       TE->setOperand(1, Right);
4201       buildTree_rec(Left, Depth + 1, {TE, 0});
4202       buildTree_rec(Right, Depth + 1, {TE, 1});
4203       return;
4204     }
4205     case Instruction::Select:
4206     case Instruction::FNeg:
4207     case Instruction::Add:
4208     case Instruction::FAdd:
4209     case Instruction::Sub:
4210     case Instruction::FSub:
4211     case Instruction::Mul:
4212     case Instruction::FMul:
4213     case Instruction::UDiv:
4214     case Instruction::SDiv:
4215     case Instruction::FDiv:
4216     case Instruction::URem:
4217     case Instruction::SRem:
4218     case Instruction::FRem:
4219     case Instruction::Shl:
4220     case Instruction::LShr:
4221     case Instruction::AShr:
4222     case Instruction::And:
4223     case Instruction::Or:
4224     case Instruction::Xor: {
4225       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4226                                    ReuseShuffleIndicies);
4227       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4228 
4229       // Sort operands of the instructions so that each side is more likely to
4230       // have the same opcode.
4231       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4232         ValueList Left, Right;
4233         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4234         TE->setOperand(0, Left);
4235         TE->setOperand(1, Right);
4236         buildTree_rec(Left, Depth + 1, {TE, 0});
4237         buildTree_rec(Right, Depth + 1, {TE, 1});
4238         return;
4239       }
4240 
4241       TE->setOperandsInOrder();
4242       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4243         ValueList Operands;
4244         // Prepare the operand vector.
4245         for (Value *V : VL)
4246           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4247 
4248         buildTree_rec(Operands, Depth + 1, {TE, i});
4249       }
4250       return;
4251     }
4252     case Instruction::GetElementPtr: {
4253       // We don't combine GEPs with complicated (nested) indexing.
4254       for (Value *V : VL) {
4255         if (cast<Instruction>(V)->getNumOperands() != 2) {
4256           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4257           BS.cancelScheduling(VL, VL0);
4258           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4259                        ReuseShuffleIndicies);
4260           return;
4261         }
4262       }
4263 
4264       // We can't combine several GEPs into one vector if they operate on
4265       // different types.
4266       Type *Ty0 = VL0->getOperand(0)->getType();
4267       for (Value *V : VL) {
4268         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4269         if (Ty0 != CurTy) {
4270           LLVM_DEBUG(dbgs()
4271                      << "SLP: not-vectorizable GEP (different types).\n");
4272           BS.cancelScheduling(VL, VL0);
4273           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4274                        ReuseShuffleIndicies);
4275           return;
4276         }
4277       }
4278 
4279       // We don't combine GEPs with non-constant indexes.
4280       Type *Ty1 = VL0->getOperand(1)->getType();
4281       for (Value *V : VL) {
4282         auto Op = cast<Instruction>(V)->getOperand(1);
4283         if (!isa<ConstantInt>(Op) ||
4284             (Op->getType() != Ty1 &&
4285              Op->getType()->getScalarSizeInBits() >
4286                  DL->getIndexSizeInBits(
4287                      V->getType()->getPointerAddressSpace()))) {
4288           LLVM_DEBUG(dbgs()
4289                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4290           BS.cancelScheduling(VL, VL0);
4291           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4292                        ReuseShuffleIndicies);
4293           return;
4294         }
4295       }
4296 
4297       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4298                                    ReuseShuffleIndicies);
4299       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4300       SmallVector<ValueList, 2> Operands(2);
4301       // Prepare the operand vector for pointer operands.
4302       for (Value *V : VL)
4303         Operands.front().push_back(
4304             cast<GetElementPtrInst>(V)->getPointerOperand());
4305       TE->setOperand(0, Operands.front());
4306       // Need to cast all indices to the same type before vectorization to
4307       // avoid crash.
4308       // Required to be able to find correct matches between different gather
4309       // nodes and reuse the vectorized values rather than trying to gather them
4310       // again.
4311       int IndexIdx = 1;
4312       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4313       Type *Ty = all_of(VL,
4314                         [VL0Ty, IndexIdx](Value *V) {
4315                           return VL0Ty == cast<GetElementPtrInst>(V)
4316                                               ->getOperand(IndexIdx)
4317                                               ->getType();
4318                         })
4319                      ? VL0Ty
4320                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4321                                             ->getPointerOperandType()
4322                                             ->getScalarType());
4323       // Prepare the operand vector.
4324       for (Value *V : VL) {
4325         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4326         auto *CI = cast<ConstantInt>(Op);
4327         Operands.back().push_back(ConstantExpr::getIntegerCast(
4328             CI, Ty, CI->getValue().isSignBitSet()));
4329       }
4330       TE->setOperand(IndexIdx, Operands.back());
4331 
4332       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4333         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4334       return;
4335     }
4336     case Instruction::Store: {
4337       // Check if the stores are consecutive or if we need to swizzle them.
4338       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4339       // Avoid types that are padded when being allocated as scalars, while
4340       // being packed together in a vector (such as i1).
4341       if (DL->getTypeSizeInBits(ScalarTy) !=
4342           DL->getTypeAllocSizeInBits(ScalarTy)) {
4343         BS.cancelScheduling(VL, VL0);
4344         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4345                      ReuseShuffleIndicies);
4346         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4347         return;
4348       }
4349       // Make sure all stores in the bundle are simple - we can't vectorize
4350       // atomic or volatile stores.
4351       SmallVector<Value *, 4> PointerOps(VL.size());
4352       ValueList Operands(VL.size());
4353       auto POIter = PointerOps.begin();
4354       auto OIter = Operands.begin();
4355       for (Value *V : VL) {
4356         auto *SI = cast<StoreInst>(V);
4357         if (!SI->isSimple()) {
4358           BS.cancelScheduling(VL, VL0);
4359           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4360                        ReuseShuffleIndicies);
4361           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4362           return;
4363         }
4364         *POIter = SI->getPointerOperand();
4365         *OIter = SI->getValueOperand();
4366         ++POIter;
4367         ++OIter;
4368       }
4369 
4370       OrdersType CurrentOrder;
4371       // Check the order of pointer operands.
4372       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4373         Value *Ptr0;
4374         Value *PtrN;
4375         if (CurrentOrder.empty()) {
4376           Ptr0 = PointerOps.front();
4377           PtrN = PointerOps.back();
4378         } else {
4379           Ptr0 = PointerOps[CurrentOrder.front()];
4380           PtrN = PointerOps[CurrentOrder.back()];
4381         }
4382         Optional<int> Dist =
4383             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4384         // Check that the sorted pointer operands are consecutive.
4385         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4386           if (CurrentOrder.empty()) {
4387             // Original stores are consecutive and does not require reordering.
4388             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4389                                          UserTreeIdx, ReuseShuffleIndicies);
4390             TE->setOperandsInOrder();
4391             buildTree_rec(Operands, Depth + 1, {TE, 0});
4392             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4393           } else {
4394             fixupOrderingIndices(CurrentOrder);
4395             TreeEntry *TE =
4396                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4397                              ReuseShuffleIndicies, CurrentOrder);
4398             TE->setOperandsInOrder();
4399             buildTree_rec(Operands, Depth + 1, {TE, 0});
4400             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4401           }
4402           return;
4403         }
4404       }
4405 
4406       BS.cancelScheduling(VL, VL0);
4407       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4408                    ReuseShuffleIndicies);
4409       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4410       return;
4411     }
4412     case Instruction::Call: {
4413       // Check if the calls are all to the same vectorizable intrinsic or
4414       // library function.
4415       CallInst *CI = cast<CallInst>(VL0);
4416       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4417 
4418       VFShape Shape = VFShape::get(
4419           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4420           false /*HasGlobalPred*/);
4421       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4422 
4423       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4424         BS.cancelScheduling(VL, VL0);
4425         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4426                      ReuseShuffleIndicies);
4427         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4428         return;
4429       }
4430       Function *F = CI->getCalledFunction();
4431       unsigned NumArgs = CI->arg_size();
4432       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4433       for (unsigned j = 0; j != NumArgs; ++j)
4434         if (hasVectorInstrinsicScalarOpd(ID, j))
4435           ScalarArgs[j] = CI->getArgOperand(j);
4436       for (Value *V : VL) {
4437         CallInst *CI2 = dyn_cast<CallInst>(V);
4438         if (!CI2 || CI2->getCalledFunction() != F ||
4439             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4440             (VecFunc &&
4441              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4442             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4443           BS.cancelScheduling(VL, VL0);
4444           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4445                        ReuseShuffleIndicies);
4446           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4447                             << "\n");
4448           return;
4449         }
4450         // Some intrinsics have scalar arguments and should be same in order for
4451         // them to be vectorized.
4452         for (unsigned j = 0; j != NumArgs; ++j) {
4453           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4454             Value *A1J = CI2->getArgOperand(j);
4455             if (ScalarArgs[j] != A1J) {
4456               BS.cancelScheduling(VL, VL0);
4457               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4458                            ReuseShuffleIndicies);
4459               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4460                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4461                                 << "\n");
4462               return;
4463             }
4464           }
4465         }
4466         // Verify that the bundle operands are identical between the two calls.
4467         if (CI->hasOperandBundles() &&
4468             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4469                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4470                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4471           BS.cancelScheduling(VL, VL0);
4472           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4473                        ReuseShuffleIndicies);
4474           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4475                             << *CI << "!=" << *V << '\n');
4476           return;
4477         }
4478       }
4479 
4480       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4481                                    ReuseShuffleIndicies);
4482       TE->setOperandsInOrder();
4483       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4484         // For scalar operands no need to to create an entry since no need to
4485         // vectorize it.
4486         if (hasVectorInstrinsicScalarOpd(ID, i))
4487           continue;
4488         ValueList Operands;
4489         // Prepare the operand vector.
4490         for (Value *V : VL) {
4491           auto *CI2 = cast<CallInst>(V);
4492           Operands.push_back(CI2->getArgOperand(i));
4493         }
4494         buildTree_rec(Operands, Depth + 1, {TE, i});
4495       }
4496       return;
4497     }
4498     case Instruction::ShuffleVector: {
4499       // If this is not an alternate sequence of opcode like add-sub
4500       // then do not vectorize this instruction.
4501       if (!S.isAltShuffle()) {
4502         BS.cancelScheduling(VL, VL0);
4503         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4504                      ReuseShuffleIndicies);
4505         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4506         return;
4507       }
4508       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4509                                    ReuseShuffleIndicies);
4510       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4511 
4512       // Reorder operands if reordering would enable vectorization.
4513       auto *CI = dyn_cast<CmpInst>(VL0);
4514       if (isa<BinaryOperator>(VL0) || CI) {
4515         ValueList Left, Right;
4516         if (!CI || all_of(VL, [](Value *V) {
4517               return cast<CmpInst>(V)->isCommutative();
4518             })) {
4519           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4520         } else {
4521           CmpInst::Predicate P0 = CI->getPredicate();
4522           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4523           assert(P0 != AltP0 &&
4524                  "Expected different main/alternate predicates.");
4525           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4526           Value *BaseOp0 = VL0->getOperand(0);
4527           Value *BaseOp1 = VL0->getOperand(1);
4528           // Collect operands - commute if it uses the swapped predicate or
4529           // alternate operation.
4530           for (Value *V : VL) {
4531             auto *Cmp = cast<CmpInst>(V);
4532             Value *LHS = Cmp->getOperand(0);
4533             Value *RHS = Cmp->getOperand(1);
4534             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4535             if (P0 == AltP0Swapped) {
4536               if ((P0 == CurrentPred &&
4537                    !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4538                   (AltP0 == CurrentPred &&
4539                    areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))
4540                 std::swap(LHS, RHS);
4541             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4542               std::swap(LHS, RHS);
4543             }
4544             Left.push_back(LHS);
4545             Right.push_back(RHS);
4546           }
4547         }
4548         TE->setOperand(0, Left);
4549         TE->setOperand(1, Right);
4550         buildTree_rec(Left, Depth + 1, {TE, 0});
4551         buildTree_rec(Right, Depth + 1, {TE, 1});
4552         return;
4553       }
4554 
4555       TE->setOperandsInOrder();
4556       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4557         ValueList Operands;
4558         // Prepare the operand vector.
4559         for (Value *V : VL)
4560           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4561 
4562         buildTree_rec(Operands, Depth + 1, {TE, i});
4563       }
4564       return;
4565     }
4566     default:
4567       BS.cancelScheduling(VL, VL0);
4568       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4569                    ReuseShuffleIndicies);
4570       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4571       return;
4572   }
4573 }
4574 
4575 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4576   unsigned N = 1;
4577   Type *EltTy = T;
4578 
4579   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4580          isa<VectorType>(EltTy)) {
4581     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4582       // Check that struct is homogeneous.
4583       for (const auto *Ty : ST->elements())
4584         if (Ty != *ST->element_begin())
4585           return 0;
4586       N *= ST->getNumElements();
4587       EltTy = *ST->element_begin();
4588     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4589       N *= AT->getNumElements();
4590       EltTy = AT->getElementType();
4591     } else {
4592       auto *VT = cast<FixedVectorType>(EltTy);
4593       N *= VT->getNumElements();
4594       EltTy = VT->getElementType();
4595     }
4596   }
4597 
4598   if (!isValidElementType(EltTy))
4599     return 0;
4600   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4601   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4602     return 0;
4603   return N;
4604 }
4605 
4606 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4607                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4608   const auto *It = find_if(VL, [](Value *V) {
4609     return isa<ExtractElementInst, ExtractValueInst>(V);
4610   });
4611   assert(It != VL.end() && "Expected at least one extract instruction.");
4612   auto *E0 = cast<Instruction>(*It);
4613   assert(all_of(VL,
4614                 [](Value *V) {
4615                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4616                       V);
4617                 }) &&
4618          "Invalid opcode");
4619   // Check if all of the extracts come from the same vector and from the
4620   // correct offset.
4621   Value *Vec = E0->getOperand(0);
4622 
4623   CurrentOrder.clear();
4624 
4625   // We have to extract from a vector/aggregate with the same number of elements.
4626   unsigned NElts;
4627   if (E0->getOpcode() == Instruction::ExtractValue) {
4628     const DataLayout &DL = E0->getModule()->getDataLayout();
4629     NElts = canMapToVector(Vec->getType(), DL);
4630     if (!NElts)
4631       return false;
4632     // Check if load can be rewritten as load of vector.
4633     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4634     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4635       return false;
4636   } else {
4637     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4638   }
4639 
4640   if (NElts != VL.size())
4641     return false;
4642 
4643   // Check that all of the indices extract from the correct offset.
4644   bool ShouldKeepOrder = true;
4645   unsigned E = VL.size();
4646   // Assign to all items the initial value E + 1 so we can check if the extract
4647   // instruction index was used already.
4648   // Also, later we can check that all the indices are used and we have a
4649   // consecutive access in the extract instructions, by checking that no
4650   // element of CurrentOrder still has value E + 1.
4651   CurrentOrder.assign(E, E);
4652   unsigned I = 0;
4653   for (; I < E; ++I) {
4654     auto *Inst = dyn_cast<Instruction>(VL[I]);
4655     if (!Inst)
4656       continue;
4657     if (Inst->getOperand(0) != Vec)
4658       break;
4659     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4660       if (isa<UndefValue>(EE->getIndexOperand()))
4661         continue;
4662     Optional<unsigned> Idx = getExtractIndex(Inst);
4663     if (!Idx)
4664       break;
4665     const unsigned ExtIdx = *Idx;
4666     if (ExtIdx != I) {
4667       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4668         break;
4669       ShouldKeepOrder = false;
4670       CurrentOrder[ExtIdx] = I;
4671     } else {
4672       if (CurrentOrder[I] != E)
4673         break;
4674       CurrentOrder[I] = I;
4675     }
4676   }
4677   if (I < E) {
4678     CurrentOrder.clear();
4679     return false;
4680   }
4681   if (ShouldKeepOrder)
4682     CurrentOrder.clear();
4683 
4684   return ShouldKeepOrder;
4685 }
4686 
4687 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4688                                     ArrayRef<Value *> VectorizedVals) const {
4689   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4690          all_of(I->users(), [this](User *U) {
4691            return ScalarToTreeEntry.count(U) > 0 ||
4692                   isVectorLikeInstWithConstOps(U) ||
4693                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4694          });
4695 }
4696 
4697 static std::pair<InstructionCost, InstructionCost>
4698 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4699                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4700   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4701 
4702   // Calculate the cost of the scalar and vector calls.
4703   SmallVector<Type *, 4> VecTys;
4704   for (Use &Arg : CI->args())
4705     VecTys.push_back(
4706         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4707   FastMathFlags FMF;
4708   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4709     FMF = FPCI->getFastMathFlags();
4710   SmallVector<const Value *> Arguments(CI->args());
4711   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4712                                     dyn_cast<IntrinsicInst>(CI));
4713   auto IntrinsicCost =
4714     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4715 
4716   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4717                                      VecTy->getNumElements())),
4718                             false /*HasGlobalPred*/);
4719   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4720   auto LibCost = IntrinsicCost;
4721   if (!CI->isNoBuiltin() && VecFunc) {
4722     // Calculate the cost of the vector library call.
4723     // If the corresponding vector call is cheaper, return its cost.
4724     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4725                                     TTI::TCK_RecipThroughput);
4726   }
4727   return {IntrinsicCost, LibCost};
4728 }
4729 
4730 /// Compute the cost of creating a vector of type \p VecTy containing the
4731 /// extracted values from \p VL.
4732 static InstructionCost
4733 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4734                    TargetTransformInfo::ShuffleKind ShuffleKind,
4735                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4736   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4737 
4738   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4739       VecTy->getNumElements() < NumOfParts)
4740     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4741 
4742   bool AllConsecutive = true;
4743   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4744   unsigned Idx = -1;
4745   InstructionCost Cost = 0;
4746 
4747   // Process extracts in blocks of EltsPerVector to check if the source vector
4748   // operand can be re-used directly. If not, add the cost of creating a shuffle
4749   // to extract the values into a vector register.
4750   for (auto *V : VL) {
4751     ++Idx;
4752 
4753     // Need to exclude undefs from analysis.
4754     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4755       continue;
4756 
4757     // Reached the start of a new vector registers.
4758     if (Idx % EltsPerVector == 0) {
4759       AllConsecutive = true;
4760       continue;
4761     }
4762 
4763     // Check all extracts for a vector register on the target directly
4764     // extract values in order.
4765     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4766     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4767       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4768       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4769                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4770     }
4771 
4772     if (AllConsecutive)
4773       continue;
4774 
4775     // Skip all indices, except for the last index per vector block.
4776     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4777       continue;
4778 
4779     // If we have a series of extracts which are not consecutive and hence
4780     // cannot re-use the source vector register directly, compute the shuffle
4781     // cost to extract the a vector with EltsPerVector elements.
4782     Cost += TTI.getShuffleCost(
4783         TargetTransformInfo::SK_PermuteSingleSrc,
4784         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4785   }
4786   return Cost;
4787 }
4788 
4789 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4790 /// operations operands.
4791 static void
4792 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4793                      ArrayRef<int> ReusesIndices,
4794                      const function_ref<bool(Instruction *)> IsAltOp,
4795                      SmallVectorImpl<int> &Mask,
4796                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4797                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4798   unsigned Sz = VL.size();
4799   Mask.assign(Sz, UndefMaskElem);
4800   SmallVector<int> OrderMask;
4801   if (!ReorderIndices.empty())
4802     inversePermutation(ReorderIndices, OrderMask);
4803   for (unsigned I = 0; I < Sz; ++I) {
4804     unsigned Idx = I;
4805     if (!ReorderIndices.empty())
4806       Idx = OrderMask[I];
4807     auto *OpInst = cast<Instruction>(VL[Idx]);
4808     if (IsAltOp(OpInst)) {
4809       Mask[I] = Sz + Idx;
4810       if (AltScalars)
4811         AltScalars->push_back(OpInst);
4812     } else {
4813       Mask[I] = Idx;
4814       if (OpScalars)
4815         OpScalars->push_back(OpInst);
4816     }
4817   }
4818   if (!ReusesIndices.empty()) {
4819     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4820     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4821       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4822     });
4823     Mask.swap(NewMask);
4824   }
4825 }
4826 
4827 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4828                                       ArrayRef<Value *> VectorizedVals) {
4829   ArrayRef<Value*> VL = E->Scalars;
4830 
4831   Type *ScalarTy = VL[0]->getType();
4832   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4833     ScalarTy = SI->getValueOperand()->getType();
4834   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4835     ScalarTy = CI->getOperand(0)->getType();
4836   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4837     ScalarTy = IE->getOperand(1)->getType();
4838   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4839   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4840 
4841   // If we have computed a smaller type for the expression, update VecTy so
4842   // that the costs will be accurate.
4843   if (MinBWs.count(VL[0]))
4844     VecTy = FixedVectorType::get(
4845         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4846   unsigned EntryVF = E->getVectorFactor();
4847   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4848 
4849   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4850   // FIXME: it tries to fix a problem with MSVC buildbots.
4851   TargetTransformInfo &TTIRef = *TTI;
4852   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4853                                VectorizedVals, E](InstructionCost &Cost) {
4854     DenseMap<Value *, int> ExtractVectorsTys;
4855     SmallPtrSet<Value *, 4> CheckedExtracts;
4856     for (auto *V : VL) {
4857       if (isa<UndefValue>(V))
4858         continue;
4859       // If all users of instruction are going to be vectorized and this
4860       // instruction itself is not going to be vectorized, consider this
4861       // instruction as dead and remove its cost from the final cost of the
4862       // vectorized tree.
4863       // Also, avoid adjusting the cost for extractelements with multiple uses
4864       // in different graph entries.
4865       const TreeEntry *VE = getTreeEntry(V);
4866       if (!CheckedExtracts.insert(V).second ||
4867           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4868           (VE && VE != E))
4869         continue;
4870       auto *EE = cast<ExtractElementInst>(V);
4871       Optional<unsigned> EEIdx = getExtractIndex(EE);
4872       if (!EEIdx)
4873         continue;
4874       unsigned Idx = *EEIdx;
4875       if (TTIRef.getNumberOfParts(VecTy) !=
4876           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4877         auto It =
4878             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4879         It->getSecond() = std::min<int>(It->second, Idx);
4880       }
4881       // Take credit for instruction that will become dead.
4882       if (EE->hasOneUse()) {
4883         Instruction *Ext = EE->user_back();
4884         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4885             all_of(Ext->users(),
4886                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4887           // Use getExtractWithExtendCost() to calculate the cost of
4888           // extractelement/ext pair.
4889           Cost -=
4890               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4891                                               EE->getVectorOperandType(), Idx);
4892           // Add back the cost of s|zext which is subtracted separately.
4893           Cost += TTIRef.getCastInstrCost(
4894               Ext->getOpcode(), Ext->getType(), EE->getType(),
4895               TTI::getCastContextHint(Ext), CostKind, Ext);
4896           continue;
4897         }
4898       }
4899       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4900                                         EE->getVectorOperandType(), Idx);
4901     }
4902     // Add a cost for subvector extracts/inserts if required.
4903     for (const auto &Data : ExtractVectorsTys) {
4904       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4905       unsigned NumElts = VecTy->getNumElements();
4906       if (Data.second % NumElts == 0)
4907         continue;
4908       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4909         unsigned Idx = (Data.second / NumElts) * NumElts;
4910         unsigned EENumElts = EEVTy->getNumElements();
4911         if (Idx + NumElts <= EENumElts) {
4912           Cost +=
4913               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4914                                     EEVTy, None, Idx, VecTy);
4915         } else {
4916           // Need to round up the subvector type vectorization factor to avoid a
4917           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4918           // <= EENumElts.
4919           auto *SubVT =
4920               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4921           Cost +=
4922               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4923                                     EEVTy, None, Idx, SubVT);
4924         }
4925       } else {
4926         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4927                                       VecTy, None, 0, EEVTy);
4928       }
4929     }
4930   };
4931   if (E->State == TreeEntry::NeedToGather) {
4932     if (allConstant(VL))
4933       return 0;
4934     if (isa<InsertElementInst>(VL[0]))
4935       return InstructionCost::getInvalid();
4936     SmallVector<int> Mask;
4937     SmallVector<const TreeEntry *> Entries;
4938     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4939         isGatherShuffledEntry(E, Mask, Entries);
4940     if (Shuffle.hasValue()) {
4941       InstructionCost GatherCost = 0;
4942       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4943         // Perfect match in the graph, will reuse the previously vectorized
4944         // node. Cost is 0.
4945         LLVM_DEBUG(
4946             dbgs()
4947             << "SLP: perfect diamond match for gather bundle that starts with "
4948             << *VL.front() << ".\n");
4949         if (NeedToShuffleReuses)
4950           GatherCost =
4951               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4952                                   FinalVecTy, E->ReuseShuffleIndices);
4953       } else {
4954         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4955                           << " entries for bundle that starts with "
4956                           << *VL.front() << ".\n");
4957         // Detected that instead of gather we can emit a shuffle of single/two
4958         // previously vectorized nodes. Add the cost of the permutation rather
4959         // than gather.
4960         ::addMask(Mask, E->ReuseShuffleIndices);
4961         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4962       }
4963       return GatherCost;
4964     }
4965     if ((E->getOpcode() == Instruction::ExtractElement ||
4966          all_of(E->Scalars,
4967                 [](Value *V) {
4968                   return isa<ExtractElementInst, UndefValue>(V);
4969                 })) &&
4970         allSameType(VL)) {
4971       // Check that gather of extractelements can be represented as just a
4972       // shuffle of a single/two vectors the scalars are extracted from.
4973       SmallVector<int> Mask;
4974       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4975           isFixedVectorShuffle(VL, Mask);
4976       if (ShuffleKind.hasValue()) {
4977         // Found the bunch of extractelement instructions that must be gathered
4978         // into a vector and can be represented as a permutation elements in a
4979         // single input vector or of 2 input vectors.
4980         InstructionCost Cost =
4981             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4982         AdjustExtractsCost(Cost);
4983         if (NeedToShuffleReuses)
4984           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4985                                       FinalVecTy, E->ReuseShuffleIndices);
4986         return Cost;
4987       }
4988     }
4989     if (isSplat(VL)) {
4990       // Found the broadcasting of the single scalar, calculate the cost as the
4991       // broadcast.
4992       assert(VecTy == FinalVecTy &&
4993              "No reused scalars expected for broadcast.");
4994       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4995     }
4996     InstructionCost ReuseShuffleCost = 0;
4997     if (NeedToShuffleReuses)
4998       ReuseShuffleCost = TTI->getShuffleCost(
4999           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5000     // Improve gather cost for gather of loads, if we can group some of the
5001     // loads into vector loads.
5002     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5003         !E->isAltShuffle()) {
5004       BoUpSLP::ValueSet VectorizedLoads;
5005       unsigned StartIdx = 0;
5006       unsigned VF = VL.size() / 2;
5007       unsigned VectorizedCnt = 0;
5008       unsigned ScatterVectorizeCnt = 0;
5009       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5010       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5011         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5012              Cnt += VF) {
5013           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5014           if (!VectorizedLoads.count(Slice.front()) &&
5015               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5016             SmallVector<Value *> PointerOps;
5017             OrdersType CurrentOrder;
5018             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5019                                               *SE, CurrentOrder, PointerOps);
5020             switch (LS) {
5021             case LoadsState::Vectorize:
5022             case LoadsState::ScatterVectorize:
5023               // Mark the vectorized loads so that we don't vectorize them
5024               // again.
5025               if (LS == LoadsState::Vectorize)
5026                 ++VectorizedCnt;
5027               else
5028                 ++ScatterVectorizeCnt;
5029               VectorizedLoads.insert(Slice.begin(), Slice.end());
5030               // If we vectorized initial block, no need to try to vectorize it
5031               // again.
5032               if (Cnt == StartIdx)
5033                 StartIdx += VF;
5034               break;
5035             case LoadsState::Gather:
5036               break;
5037             }
5038           }
5039         }
5040         // Check if the whole array was vectorized already - exit.
5041         if (StartIdx >= VL.size())
5042           break;
5043         // Found vectorizable parts - exit.
5044         if (!VectorizedLoads.empty())
5045           break;
5046       }
5047       if (!VectorizedLoads.empty()) {
5048         InstructionCost GatherCost = 0;
5049         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5050         bool NeedInsertSubvectorAnalysis =
5051             !NumParts || (VL.size() / VF) > NumParts;
5052         // Get the cost for gathered loads.
5053         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5054           if (VectorizedLoads.contains(VL[I]))
5055             continue;
5056           GatherCost += getGatherCost(VL.slice(I, VF));
5057         }
5058         // The cost for vectorized loads.
5059         InstructionCost ScalarsCost = 0;
5060         for (Value *V : VectorizedLoads) {
5061           auto *LI = cast<LoadInst>(V);
5062           ScalarsCost += TTI->getMemoryOpCost(
5063               Instruction::Load, LI->getType(), LI->getAlign(),
5064               LI->getPointerAddressSpace(), CostKind, LI);
5065         }
5066         auto *LI = cast<LoadInst>(E->getMainOp());
5067         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5068         Align Alignment = LI->getAlign();
5069         GatherCost +=
5070             VectorizedCnt *
5071             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5072                                  LI->getPointerAddressSpace(), CostKind, LI);
5073         GatherCost += ScatterVectorizeCnt *
5074                       TTI->getGatherScatterOpCost(
5075                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5076                           /*VariableMask=*/false, Alignment, CostKind, LI);
5077         if (NeedInsertSubvectorAnalysis) {
5078           // Add the cost for the subvectors insert.
5079           for (int I = VF, E = VL.size(); I < E; I += VF)
5080             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5081                                               None, I, LoadTy);
5082         }
5083         return ReuseShuffleCost + GatherCost - ScalarsCost;
5084       }
5085     }
5086     return ReuseShuffleCost + getGatherCost(VL);
5087   }
5088   InstructionCost CommonCost = 0;
5089   SmallVector<int> Mask;
5090   if (!E->ReorderIndices.empty()) {
5091     SmallVector<int> NewMask;
5092     if (E->getOpcode() == Instruction::Store) {
5093       // For stores the order is actually a mask.
5094       NewMask.resize(E->ReorderIndices.size());
5095       copy(E->ReorderIndices, NewMask.begin());
5096     } else {
5097       inversePermutation(E->ReorderIndices, NewMask);
5098     }
5099     ::addMask(Mask, NewMask);
5100   }
5101   if (NeedToShuffleReuses)
5102     ::addMask(Mask, E->ReuseShuffleIndices);
5103   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5104     CommonCost =
5105         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5106   assert((E->State == TreeEntry::Vectorize ||
5107           E->State == TreeEntry::ScatterVectorize) &&
5108          "Unhandled state");
5109   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5110   Instruction *VL0 = E->getMainOp();
5111   unsigned ShuffleOrOp =
5112       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5113   switch (ShuffleOrOp) {
5114     case Instruction::PHI:
5115       return 0;
5116 
5117     case Instruction::ExtractValue:
5118     case Instruction::ExtractElement: {
5119       // The common cost of removal ExtractElement/ExtractValue instructions +
5120       // the cost of shuffles, if required to resuffle the original vector.
5121       if (NeedToShuffleReuses) {
5122         unsigned Idx = 0;
5123         for (unsigned I : E->ReuseShuffleIndices) {
5124           if (ShuffleOrOp == Instruction::ExtractElement) {
5125             auto *EE = cast<ExtractElementInst>(VL[I]);
5126             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5127                                                   EE->getVectorOperandType(),
5128                                                   *getExtractIndex(EE));
5129           } else {
5130             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5131                                                   VecTy, Idx);
5132             ++Idx;
5133           }
5134         }
5135         Idx = EntryVF;
5136         for (Value *V : VL) {
5137           if (ShuffleOrOp == Instruction::ExtractElement) {
5138             auto *EE = cast<ExtractElementInst>(V);
5139             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5140                                                   EE->getVectorOperandType(),
5141                                                   *getExtractIndex(EE));
5142           } else {
5143             --Idx;
5144             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5145                                                   VecTy, Idx);
5146           }
5147         }
5148       }
5149       if (ShuffleOrOp == Instruction::ExtractValue) {
5150         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5151           auto *EI = cast<Instruction>(VL[I]);
5152           // Take credit for instruction that will become dead.
5153           if (EI->hasOneUse()) {
5154             Instruction *Ext = EI->user_back();
5155             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5156                 all_of(Ext->users(),
5157                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5158               // Use getExtractWithExtendCost() to calculate the cost of
5159               // extractelement/ext pair.
5160               CommonCost -= TTI->getExtractWithExtendCost(
5161                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5162               // Add back the cost of s|zext which is subtracted separately.
5163               CommonCost += TTI->getCastInstrCost(
5164                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5165                   TTI::getCastContextHint(Ext), CostKind, Ext);
5166               continue;
5167             }
5168           }
5169           CommonCost -=
5170               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5171         }
5172       } else {
5173         AdjustExtractsCost(CommonCost);
5174       }
5175       return CommonCost;
5176     }
5177     case Instruction::InsertElement: {
5178       assert(E->ReuseShuffleIndices.empty() &&
5179              "Unique insertelements only are expected.");
5180       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5181 
5182       unsigned const NumElts = SrcVecTy->getNumElements();
5183       unsigned const NumScalars = VL.size();
5184       APInt DemandedElts = APInt::getZero(NumElts);
5185       // TODO: Add support for Instruction::InsertValue.
5186       SmallVector<int> Mask;
5187       if (!E->ReorderIndices.empty()) {
5188         inversePermutation(E->ReorderIndices, Mask);
5189         Mask.append(NumElts - NumScalars, UndefMaskElem);
5190       } else {
5191         Mask.assign(NumElts, UndefMaskElem);
5192         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5193       }
5194       unsigned Offset = *getInsertIndex(VL0, 0);
5195       bool IsIdentity = true;
5196       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5197       Mask.swap(PrevMask);
5198       for (unsigned I = 0; I < NumScalars; ++I) {
5199         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
5200         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5201           continue;
5202         DemandedElts.setBit(*InsertIdx);
5203         IsIdentity &= *InsertIdx - Offset == I;
5204         Mask[*InsertIdx - Offset] = I;
5205       }
5206       assert(Offset < NumElts && "Failed to find vector index offset");
5207 
5208       InstructionCost Cost = 0;
5209       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5210                                             /*Insert*/ true, /*Extract*/ false);
5211 
5212       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5213         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5214         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5215         Cost += TTI->getShuffleCost(
5216             TargetTransformInfo::SK_PermuteSingleSrc,
5217             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5218       } else if (!IsIdentity) {
5219         auto *FirstInsert =
5220             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5221               return !is_contained(E->Scalars,
5222                                    cast<Instruction>(V)->getOperand(0));
5223             }));
5224         if (isUndefVector(FirstInsert->getOperand(0))) {
5225           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5226         } else {
5227           SmallVector<int> InsertMask(NumElts);
5228           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5229           for (unsigned I = 0; I < NumElts; I++) {
5230             if (Mask[I] != UndefMaskElem)
5231               InsertMask[Offset + I] = NumElts + I;
5232           }
5233           Cost +=
5234               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5235         }
5236       }
5237 
5238       return Cost;
5239     }
5240     case Instruction::ZExt:
5241     case Instruction::SExt:
5242     case Instruction::FPToUI:
5243     case Instruction::FPToSI:
5244     case Instruction::FPExt:
5245     case Instruction::PtrToInt:
5246     case Instruction::IntToPtr:
5247     case Instruction::SIToFP:
5248     case Instruction::UIToFP:
5249     case Instruction::Trunc:
5250     case Instruction::FPTrunc:
5251     case Instruction::BitCast: {
5252       Type *SrcTy = VL0->getOperand(0)->getType();
5253       InstructionCost ScalarEltCost =
5254           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5255                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5256       if (NeedToShuffleReuses) {
5257         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5258       }
5259 
5260       // Calculate the cost of this instruction.
5261       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5262 
5263       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5264       InstructionCost VecCost = 0;
5265       // Check if the values are candidates to demote.
5266       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5267         VecCost = CommonCost + TTI->getCastInstrCost(
5268                                    E->getOpcode(), VecTy, SrcVecTy,
5269                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5270       }
5271       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5272       return VecCost - ScalarCost;
5273     }
5274     case Instruction::FCmp:
5275     case Instruction::ICmp:
5276     case Instruction::Select: {
5277       // Calculate the cost of this instruction.
5278       InstructionCost ScalarEltCost =
5279           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5280                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5281       if (NeedToShuffleReuses) {
5282         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5283       }
5284       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5285       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5286 
5287       // Check if all entries in VL are either compares or selects with compares
5288       // as condition that have the same predicates.
5289       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5290       bool First = true;
5291       for (auto *V : VL) {
5292         CmpInst::Predicate CurrentPred;
5293         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5294         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5295              !match(V, MatchCmp)) ||
5296             (!First && VecPred != CurrentPred)) {
5297           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5298           break;
5299         }
5300         First = false;
5301         VecPred = CurrentPred;
5302       }
5303 
5304       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5305           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5306       // Check if it is possible and profitable to use min/max for selects in
5307       // VL.
5308       //
5309       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5310       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5311         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5312                                           {VecTy, VecTy});
5313         InstructionCost IntrinsicCost =
5314             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5315         // If the selects are the only uses of the compares, they will be dead
5316         // and we can adjust the cost by removing their cost.
5317         if (IntrinsicAndUse.second)
5318           IntrinsicCost -=
5319               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5320                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5321         VecCost = std::min(VecCost, IntrinsicCost);
5322       }
5323       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5324       return CommonCost + VecCost - ScalarCost;
5325     }
5326     case Instruction::FNeg:
5327     case Instruction::Add:
5328     case Instruction::FAdd:
5329     case Instruction::Sub:
5330     case Instruction::FSub:
5331     case Instruction::Mul:
5332     case Instruction::FMul:
5333     case Instruction::UDiv:
5334     case Instruction::SDiv:
5335     case Instruction::FDiv:
5336     case Instruction::URem:
5337     case Instruction::SRem:
5338     case Instruction::FRem:
5339     case Instruction::Shl:
5340     case Instruction::LShr:
5341     case Instruction::AShr:
5342     case Instruction::And:
5343     case Instruction::Or:
5344     case Instruction::Xor: {
5345       // Certain instructions can be cheaper to vectorize if they have a
5346       // constant second vector operand.
5347       TargetTransformInfo::OperandValueKind Op1VK =
5348           TargetTransformInfo::OK_AnyValue;
5349       TargetTransformInfo::OperandValueKind Op2VK =
5350           TargetTransformInfo::OK_UniformConstantValue;
5351       TargetTransformInfo::OperandValueProperties Op1VP =
5352           TargetTransformInfo::OP_None;
5353       TargetTransformInfo::OperandValueProperties Op2VP =
5354           TargetTransformInfo::OP_PowerOf2;
5355 
5356       // If all operands are exactly the same ConstantInt then set the
5357       // operand kind to OK_UniformConstantValue.
5358       // If instead not all operands are constants, then set the operand kind
5359       // to OK_AnyValue. If all operands are constants but not the same,
5360       // then set the operand kind to OK_NonUniformConstantValue.
5361       ConstantInt *CInt0 = nullptr;
5362       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5363         const Instruction *I = cast<Instruction>(VL[i]);
5364         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5365         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5366         if (!CInt) {
5367           Op2VK = TargetTransformInfo::OK_AnyValue;
5368           Op2VP = TargetTransformInfo::OP_None;
5369           break;
5370         }
5371         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5372             !CInt->getValue().isPowerOf2())
5373           Op2VP = TargetTransformInfo::OP_None;
5374         if (i == 0) {
5375           CInt0 = CInt;
5376           continue;
5377         }
5378         if (CInt0 != CInt)
5379           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5380       }
5381 
5382       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5383       InstructionCost ScalarEltCost =
5384           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5385                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5386       if (NeedToShuffleReuses) {
5387         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5388       }
5389       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5390       InstructionCost VecCost =
5391           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5392                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5393       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5394       return CommonCost + VecCost - ScalarCost;
5395     }
5396     case Instruction::GetElementPtr: {
5397       TargetTransformInfo::OperandValueKind Op1VK =
5398           TargetTransformInfo::OK_AnyValue;
5399       TargetTransformInfo::OperandValueKind Op2VK =
5400           TargetTransformInfo::OK_UniformConstantValue;
5401 
5402       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5403           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5404       if (NeedToShuffleReuses) {
5405         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5406       }
5407       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5408       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5409           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5410       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5411       return CommonCost + VecCost - ScalarCost;
5412     }
5413     case Instruction::Load: {
5414       // Cost of wide load - cost of scalar loads.
5415       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5416       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5417           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5418       if (NeedToShuffleReuses) {
5419         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5420       }
5421       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5422       InstructionCost VecLdCost;
5423       if (E->State == TreeEntry::Vectorize) {
5424         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5425                                          CostKind, VL0);
5426       } else {
5427         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5428         Align CommonAlignment = Alignment;
5429         for (Value *V : VL)
5430           CommonAlignment =
5431               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5432         VecLdCost = TTI->getGatherScatterOpCost(
5433             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5434             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5435       }
5436       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5437       return CommonCost + VecLdCost - ScalarLdCost;
5438     }
5439     case Instruction::Store: {
5440       // We know that we can merge the stores. Calculate the cost.
5441       bool IsReorder = !E->ReorderIndices.empty();
5442       auto *SI =
5443           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5444       Align Alignment = SI->getAlign();
5445       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5446           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5447       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5448       InstructionCost VecStCost = TTI->getMemoryOpCost(
5449           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5450       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5451       return CommonCost + VecStCost - ScalarStCost;
5452     }
5453     case Instruction::Call: {
5454       CallInst *CI = cast<CallInst>(VL0);
5455       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5456 
5457       // Calculate the cost of the scalar and vector calls.
5458       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5459       InstructionCost ScalarEltCost =
5460           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5461       if (NeedToShuffleReuses) {
5462         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5463       }
5464       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5465 
5466       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5467       InstructionCost VecCallCost =
5468           std::min(VecCallCosts.first, VecCallCosts.second);
5469 
5470       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5471                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5472                         << " for " << *CI << "\n");
5473 
5474       return CommonCost + VecCallCost - ScalarCallCost;
5475     }
5476     case Instruction::ShuffleVector: {
5477       assert(E->isAltShuffle() &&
5478              ((Instruction::isBinaryOp(E->getOpcode()) &&
5479                Instruction::isBinaryOp(E->getAltOpcode())) ||
5480               (Instruction::isCast(E->getOpcode()) &&
5481                Instruction::isCast(E->getAltOpcode())) ||
5482               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5483              "Invalid Shuffle Vector Operand");
5484       InstructionCost ScalarCost = 0;
5485       if (NeedToShuffleReuses) {
5486         for (unsigned Idx : E->ReuseShuffleIndices) {
5487           Instruction *I = cast<Instruction>(VL[Idx]);
5488           CommonCost -= TTI->getInstructionCost(I, CostKind);
5489         }
5490         for (Value *V : VL) {
5491           Instruction *I = cast<Instruction>(V);
5492           CommonCost += TTI->getInstructionCost(I, CostKind);
5493         }
5494       }
5495       for (Value *V : VL) {
5496         Instruction *I = cast<Instruction>(V);
5497         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5498         ScalarCost += TTI->getInstructionCost(I, CostKind);
5499       }
5500       // VecCost is equal to sum of the cost of creating 2 vectors
5501       // and the cost of creating shuffle.
5502       InstructionCost VecCost = 0;
5503       // Try to find the previous shuffle node with the same operands and same
5504       // main/alternate ops.
5505       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5506         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5507           if (TE.get() == E)
5508             break;
5509           if (TE->isAltShuffle() &&
5510               ((TE->getOpcode() == E->getOpcode() &&
5511                 TE->getAltOpcode() == E->getAltOpcode()) ||
5512                (TE->getOpcode() == E->getAltOpcode() &&
5513                 TE->getAltOpcode() == E->getOpcode())) &&
5514               TE->hasEqualOperands(*E))
5515             return true;
5516         }
5517         return false;
5518       };
5519       if (TryFindNodeWithEqualOperands()) {
5520         LLVM_DEBUG({
5521           dbgs() << "SLP: diamond match for alternate node found.\n";
5522           E->dump();
5523         });
5524         // No need to add new vector costs here since we're going to reuse
5525         // same main/alternate vector ops, just do different shuffling.
5526       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5527         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5528         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5529                                                CostKind);
5530       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5531         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5532                                           Builder.getInt1Ty(),
5533                                           CI0->getPredicate(), CostKind, VL0);
5534         VecCost += TTI->getCmpSelInstrCost(
5535             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5536             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5537             E->getAltOp());
5538       } else {
5539         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5540         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5541         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5542         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5543         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5544                                         TTI::CastContextHint::None, CostKind);
5545         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5546                                          TTI::CastContextHint::None, CostKind);
5547       }
5548 
5549       SmallVector<int> Mask;
5550       buildSuffleEntryMask(
5551           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5552           [E](Instruction *I) {
5553             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5554             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
5555               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
5556               auto *CI = cast<CmpInst>(I);
5557               CmpInst::Predicate P0 = CI0->getPredicate();
5558               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5559               assert(P0 != AltP0 &&
5560                      "Expected different main/alternate predicates.");
5561               CmpInst::Predicate AltP0Swapped =
5562                   CmpInst::getSwappedPredicate(AltP0);
5563               CmpInst::Predicate CurrentPred = CI->getPredicate();
5564               if (P0 == AltP0Swapped)
5565                 return (P0 == CurrentPred &&
5566                         !areCompatibleCmpOps(
5567                             CI0->getOperand(0), CI0->getOperand(1),
5568                             CI->getOperand(0), CI->getOperand(1))) ||
5569                        (AltP0 == CurrentPred &&
5570                         !areCompatibleCmpOps(
5571                             CI0->getOperand(0), CI0->getOperand(1),
5572                             CI->getOperand(1), CI->getOperand(0)));
5573               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5574             }
5575             return I->getOpcode() == E->getAltOpcode();
5576           },
5577           Mask);
5578       CommonCost =
5579           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5580       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5581       return CommonCost + VecCost - ScalarCost;
5582     }
5583     default:
5584       llvm_unreachable("Unknown instruction");
5585   }
5586 }
5587 
5588 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5589   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5590                     << VectorizableTree.size() << " is fully vectorizable .\n");
5591 
5592   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5593     SmallVector<int> Mask;
5594     return TE->State == TreeEntry::NeedToGather &&
5595            !any_of(TE->Scalars,
5596                    [this](Value *V) { return EphValues.contains(V); }) &&
5597            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5598             TE->Scalars.size() < Limit ||
5599             ((TE->getOpcode() == Instruction::ExtractElement ||
5600               all_of(TE->Scalars,
5601                      [](Value *V) {
5602                        return isa<ExtractElementInst, UndefValue>(V);
5603                      })) &&
5604              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5605             (TE->State == TreeEntry::NeedToGather &&
5606              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5607   };
5608 
5609   // We only handle trees of heights 1 and 2.
5610   if (VectorizableTree.size() == 1 &&
5611       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5612        (ForReduction &&
5613         AreVectorizableGathers(VectorizableTree[0].get(),
5614                                VectorizableTree[0]->Scalars.size()) &&
5615         VectorizableTree[0]->getVectorFactor() > 2)))
5616     return true;
5617 
5618   if (VectorizableTree.size() != 2)
5619     return false;
5620 
5621   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5622   // with the second gather nodes if they have less scalar operands rather than
5623   // the initial tree element (may be profitable to shuffle the second gather)
5624   // or they are extractelements, which form shuffle.
5625   SmallVector<int> Mask;
5626   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5627       AreVectorizableGathers(VectorizableTree[1].get(),
5628                              VectorizableTree[0]->Scalars.size()))
5629     return true;
5630 
5631   // Gathering cost would be too much for tiny trees.
5632   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5633       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5634        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5635     return false;
5636 
5637   return true;
5638 }
5639 
5640 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5641                                        TargetTransformInfo *TTI,
5642                                        bool MustMatchOrInst) {
5643   // Look past the root to find a source value. Arbitrarily follow the
5644   // path through operand 0 of any 'or'. Also, peek through optional
5645   // shift-left-by-multiple-of-8-bits.
5646   Value *ZextLoad = Root;
5647   const APInt *ShAmtC;
5648   bool FoundOr = false;
5649   while (!isa<ConstantExpr>(ZextLoad) &&
5650          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5651           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5652            ShAmtC->urem(8) == 0))) {
5653     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5654     ZextLoad = BinOp->getOperand(0);
5655     if (BinOp->getOpcode() == Instruction::Or)
5656       FoundOr = true;
5657   }
5658   // Check if the input is an extended load of the required or/shift expression.
5659   Value *Load;
5660   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5661       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5662     return false;
5663 
5664   // Require that the total load bit width is a legal integer type.
5665   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5666   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5667   Type *SrcTy = Load->getType();
5668   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5669   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5670     return false;
5671 
5672   // Everything matched - assume that we can fold the whole sequence using
5673   // load combining.
5674   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5675              << *(cast<Instruction>(Root)) << "\n");
5676 
5677   return true;
5678 }
5679 
5680 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5681   if (RdxKind != RecurKind::Or)
5682     return false;
5683 
5684   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5685   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5686   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5687                                     /* MatchOr */ false);
5688 }
5689 
5690 bool BoUpSLP::isLoadCombineCandidate() const {
5691   // Peek through a final sequence of stores and check if all operations are
5692   // likely to be load-combined.
5693   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5694   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5695     Value *X;
5696     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5697         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5698       return false;
5699   }
5700   return true;
5701 }
5702 
5703 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5704   // No need to vectorize inserts of gathered values.
5705   if (VectorizableTree.size() == 2 &&
5706       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5707       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5708     return true;
5709 
5710   // We can vectorize the tree if its size is greater than or equal to the
5711   // minimum size specified by the MinTreeSize command line option.
5712   if (VectorizableTree.size() >= MinTreeSize)
5713     return false;
5714 
5715   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5716   // can vectorize it if we can prove it fully vectorizable.
5717   if (isFullyVectorizableTinyTree(ForReduction))
5718     return false;
5719 
5720   assert(VectorizableTree.empty()
5721              ? ExternalUses.empty()
5722              : true && "We shouldn't have any external users");
5723 
5724   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5725   // vectorizable.
5726   return true;
5727 }
5728 
5729 InstructionCost BoUpSLP::getSpillCost() const {
5730   // Walk from the bottom of the tree to the top, tracking which values are
5731   // live. When we see a call instruction that is not part of our tree,
5732   // query TTI to see if there is a cost to keeping values live over it
5733   // (for example, if spills and fills are required).
5734   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5735   InstructionCost Cost = 0;
5736 
5737   SmallPtrSet<Instruction*, 4> LiveValues;
5738   Instruction *PrevInst = nullptr;
5739 
5740   // The entries in VectorizableTree are not necessarily ordered by their
5741   // position in basic blocks. Collect them and order them by dominance so later
5742   // instructions are guaranteed to be visited first. For instructions in
5743   // different basic blocks, we only scan to the beginning of the block, so
5744   // their order does not matter, as long as all instructions in a basic block
5745   // are grouped together. Using dominance ensures a deterministic order.
5746   SmallVector<Instruction *, 16> OrderedScalars;
5747   for (const auto &TEPtr : VectorizableTree) {
5748     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5749     if (!Inst)
5750       continue;
5751     OrderedScalars.push_back(Inst);
5752   }
5753   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5754     auto *NodeA = DT->getNode(A->getParent());
5755     auto *NodeB = DT->getNode(B->getParent());
5756     assert(NodeA && "Should only process reachable instructions");
5757     assert(NodeB && "Should only process reachable instructions");
5758     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5759            "Different nodes should have different DFS numbers");
5760     if (NodeA != NodeB)
5761       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5762     return B->comesBefore(A);
5763   });
5764 
5765   for (Instruction *Inst : OrderedScalars) {
5766     if (!PrevInst) {
5767       PrevInst = Inst;
5768       continue;
5769     }
5770 
5771     // Update LiveValues.
5772     LiveValues.erase(PrevInst);
5773     for (auto &J : PrevInst->operands()) {
5774       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5775         LiveValues.insert(cast<Instruction>(&*J));
5776     }
5777 
5778     LLVM_DEBUG({
5779       dbgs() << "SLP: #LV: " << LiveValues.size();
5780       for (auto *X : LiveValues)
5781         dbgs() << " " << X->getName();
5782       dbgs() << ", Looking at ";
5783       Inst->dump();
5784     });
5785 
5786     // Now find the sequence of instructions between PrevInst and Inst.
5787     unsigned NumCalls = 0;
5788     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5789                                  PrevInstIt =
5790                                      PrevInst->getIterator().getReverse();
5791     while (InstIt != PrevInstIt) {
5792       if (PrevInstIt == PrevInst->getParent()->rend()) {
5793         PrevInstIt = Inst->getParent()->rbegin();
5794         continue;
5795       }
5796 
5797       // Debug information does not impact spill cost.
5798       if ((isa<CallInst>(&*PrevInstIt) &&
5799            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5800           &*PrevInstIt != PrevInst)
5801         NumCalls++;
5802 
5803       ++PrevInstIt;
5804     }
5805 
5806     if (NumCalls) {
5807       SmallVector<Type*, 4> V;
5808       for (auto *II : LiveValues) {
5809         auto *ScalarTy = II->getType();
5810         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5811           ScalarTy = VectorTy->getElementType();
5812         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5813       }
5814       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5815     }
5816 
5817     PrevInst = Inst;
5818   }
5819 
5820   return Cost;
5821 }
5822 
5823 /// Check if two insertelement instructions are from the same buildvector.
5824 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5825                                             InsertElementInst *V) {
5826   // Instructions must be from the same basic blocks.
5827   if (VU->getParent() != V->getParent())
5828     return false;
5829   // Checks if 2 insertelements are from the same buildvector.
5830   if (VU->getType() != V->getType())
5831     return false;
5832   // Multiple used inserts are separate nodes.
5833   if (!VU->hasOneUse() && !V->hasOneUse())
5834     return false;
5835   auto *IE1 = VU;
5836   auto *IE2 = V;
5837   // Go through the vector operand of insertelement instructions trying to find
5838   // either VU as the original vector for IE2 or V as the original vector for
5839   // IE1.
5840   do {
5841     if (IE2 == VU || IE1 == V)
5842       return true;
5843     if (IE1) {
5844       if (IE1 != VU && !IE1->hasOneUse())
5845         IE1 = nullptr;
5846       else
5847         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5848     }
5849     if (IE2) {
5850       if (IE2 != V && !IE2->hasOneUse())
5851         IE2 = nullptr;
5852       else
5853         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5854     }
5855   } while (IE1 || IE2);
5856   return false;
5857 }
5858 
5859 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5860   InstructionCost Cost = 0;
5861   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5862                     << VectorizableTree.size() << ".\n");
5863 
5864   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5865 
5866   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5867     TreeEntry &TE = *VectorizableTree[I].get();
5868 
5869     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5870     Cost += C;
5871     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5872                       << " for bundle that starts with " << *TE.Scalars[0]
5873                       << ".\n"
5874                       << "SLP: Current total cost = " << Cost << "\n");
5875   }
5876 
5877   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5878   InstructionCost ExtractCost = 0;
5879   SmallVector<unsigned> VF;
5880   SmallVector<SmallVector<int>> ShuffleMask;
5881   SmallVector<Value *> FirstUsers;
5882   SmallVector<APInt> DemandedElts;
5883   for (ExternalUser &EU : ExternalUses) {
5884     // We only add extract cost once for the same scalar.
5885     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5886         !ExtractCostCalculated.insert(EU.Scalar).second)
5887       continue;
5888 
5889     // Uses by ephemeral values are free (because the ephemeral value will be
5890     // removed prior to code generation, and so the extraction will be
5891     // removed as well).
5892     if (EphValues.count(EU.User))
5893       continue;
5894 
5895     // No extract cost for vector "scalar"
5896     if (isa<FixedVectorType>(EU.Scalar->getType()))
5897       continue;
5898 
5899     // Already counted the cost for external uses when tried to adjust the cost
5900     // for extractelements, no need to add it again.
5901     if (isa<ExtractElementInst>(EU.Scalar))
5902       continue;
5903 
5904     // If found user is an insertelement, do not calculate extract cost but try
5905     // to detect it as a final shuffled/identity match.
5906     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5907       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5908         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5909         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5910           continue;
5911         auto *It = find_if(FirstUsers, [VU](Value *V) {
5912           return areTwoInsertFromSameBuildVector(VU,
5913                                                  cast<InsertElementInst>(V));
5914         });
5915         int VecId = -1;
5916         if (It == FirstUsers.end()) {
5917           VF.push_back(FTy->getNumElements());
5918           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5919           // Find the insertvector, vectorized in tree, if any.
5920           Value *Base = VU;
5921           while (isa<InsertElementInst>(Base)) {
5922             // Build the mask for the vectorized insertelement instructions.
5923             if (const TreeEntry *E = getTreeEntry(Base)) {
5924               VU = cast<InsertElementInst>(Base);
5925               do {
5926                 int Idx = E->findLaneForValue(Base);
5927                 ShuffleMask.back()[Idx] = Idx;
5928                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5929               } while (E == getTreeEntry(Base));
5930               break;
5931             }
5932             Base = cast<InsertElementInst>(Base)->getOperand(0);
5933           }
5934           FirstUsers.push_back(VU);
5935           DemandedElts.push_back(APInt::getZero(VF.back()));
5936           VecId = FirstUsers.size() - 1;
5937         } else {
5938           VecId = std::distance(FirstUsers.begin(), It);
5939         }
5940         int Idx = *InsertIdx;
5941         ShuffleMask[VecId][Idx] = EU.Lane;
5942         DemandedElts[VecId].setBit(Idx);
5943         continue;
5944       }
5945     }
5946 
5947     // If we plan to rewrite the tree in a smaller type, we will need to sign
5948     // extend the extracted value back to the original type. Here, we account
5949     // for the extract and the added cost of the sign extend if needed.
5950     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5951     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5952     if (MinBWs.count(ScalarRoot)) {
5953       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5954       auto Extend =
5955           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5956       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5957       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5958                                                    VecTy, EU.Lane);
5959     } else {
5960       ExtractCost +=
5961           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5962     }
5963   }
5964 
5965   InstructionCost SpillCost = getSpillCost();
5966   Cost += SpillCost + ExtractCost;
5967   if (FirstUsers.size() == 1) {
5968     int Limit = ShuffleMask.front().size() * 2;
5969     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5970         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5971       InstructionCost C = TTI->getShuffleCost(
5972           TTI::SK_PermuteSingleSrc,
5973           cast<FixedVectorType>(FirstUsers.front()->getType()),
5974           ShuffleMask.front());
5975       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5976                         << " for final shuffle of insertelement external users "
5977                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5978                         << "SLP: Current total cost = " << Cost << "\n");
5979       Cost += C;
5980     }
5981     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5982         cast<FixedVectorType>(FirstUsers.front()->getType()),
5983         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5984     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5985                       << " for insertelements gather.\n"
5986                       << "SLP: Current total cost = " << Cost << "\n");
5987     Cost -= InsertCost;
5988   } else if (FirstUsers.size() >= 2) {
5989     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5990     // Combined masks of the first 2 vectors.
5991     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5992     copy(ShuffleMask.front(), CombinedMask.begin());
5993     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5994     auto *VecTy = FixedVectorType::get(
5995         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5996         MaxVF);
5997     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5998       if (ShuffleMask[1][I] != UndefMaskElem) {
5999         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6000         CombinedDemandedElts.setBit(I);
6001       }
6002     }
6003     InstructionCost C =
6004         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6005     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6006                       << " for final shuffle of vector node and external "
6007                          "insertelement users "
6008                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6009                       << "SLP: Current total cost = " << Cost << "\n");
6010     Cost += C;
6011     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6012         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6013     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6014                       << " for insertelements gather.\n"
6015                       << "SLP: Current total cost = " << Cost << "\n");
6016     Cost -= InsertCost;
6017     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6018       // Other elements - permutation of 2 vectors (the initial one and the
6019       // next Ith incoming vector).
6020       unsigned VF = ShuffleMask[I].size();
6021       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6022         int Mask = ShuffleMask[I][Idx];
6023         if (Mask != UndefMaskElem)
6024           CombinedMask[Idx] = MaxVF + Mask;
6025         else if (CombinedMask[Idx] != UndefMaskElem)
6026           CombinedMask[Idx] = Idx;
6027       }
6028       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6029         if (CombinedMask[Idx] != UndefMaskElem)
6030           CombinedMask[Idx] = Idx;
6031       InstructionCost C =
6032           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6033       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6034                         << " for final shuffle of vector node and external "
6035                            "insertelement users "
6036                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6037                         << "SLP: Current total cost = " << Cost << "\n");
6038       Cost += C;
6039       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6040           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6041           /*Insert*/ true, /*Extract*/ false);
6042       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6043                         << " for insertelements gather.\n"
6044                         << "SLP: Current total cost = " << Cost << "\n");
6045       Cost -= InsertCost;
6046     }
6047   }
6048 
6049 #ifndef NDEBUG
6050   SmallString<256> Str;
6051   {
6052     raw_svector_ostream OS(Str);
6053     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6054        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6055        << "SLP: Total Cost = " << Cost << ".\n";
6056   }
6057   LLVM_DEBUG(dbgs() << Str);
6058   if (ViewSLPTree)
6059     ViewGraph(this, "SLP" + F->getName(), false, Str);
6060 #endif
6061 
6062   return Cost;
6063 }
6064 
6065 Optional<TargetTransformInfo::ShuffleKind>
6066 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6067                                SmallVectorImpl<const TreeEntry *> &Entries) {
6068   // TODO: currently checking only for Scalars in the tree entry, need to count
6069   // reused elements too for better cost estimation.
6070   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6071   Entries.clear();
6072   // Build a lists of values to tree entries.
6073   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6074   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6075     if (EntryPtr.get() == TE)
6076       break;
6077     if (EntryPtr->State != TreeEntry::NeedToGather)
6078       continue;
6079     for (Value *V : EntryPtr->Scalars)
6080       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6081   }
6082   // Find all tree entries used by the gathered values. If no common entries
6083   // found - not a shuffle.
6084   // Here we build a set of tree nodes for each gathered value and trying to
6085   // find the intersection between these sets. If we have at least one common
6086   // tree node for each gathered value - we have just a permutation of the
6087   // single vector. If we have 2 different sets, we're in situation where we
6088   // have a permutation of 2 input vectors.
6089   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6090   DenseMap<Value *, int> UsedValuesEntry;
6091   for (Value *V : TE->Scalars) {
6092     if (isa<UndefValue>(V))
6093       continue;
6094     // Build a list of tree entries where V is used.
6095     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6096     auto It = ValueToTEs.find(V);
6097     if (It != ValueToTEs.end())
6098       VToTEs = It->second;
6099     if (const TreeEntry *VTE = getTreeEntry(V))
6100       VToTEs.insert(VTE);
6101     if (VToTEs.empty())
6102       return None;
6103     if (UsedTEs.empty()) {
6104       // The first iteration, just insert the list of nodes to vector.
6105       UsedTEs.push_back(VToTEs);
6106     } else {
6107       // Need to check if there are any previously used tree nodes which use V.
6108       // If there are no such nodes, consider that we have another one input
6109       // vector.
6110       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6111       unsigned Idx = 0;
6112       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6113         // Do we have a non-empty intersection of previously listed tree entries
6114         // and tree entries using current V?
6115         set_intersect(VToTEs, Set);
6116         if (!VToTEs.empty()) {
6117           // Yes, write the new subset and continue analysis for the next
6118           // scalar.
6119           Set.swap(VToTEs);
6120           break;
6121         }
6122         VToTEs = SavedVToTEs;
6123         ++Idx;
6124       }
6125       // No non-empty intersection found - need to add a second set of possible
6126       // source vectors.
6127       if (Idx == UsedTEs.size()) {
6128         // If the number of input vectors is greater than 2 - not a permutation,
6129         // fallback to the regular gather.
6130         if (UsedTEs.size() == 2)
6131           return None;
6132         UsedTEs.push_back(SavedVToTEs);
6133         Idx = UsedTEs.size() - 1;
6134       }
6135       UsedValuesEntry.try_emplace(V, Idx);
6136     }
6137   }
6138 
6139   unsigned VF = 0;
6140   if (UsedTEs.size() == 1) {
6141     // Try to find the perfect match in another gather node at first.
6142     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6143       return EntryPtr->isSame(TE->Scalars);
6144     });
6145     if (It != UsedTEs.front().end()) {
6146       Entries.push_back(*It);
6147       std::iota(Mask.begin(), Mask.end(), 0);
6148       return TargetTransformInfo::SK_PermuteSingleSrc;
6149     }
6150     // No perfect match, just shuffle, so choose the first tree node.
6151     Entries.push_back(*UsedTEs.front().begin());
6152   } else {
6153     // Try to find nodes with the same vector factor.
6154     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6155     DenseMap<int, const TreeEntry *> VFToTE;
6156     for (const TreeEntry *TE : UsedTEs.front())
6157       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6158     for (const TreeEntry *TE : UsedTEs.back()) {
6159       auto It = VFToTE.find(TE->getVectorFactor());
6160       if (It != VFToTE.end()) {
6161         VF = It->first;
6162         Entries.push_back(It->second);
6163         Entries.push_back(TE);
6164         break;
6165       }
6166     }
6167     // No 2 source vectors with the same vector factor - give up and do regular
6168     // gather.
6169     if (Entries.empty())
6170       return None;
6171   }
6172 
6173   // Build a shuffle mask for better cost estimation and vector emission.
6174   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6175     Value *V = TE->Scalars[I];
6176     if (isa<UndefValue>(V))
6177       continue;
6178     unsigned Idx = UsedValuesEntry.lookup(V);
6179     const TreeEntry *VTE = Entries[Idx];
6180     int FoundLane = VTE->findLaneForValue(V);
6181     Mask[I] = Idx * VF + FoundLane;
6182     // Extra check required by isSingleSourceMaskImpl function (called by
6183     // ShuffleVectorInst::isSingleSourceMask).
6184     if (Mask[I] >= 2 * E)
6185       return None;
6186   }
6187   switch (Entries.size()) {
6188   case 1:
6189     return TargetTransformInfo::SK_PermuteSingleSrc;
6190   case 2:
6191     return TargetTransformInfo::SK_PermuteTwoSrc;
6192   default:
6193     break;
6194   }
6195   return None;
6196 }
6197 
6198 InstructionCost
6199 BoUpSLP::getGatherCost(FixedVectorType *Ty,
6200                        const DenseSet<unsigned> &ShuffledIndices,
6201                        bool NeedToShuffle) const {
6202   unsigned NumElts = Ty->getNumElements();
6203   APInt DemandedElts = APInt::getZero(NumElts);
6204   for (unsigned I = 0; I < NumElts; ++I)
6205     if (!ShuffledIndices.count(I))
6206       DemandedElts.setBit(I);
6207   InstructionCost Cost =
6208       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
6209                                     /*Extract*/ false);
6210   if (NeedToShuffle)
6211     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6212   return Cost;
6213 }
6214 
6215 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6216   // Find the type of the operands in VL.
6217   Type *ScalarTy = VL[0]->getType();
6218   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6219     ScalarTy = SI->getValueOperand()->getType();
6220   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6221   bool DuplicateNonConst = false;
6222   // Find the cost of inserting/extracting values from the vector.
6223   // Check if the same elements are inserted several times and count them as
6224   // shuffle candidates.
6225   DenseSet<unsigned> ShuffledElements;
6226   DenseSet<Value *> UniqueElements;
6227   // Iterate in reverse order to consider insert elements with the high cost.
6228   for (unsigned I = VL.size(); I > 0; --I) {
6229     unsigned Idx = I - 1;
6230     // No need to shuffle duplicates for constants.
6231     if (isConstant(VL[Idx])) {
6232       ShuffledElements.insert(Idx);
6233       continue;
6234     }
6235     if (!UniqueElements.insert(VL[Idx]).second) {
6236       DuplicateNonConst = true;
6237       ShuffledElements.insert(Idx);
6238     }
6239   }
6240   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6241 }
6242 
6243 // Perform operand reordering on the instructions in VL and return the reordered
6244 // operands in Left and Right.
6245 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6246                                              SmallVectorImpl<Value *> &Left,
6247                                              SmallVectorImpl<Value *> &Right,
6248                                              const DataLayout &DL,
6249                                              ScalarEvolution &SE,
6250                                              const BoUpSLP &R) {
6251   if (VL.empty())
6252     return;
6253   VLOperands Ops(VL, DL, SE, R);
6254   // Reorder the operands in place.
6255   Ops.reorder();
6256   Left = Ops.getVL(0);
6257   Right = Ops.getVL(1);
6258 }
6259 
6260 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6261   // Get the basic block this bundle is in. All instructions in the bundle
6262   // should be in this block.
6263   auto *Front = E->getMainOp();
6264   auto *BB = Front->getParent();
6265   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6266     auto *I = cast<Instruction>(V);
6267     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6268   }));
6269 
6270   // The last instruction in the bundle in program order.
6271   Instruction *LastInst = nullptr;
6272 
6273   // Find the last instruction. The common case should be that BB has been
6274   // scheduled, and the last instruction is VL.back(). So we start with
6275   // VL.back() and iterate over schedule data until we reach the end of the
6276   // bundle. The end of the bundle is marked by null ScheduleData.
6277   if (BlocksSchedules.count(BB)) {
6278     auto *Bundle =
6279         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6280     if (Bundle && Bundle->isPartOfBundle())
6281       for (; Bundle; Bundle = Bundle->NextInBundle)
6282         if (Bundle->OpValue == Bundle->Inst)
6283           LastInst = Bundle->Inst;
6284   }
6285 
6286   // LastInst can still be null at this point if there's either not an entry
6287   // for BB in BlocksSchedules or there's no ScheduleData available for
6288   // VL.back(). This can be the case if buildTree_rec aborts for various
6289   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6290   // size is reached, etc.). ScheduleData is initialized in the scheduling
6291   // "dry-run".
6292   //
6293   // If this happens, we can still find the last instruction by brute force. We
6294   // iterate forwards from Front (inclusive) until we either see all
6295   // instructions in the bundle or reach the end of the block. If Front is the
6296   // last instruction in program order, LastInst will be set to Front, and we
6297   // will visit all the remaining instructions in the block.
6298   //
6299   // One of the reasons we exit early from buildTree_rec is to place an upper
6300   // bound on compile-time. Thus, taking an additional compile-time hit here is
6301   // not ideal. However, this should be exceedingly rare since it requires that
6302   // we both exit early from buildTree_rec and that the bundle be out-of-order
6303   // (causing us to iterate all the way to the end of the block).
6304   if (!LastInst) {
6305     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6306     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6307       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6308         LastInst = &I;
6309       if (Bundle.empty())
6310         break;
6311     }
6312   }
6313   assert(LastInst && "Failed to find last instruction in bundle");
6314 
6315   // Set the insertion point after the last instruction in the bundle. Set the
6316   // debug location to Front.
6317   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6318   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6319 }
6320 
6321 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6322   // List of instructions/lanes from current block and/or the blocks which are
6323   // part of the current loop. These instructions will be inserted at the end to
6324   // make it possible to optimize loops and hoist invariant instructions out of
6325   // the loops body with better chances for success.
6326   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6327   SmallSet<int, 4> PostponedIndices;
6328   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6329   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6330     SmallPtrSet<BasicBlock *, 4> Visited;
6331     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6332       InsertBB = InsertBB->getSinglePredecessor();
6333     return InsertBB && InsertBB == InstBB;
6334   };
6335   for (int I = 0, E = VL.size(); I < E; ++I) {
6336     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6337       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6338            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6339           PostponedIndices.insert(I).second)
6340         PostponedInsts.emplace_back(Inst, I);
6341   }
6342 
6343   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6344     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6345     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6346     if (!InsElt)
6347       return Vec;
6348     GatherShuffleSeq.insert(InsElt);
6349     CSEBlocks.insert(InsElt->getParent());
6350     // Add to our 'need-to-extract' list.
6351     if (TreeEntry *Entry = getTreeEntry(V)) {
6352       // Find which lane we need to extract.
6353       unsigned FoundLane = Entry->findLaneForValue(V);
6354       ExternalUses.emplace_back(V, InsElt, FoundLane);
6355     }
6356     return Vec;
6357   };
6358   Value *Val0 =
6359       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6360   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6361   Value *Vec = PoisonValue::get(VecTy);
6362   SmallVector<int> NonConsts;
6363   // Insert constant values at first.
6364   for (int I = 0, E = VL.size(); I < E; ++I) {
6365     if (PostponedIndices.contains(I))
6366       continue;
6367     if (!isConstant(VL[I])) {
6368       NonConsts.push_back(I);
6369       continue;
6370     }
6371     Vec = CreateInsertElement(Vec, VL[I], I);
6372   }
6373   // Insert non-constant values.
6374   for (int I : NonConsts)
6375     Vec = CreateInsertElement(Vec, VL[I], I);
6376   // Append instructions, which are/may be part of the loop, in the end to make
6377   // it possible to hoist non-loop-based instructions.
6378   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6379     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6380 
6381   return Vec;
6382 }
6383 
6384 namespace {
6385 /// Merges shuffle masks and emits final shuffle instruction, if required.
6386 class ShuffleInstructionBuilder {
6387   IRBuilderBase &Builder;
6388   const unsigned VF = 0;
6389   bool IsFinalized = false;
6390   SmallVector<int, 4> Mask;
6391   /// Holds all of the instructions that we gathered.
6392   SetVector<Instruction *> &GatherShuffleSeq;
6393   /// A list of blocks that we are going to CSE.
6394   SetVector<BasicBlock *> &CSEBlocks;
6395 
6396 public:
6397   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6398                             SetVector<Instruction *> &GatherShuffleSeq,
6399                             SetVector<BasicBlock *> &CSEBlocks)
6400       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6401         CSEBlocks(CSEBlocks) {}
6402 
6403   /// Adds a mask, inverting it before applying.
6404   void addInversedMask(ArrayRef<unsigned> SubMask) {
6405     if (SubMask.empty())
6406       return;
6407     SmallVector<int, 4> NewMask;
6408     inversePermutation(SubMask, NewMask);
6409     addMask(NewMask);
6410   }
6411 
6412   /// Functions adds masks, merging them into  single one.
6413   void addMask(ArrayRef<unsigned> SubMask) {
6414     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6415     addMask(NewMask);
6416   }
6417 
6418   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6419 
6420   Value *finalize(Value *V) {
6421     IsFinalized = true;
6422     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6423     if (VF == ValueVF && Mask.empty())
6424       return V;
6425     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6426     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6427     addMask(NormalizedMask);
6428 
6429     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6430       return V;
6431     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6432     if (auto *I = dyn_cast<Instruction>(Vec)) {
6433       GatherShuffleSeq.insert(I);
6434       CSEBlocks.insert(I->getParent());
6435     }
6436     return Vec;
6437   }
6438 
6439   ~ShuffleInstructionBuilder() {
6440     assert((IsFinalized || Mask.empty()) &&
6441            "Shuffle construction must be finalized.");
6442   }
6443 };
6444 } // namespace
6445 
6446 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6447   unsigned VF = VL.size();
6448   InstructionsState S = getSameOpcode(VL);
6449   if (S.getOpcode()) {
6450     if (TreeEntry *E = getTreeEntry(S.OpValue))
6451       if (E->isSame(VL)) {
6452         Value *V = vectorizeTree(E);
6453         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6454           if (!E->ReuseShuffleIndices.empty()) {
6455             // Reshuffle to get only unique values.
6456             // If some of the scalars are duplicated in the vectorization tree
6457             // entry, we do not vectorize them but instead generate a mask for
6458             // the reuses. But if there are several users of the same entry,
6459             // they may have different vectorization factors. This is especially
6460             // important for PHI nodes. In this case, we need to adapt the
6461             // resulting instruction for the user vectorization factor and have
6462             // to reshuffle it again to take only unique elements of the vector.
6463             // Without this code the function incorrectly returns reduced vector
6464             // instruction with the same elements, not with the unique ones.
6465 
6466             // block:
6467             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6468             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6469             // ... (use %2)
6470             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6471             // br %block
6472             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6473             SmallSet<int, 4> UsedIdxs;
6474             int Pos = 0;
6475             int Sz = VL.size();
6476             for (int Idx : E->ReuseShuffleIndices) {
6477               if (Idx != Sz && Idx != UndefMaskElem &&
6478                   UsedIdxs.insert(Idx).second)
6479                 UniqueIdxs[Idx] = Pos;
6480               ++Pos;
6481             }
6482             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6483                                             "less than original vector size.");
6484             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6485             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6486           } else {
6487             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6488                    "Expected vectorization factor less "
6489                    "than original vector size.");
6490             SmallVector<int> UniformMask(VF, 0);
6491             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6492             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6493           }
6494           if (auto *I = dyn_cast<Instruction>(V)) {
6495             GatherShuffleSeq.insert(I);
6496             CSEBlocks.insert(I->getParent());
6497           }
6498         }
6499         return V;
6500       }
6501   }
6502 
6503   // Check that every instruction appears once in this bundle.
6504   SmallVector<int> ReuseShuffleIndicies;
6505   SmallVector<Value *> UniqueValues;
6506   if (VL.size() > 2) {
6507     DenseMap<Value *, unsigned> UniquePositions;
6508     unsigned NumValues =
6509         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6510                                     return !isa<UndefValue>(V);
6511                                   }).base());
6512     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6513     int UniqueVals = 0;
6514     for (Value *V : VL.drop_back(VL.size() - VF)) {
6515       if (isa<UndefValue>(V)) {
6516         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6517         continue;
6518       }
6519       if (isConstant(V)) {
6520         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6521         UniqueValues.emplace_back(V);
6522         continue;
6523       }
6524       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6525       ReuseShuffleIndicies.emplace_back(Res.first->second);
6526       if (Res.second) {
6527         UniqueValues.emplace_back(V);
6528         ++UniqueVals;
6529       }
6530     }
6531     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6532       // Emit pure splat vector.
6533       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6534                                   UndefMaskElem);
6535     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6536       ReuseShuffleIndicies.clear();
6537       UniqueValues.clear();
6538       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6539     }
6540     UniqueValues.append(VF - UniqueValues.size(),
6541                         PoisonValue::get(VL[0]->getType()));
6542     VL = UniqueValues;
6543   }
6544 
6545   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6546                                            CSEBlocks);
6547   Value *Vec = gather(VL);
6548   if (!ReuseShuffleIndicies.empty()) {
6549     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6550     Vec = ShuffleBuilder.finalize(Vec);
6551   }
6552   return Vec;
6553 }
6554 
6555 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6556   IRBuilder<>::InsertPointGuard Guard(Builder);
6557 
6558   if (E->VectorizedValue) {
6559     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6560     return E->VectorizedValue;
6561   }
6562 
6563   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6564   unsigned VF = E->getVectorFactor();
6565   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6566                                            CSEBlocks);
6567   if (E->State == TreeEntry::NeedToGather) {
6568     if (E->getMainOp())
6569       setInsertPointAfterBundle(E);
6570     Value *Vec;
6571     SmallVector<int> Mask;
6572     SmallVector<const TreeEntry *> Entries;
6573     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6574         isGatherShuffledEntry(E, Mask, Entries);
6575     if (Shuffle.hasValue()) {
6576       assert((Entries.size() == 1 || Entries.size() == 2) &&
6577              "Expected shuffle of 1 or 2 entries.");
6578       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6579                                         Entries.back()->VectorizedValue, Mask);
6580       if (auto *I = dyn_cast<Instruction>(Vec)) {
6581         GatherShuffleSeq.insert(I);
6582         CSEBlocks.insert(I->getParent());
6583       }
6584     } else {
6585       Vec = gather(E->Scalars);
6586     }
6587     if (NeedToShuffleReuses) {
6588       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6589       Vec = ShuffleBuilder.finalize(Vec);
6590     }
6591     E->VectorizedValue = Vec;
6592     return Vec;
6593   }
6594 
6595   assert((E->State == TreeEntry::Vectorize ||
6596           E->State == TreeEntry::ScatterVectorize) &&
6597          "Unhandled state");
6598   unsigned ShuffleOrOp =
6599       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6600   Instruction *VL0 = E->getMainOp();
6601   Type *ScalarTy = VL0->getType();
6602   if (auto *Store = dyn_cast<StoreInst>(VL0))
6603     ScalarTy = Store->getValueOperand()->getType();
6604   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6605     ScalarTy = IE->getOperand(1)->getType();
6606   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6607   switch (ShuffleOrOp) {
6608     case Instruction::PHI: {
6609       assert(
6610           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6611           "PHI reordering is free.");
6612       auto *PH = cast<PHINode>(VL0);
6613       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6614       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6615       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6616       Value *V = NewPhi;
6617       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6618       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6619       V = ShuffleBuilder.finalize(V);
6620 
6621       E->VectorizedValue = V;
6622 
6623       // PHINodes may have multiple entries from the same block. We want to
6624       // visit every block once.
6625       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6626 
6627       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6628         ValueList Operands;
6629         BasicBlock *IBB = PH->getIncomingBlock(i);
6630 
6631         if (!VisitedBBs.insert(IBB).second) {
6632           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6633           continue;
6634         }
6635 
6636         Builder.SetInsertPoint(IBB->getTerminator());
6637         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6638         Value *Vec = vectorizeTree(E->getOperand(i));
6639         NewPhi->addIncoming(Vec, IBB);
6640       }
6641 
6642       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6643              "Invalid number of incoming values");
6644       return V;
6645     }
6646 
6647     case Instruction::ExtractElement: {
6648       Value *V = E->getSingleOperand(0);
6649       Builder.SetInsertPoint(VL0);
6650       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6651       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6652       V = ShuffleBuilder.finalize(V);
6653       E->VectorizedValue = V;
6654       return V;
6655     }
6656     case Instruction::ExtractValue: {
6657       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6658       Builder.SetInsertPoint(LI);
6659       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6660       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6661       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6662       Value *NewV = propagateMetadata(V, E->Scalars);
6663       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6664       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6665       NewV = ShuffleBuilder.finalize(NewV);
6666       E->VectorizedValue = NewV;
6667       return NewV;
6668     }
6669     case Instruction::InsertElement: {
6670       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6671       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6672       Value *V = vectorizeTree(E->getOperand(1));
6673 
6674       // Create InsertVector shuffle if necessary
6675       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6676         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6677       }));
6678       const unsigned NumElts =
6679           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6680       const unsigned NumScalars = E->Scalars.size();
6681 
6682       unsigned Offset = *getInsertIndex(VL0, 0);
6683       assert(Offset < NumElts && "Failed to find vector index offset");
6684 
6685       // Create shuffle to resize vector
6686       SmallVector<int> Mask;
6687       if (!E->ReorderIndices.empty()) {
6688         inversePermutation(E->ReorderIndices, Mask);
6689         Mask.append(NumElts - NumScalars, UndefMaskElem);
6690       } else {
6691         Mask.assign(NumElts, UndefMaskElem);
6692         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6693       }
6694       // Create InsertVector shuffle if necessary
6695       bool IsIdentity = true;
6696       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6697       Mask.swap(PrevMask);
6698       for (unsigned I = 0; I < NumScalars; ++I) {
6699         Value *Scalar = E->Scalars[PrevMask[I]];
6700         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6701         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6702           continue;
6703         IsIdentity &= *InsertIdx - Offset == I;
6704         Mask[*InsertIdx - Offset] = I;
6705       }
6706       if (!IsIdentity || NumElts != NumScalars) {
6707         V = Builder.CreateShuffleVector(V, Mask);
6708         if (auto *I = dyn_cast<Instruction>(V)) {
6709           GatherShuffleSeq.insert(I);
6710           CSEBlocks.insert(I->getParent());
6711         }
6712       }
6713 
6714       if ((!IsIdentity || Offset != 0 ||
6715            !isUndefVector(FirstInsert->getOperand(0))) &&
6716           NumElts != NumScalars) {
6717         SmallVector<int> InsertMask(NumElts);
6718         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6719         for (unsigned I = 0; I < NumElts; I++) {
6720           if (Mask[I] != UndefMaskElem)
6721             InsertMask[Offset + I] = NumElts + I;
6722         }
6723 
6724         V = Builder.CreateShuffleVector(
6725             FirstInsert->getOperand(0), V, InsertMask,
6726             cast<Instruction>(E->Scalars.back())->getName());
6727         if (auto *I = dyn_cast<Instruction>(V)) {
6728           GatherShuffleSeq.insert(I);
6729           CSEBlocks.insert(I->getParent());
6730         }
6731       }
6732 
6733       ++NumVectorInstructions;
6734       E->VectorizedValue = V;
6735       return V;
6736     }
6737     case Instruction::ZExt:
6738     case Instruction::SExt:
6739     case Instruction::FPToUI:
6740     case Instruction::FPToSI:
6741     case Instruction::FPExt:
6742     case Instruction::PtrToInt:
6743     case Instruction::IntToPtr:
6744     case Instruction::SIToFP:
6745     case Instruction::UIToFP:
6746     case Instruction::Trunc:
6747     case Instruction::FPTrunc:
6748     case Instruction::BitCast: {
6749       setInsertPointAfterBundle(E);
6750 
6751       Value *InVec = vectorizeTree(E->getOperand(0));
6752 
6753       if (E->VectorizedValue) {
6754         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6755         return E->VectorizedValue;
6756       }
6757 
6758       auto *CI = cast<CastInst>(VL0);
6759       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6760       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6761       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6762       V = ShuffleBuilder.finalize(V);
6763 
6764       E->VectorizedValue = V;
6765       ++NumVectorInstructions;
6766       return V;
6767     }
6768     case Instruction::FCmp:
6769     case Instruction::ICmp: {
6770       setInsertPointAfterBundle(E);
6771 
6772       Value *L = vectorizeTree(E->getOperand(0));
6773       Value *R = vectorizeTree(E->getOperand(1));
6774 
6775       if (E->VectorizedValue) {
6776         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6777         return E->VectorizedValue;
6778       }
6779 
6780       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6781       Value *V = Builder.CreateCmp(P0, L, R);
6782       propagateIRFlags(V, E->Scalars, VL0);
6783       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6784       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6785       V = ShuffleBuilder.finalize(V);
6786 
6787       E->VectorizedValue = V;
6788       ++NumVectorInstructions;
6789       return V;
6790     }
6791     case Instruction::Select: {
6792       setInsertPointAfterBundle(E);
6793 
6794       Value *Cond = vectorizeTree(E->getOperand(0));
6795       Value *True = vectorizeTree(E->getOperand(1));
6796       Value *False = vectorizeTree(E->getOperand(2));
6797 
6798       if (E->VectorizedValue) {
6799         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6800         return E->VectorizedValue;
6801       }
6802 
6803       Value *V = Builder.CreateSelect(Cond, True, False);
6804       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6805       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6806       V = ShuffleBuilder.finalize(V);
6807 
6808       E->VectorizedValue = V;
6809       ++NumVectorInstructions;
6810       return V;
6811     }
6812     case Instruction::FNeg: {
6813       setInsertPointAfterBundle(E);
6814 
6815       Value *Op = vectorizeTree(E->getOperand(0));
6816 
6817       if (E->VectorizedValue) {
6818         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6819         return E->VectorizedValue;
6820       }
6821 
6822       Value *V = Builder.CreateUnOp(
6823           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6824       propagateIRFlags(V, E->Scalars, VL0);
6825       if (auto *I = dyn_cast<Instruction>(V))
6826         V = propagateMetadata(I, E->Scalars);
6827 
6828       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6829       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6830       V = ShuffleBuilder.finalize(V);
6831 
6832       E->VectorizedValue = V;
6833       ++NumVectorInstructions;
6834 
6835       return V;
6836     }
6837     case Instruction::Add:
6838     case Instruction::FAdd:
6839     case Instruction::Sub:
6840     case Instruction::FSub:
6841     case Instruction::Mul:
6842     case Instruction::FMul:
6843     case Instruction::UDiv:
6844     case Instruction::SDiv:
6845     case Instruction::FDiv:
6846     case Instruction::URem:
6847     case Instruction::SRem:
6848     case Instruction::FRem:
6849     case Instruction::Shl:
6850     case Instruction::LShr:
6851     case Instruction::AShr:
6852     case Instruction::And:
6853     case Instruction::Or:
6854     case Instruction::Xor: {
6855       setInsertPointAfterBundle(E);
6856 
6857       Value *LHS = vectorizeTree(E->getOperand(0));
6858       Value *RHS = vectorizeTree(E->getOperand(1));
6859 
6860       if (E->VectorizedValue) {
6861         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6862         return E->VectorizedValue;
6863       }
6864 
6865       Value *V = Builder.CreateBinOp(
6866           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6867           RHS);
6868       propagateIRFlags(V, E->Scalars, VL0);
6869       if (auto *I = dyn_cast<Instruction>(V))
6870         V = propagateMetadata(I, E->Scalars);
6871 
6872       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6873       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6874       V = ShuffleBuilder.finalize(V);
6875 
6876       E->VectorizedValue = V;
6877       ++NumVectorInstructions;
6878 
6879       return V;
6880     }
6881     case Instruction::Load: {
6882       // Loads are inserted at the head of the tree because we don't want to
6883       // sink them all the way down past store instructions.
6884       setInsertPointAfterBundle(E);
6885 
6886       LoadInst *LI = cast<LoadInst>(VL0);
6887       Instruction *NewLI;
6888       unsigned AS = LI->getPointerAddressSpace();
6889       Value *PO = LI->getPointerOperand();
6890       if (E->State == TreeEntry::Vectorize) {
6891 
6892         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6893 
6894         // The pointer operand uses an in-tree scalar so we add the new BitCast
6895         // to ExternalUses list to make sure that an extract will be generated
6896         // in the future.
6897         if (TreeEntry *Entry = getTreeEntry(PO)) {
6898           // Find which lane we need to extract.
6899           unsigned FoundLane = Entry->findLaneForValue(PO);
6900           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6901         }
6902 
6903         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6904       } else {
6905         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6906         Value *VecPtr = vectorizeTree(E->getOperand(0));
6907         // Use the minimum alignment of the gathered loads.
6908         Align CommonAlignment = LI->getAlign();
6909         for (Value *V : E->Scalars)
6910           CommonAlignment =
6911               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6912         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6913       }
6914       Value *V = propagateMetadata(NewLI, E->Scalars);
6915 
6916       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6917       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6918       V = ShuffleBuilder.finalize(V);
6919       E->VectorizedValue = V;
6920       ++NumVectorInstructions;
6921       return V;
6922     }
6923     case Instruction::Store: {
6924       auto *SI = cast<StoreInst>(VL0);
6925       unsigned AS = SI->getPointerAddressSpace();
6926 
6927       setInsertPointAfterBundle(E);
6928 
6929       Value *VecValue = vectorizeTree(E->getOperand(0));
6930       ShuffleBuilder.addMask(E->ReorderIndices);
6931       VecValue = ShuffleBuilder.finalize(VecValue);
6932 
6933       Value *ScalarPtr = SI->getPointerOperand();
6934       Value *VecPtr = Builder.CreateBitCast(
6935           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6936       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6937                                                  SI->getAlign());
6938 
6939       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6940       // ExternalUses to make sure that an extract will be generated in the
6941       // future.
6942       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6943         // Find which lane we need to extract.
6944         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6945         ExternalUses.push_back(
6946             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6947       }
6948 
6949       Value *V = propagateMetadata(ST, E->Scalars);
6950 
6951       E->VectorizedValue = V;
6952       ++NumVectorInstructions;
6953       return V;
6954     }
6955     case Instruction::GetElementPtr: {
6956       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6957       setInsertPointAfterBundle(E);
6958 
6959       Value *Op0 = vectorizeTree(E->getOperand(0));
6960 
6961       SmallVector<Value *> OpVecs;
6962       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6963         Value *OpVec = vectorizeTree(E->getOperand(J));
6964         OpVecs.push_back(OpVec);
6965       }
6966 
6967       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6968       if (Instruction *I = dyn_cast<Instruction>(V))
6969         V = propagateMetadata(I, E->Scalars);
6970 
6971       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6972       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6973       V = ShuffleBuilder.finalize(V);
6974 
6975       E->VectorizedValue = V;
6976       ++NumVectorInstructions;
6977 
6978       return V;
6979     }
6980     case Instruction::Call: {
6981       CallInst *CI = cast<CallInst>(VL0);
6982       setInsertPointAfterBundle(E);
6983 
6984       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6985       if (Function *FI = CI->getCalledFunction())
6986         IID = FI->getIntrinsicID();
6987 
6988       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6989 
6990       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6991       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6992                           VecCallCosts.first <= VecCallCosts.second;
6993 
6994       Value *ScalarArg = nullptr;
6995       std::vector<Value *> OpVecs;
6996       SmallVector<Type *, 2> TysForDecl =
6997           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6998       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6999         ValueList OpVL;
7000         // Some intrinsics have scalar arguments. This argument should not be
7001         // vectorized.
7002         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7003           CallInst *CEI = cast<CallInst>(VL0);
7004           ScalarArg = CEI->getArgOperand(j);
7005           OpVecs.push_back(CEI->getArgOperand(j));
7006           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7007             TysForDecl.push_back(ScalarArg->getType());
7008           continue;
7009         }
7010 
7011         Value *OpVec = vectorizeTree(E->getOperand(j));
7012         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7013         OpVecs.push_back(OpVec);
7014       }
7015 
7016       Function *CF;
7017       if (!UseIntrinsic) {
7018         VFShape Shape =
7019             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7020                                   VecTy->getNumElements())),
7021                          false /*HasGlobalPred*/);
7022         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7023       } else {
7024         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7025       }
7026 
7027       SmallVector<OperandBundleDef, 1> OpBundles;
7028       CI->getOperandBundlesAsDefs(OpBundles);
7029       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7030 
7031       // The scalar argument uses an in-tree scalar so we add the new vectorized
7032       // call to ExternalUses list to make sure that an extract will be
7033       // generated in the future.
7034       if (ScalarArg) {
7035         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7036           // Find which lane we need to extract.
7037           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7038           ExternalUses.push_back(
7039               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7040         }
7041       }
7042 
7043       propagateIRFlags(V, E->Scalars, VL0);
7044       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7045       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7046       V = ShuffleBuilder.finalize(V);
7047 
7048       E->VectorizedValue = V;
7049       ++NumVectorInstructions;
7050       return V;
7051     }
7052     case Instruction::ShuffleVector: {
7053       assert(E->isAltShuffle() &&
7054              ((Instruction::isBinaryOp(E->getOpcode()) &&
7055                Instruction::isBinaryOp(E->getAltOpcode())) ||
7056               (Instruction::isCast(E->getOpcode()) &&
7057                Instruction::isCast(E->getAltOpcode())) ||
7058               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7059              "Invalid Shuffle Vector Operand");
7060 
7061       Value *LHS = nullptr, *RHS = nullptr;
7062       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7063         setInsertPointAfterBundle(E);
7064         LHS = vectorizeTree(E->getOperand(0));
7065         RHS = vectorizeTree(E->getOperand(1));
7066       } else {
7067         setInsertPointAfterBundle(E);
7068         LHS = vectorizeTree(E->getOperand(0));
7069       }
7070 
7071       if (E->VectorizedValue) {
7072         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7073         return E->VectorizedValue;
7074       }
7075 
7076       Value *V0, *V1;
7077       if (Instruction::isBinaryOp(E->getOpcode())) {
7078         V0 = Builder.CreateBinOp(
7079             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7080         V1 = Builder.CreateBinOp(
7081             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7082       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7083         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7084         auto *AltCI = cast<CmpInst>(E->getAltOp());
7085         CmpInst::Predicate AltPred = AltCI->getPredicate();
7086         unsigned AltIdx =
7087             std::distance(E->Scalars.begin(), find(E->Scalars, AltCI));
7088         if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx])
7089           AltPred = CmpInst::getSwappedPredicate(AltPred);
7090         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7091       } else {
7092         V0 = Builder.CreateCast(
7093             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7094         V1 = Builder.CreateCast(
7095             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7096       }
7097       // Add V0 and V1 to later analysis to try to find and remove matching
7098       // instruction, if any.
7099       for (Value *V : {V0, V1}) {
7100         if (auto *I = dyn_cast<Instruction>(V)) {
7101           GatherShuffleSeq.insert(I);
7102           CSEBlocks.insert(I->getParent());
7103         }
7104       }
7105 
7106       // Create shuffle to take alternate operations from the vector.
7107       // Also, gather up main and alt scalar ops to propagate IR flags to
7108       // each vector operation.
7109       ValueList OpScalars, AltScalars;
7110       SmallVector<int> Mask;
7111       buildSuffleEntryMask(
7112           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7113           [E](Instruction *I) {
7114             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7115             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
7116               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
7117               auto *CI = cast<CmpInst>(I);
7118               CmpInst::Predicate P0 = CI0->getPredicate();
7119               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
7120               assert(P0 != AltP0 &&
7121                      "Expected different main/alternate predicates.");
7122               CmpInst::Predicate AltP0Swapped =
7123                   CmpInst::getSwappedPredicate(AltP0);
7124               CmpInst::Predicate CurrentPred = CI->getPredicate();
7125               if (P0 == AltP0Swapped)
7126                 return (P0 == CurrentPred &&
7127                         !areCompatibleCmpOps(
7128                             CI0->getOperand(0), CI0->getOperand(1),
7129                             CI->getOperand(0), CI->getOperand(1))) ||
7130                        (AltP0 == CurrentPred &&
7131                         !areCompatibleCmpOps(
7132                             CI0->getOperand(0), CI0->getOperand(1),
7133                             CI->getOperand(1), CI->getOperand(0)));
7134               return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
7135             }
7136             return I->getOpcode() == E->getAltOpcode();
7137           },
7138           Mask, &OpScalars, &AltScalars);
7139 
7140       propagateIRFlags(V0, OpScalars);
7141       propagateIRFlags(V1, AltScalars);
7142 
7143       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7144       if (auto *I = dyn_cast<Instruction>(V)) {
7145         V = propagateMetadata(I, E->Scalars);
7146         GatherShuffleSeq.insert(I);
7147         CSEBlocks.insert(I->getParent());
7148       }
7149       V = ShuffleBuilder.finalize(V);
7150 
7151       E->VectorizedValue = V;
7152       ++NumVectorInstructions;
7153 
7154       return V;
7155     }
7156     default:
7157     llvm_unreachable("unknown inst");
7158   }
7159   return nullptr;
7160 }
7161 
7162 Value *BoUpSLP::vectorizeTree() {
7163   ExtraValueToDebugLocsMap ExternallyUsedValues;
7164   return vectorizeTree(ExternallyUsedValues);
7165 }
7166 
7167 Value *
7168 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7169   // All blocks must be scheduled before any instructions are inserted.
7170   for (auto &BSIter : BlocksSchedules) {
7171     scheduleBlock(BSIter.second.get());
7172   }
7173 
7174   Builder.SetInsertPoint(&F->getEntryBlock().front());
7175   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7176 
7177   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7178   // vectorized root. InstCombine will then rewrite the entire expression. We
7179   // sign extend the extracted values below.
7180   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7181   if (MinBWs.count(ScalarRoot)) {
7182     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7183       // If current instr is a phi and not the last phi, insert it after the
7184       // last phi node.
7185       if (isa<PHINode>(I))
7186         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7187       else
7188         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7189     }
7190     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7191     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7192     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7193     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7194     VectorizableTree[0]->VectorizedValue = Trunc;
7195   }
7196 
7197   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7198                     << " values .\n");
7199 
7200   // Extract all of the elements with the external uses.
7201   for (const auto &ExternalUse : ExternalUses) {
7202     Value *Scalar = ExternalUse.Scalar;
7203     llvm::User *User = ExternalUse.User;
7204 
7205     // Skip users that we already RAUW. This happens when one instruction
7206     // has multiple uses of the same value.
7207     if (User && !is_contained(Scalar->users(), User))
7208       continue;
7209     TreeEntry *E = getTreeEntry(Scalar);
7210     assert(E && "Invalid scalar");
7211     assert(E->State != TreeEntry::NeedToGather &&
7212            "Extracting from a gather list");
7213 
7214     Value *Vec = E->VectorizedValue;
7215     assert(Vec && "Can't find vectorizable value");
7216 
7217     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7218     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7219       if (Scalar->getType() != Vec->getType()) {
7220         Value *Ex;
7221         // "Reuse" the existing extract to improve final codegen.
7222         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7223           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7224                                             ES->getOperand(1));
7225         } else {
7226           Ex = Builder.CreateExtractElement(Vec, Lane);
7227         }
7228         // If necessary, sign-extend or zero-extend ScalarRoot
7229         // to the larger type.
7230         if (!MinBWs.count(ScalarRoot))
7231           return Ex;
7232         if (MinBWs[ScalarRoot].second)
7233           return Builder.CreateSExt(Ex, Scalar->getType());
7234         return Builder.CreateZExt(Ex, Scalar->getType());
7235       }
7236       assert(isa<FixedVectorType>(Scalar->getType()) &&
7237              isa<InsertElementInst>(Scalar) &&
7238              "In-tree scalar of vector type is not insertelement?");
7239       return Vec;
7240     };
7241     // If User == nullptr, the Scalar is used as extra arg. Generate
7242     // ExtractElement instruction and update the record for this scalar in
7243     // ExternallyUsedValues.
7244     if (!User) {
7245       assert(ExternallyUsedValues.count(Scalar) &&
7246              "Scalar with nullptr as an external user must be registered in "
7247              "ExternallyUsedValues map");
7248       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7249         Builder.SetInsertPoint(VecI->getParent(),
7250                                std::next(VecI->getIterator()));
7251       } else {
7252         Builder.SetInsertPoint(&F->getEntryBlock().front());
7253       }
7254       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7255       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7256       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7257       auto It = ExternallyUsedValues.find(Scalar);
7258       assert(It != ExternallyUsedValues.end() &&
7259              "Externally used scalar is not found in ExternallyUsedValues");
7260       NewInstLocs.append(It->second);
7261       ExternallyUsedValues.erase(Scalar);
7262       // Required to update internally referenced instructions.
7263       Scalar->replaceAllUsesWith(NewInst);
7264       continue;
7265     }
7266 
7267     // Generate extracts for out-of-tree users.
7268     // Find the insertion point for the extractelement lane.
7269     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7270       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7271         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7272           if (PH->getIncomingValue(i) == Scalar) {
7273             Instruction *IncomingTerminator =
7274                 PH->getIncomingBlock(i)->getTerminator();
7275             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7276               Builder.SetInsertPoint(VecI->getParent(),
7277                                      std::next(VecI->getIterator()));
7278             } else {
7279               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7280             }
7281             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7282             CSEBlocks.insert(PH->getIncomingBlock(i));
7283             PH->setOperand(i, NewInst);
7284           }
7285         }
7286       } else {
7287         Builder.SetInsertPoint(cast<Instruction>(User));
7288         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7289         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7290         User->replaceUsesOfWith(Scalar, NewInst);
7291       }
7292     } else {
7293       Builder.SetInsertPoint(&F->getEntryBlock().front());
7294       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7295       CSEBlocks.insert(&F->getEntryBlock());
7296       User->replaceUsesOfWith(Scalar, NewInst);
7297     }
7298 
7299     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7300   }
7301 
7302   // For each vectorized value:
7303   for (auto &TEPtr : VectorizableTree) {
7304     TreeEntry *Entry = TEPtr.get();
7305 
7306     // No need to handle users of gathered values.
7307     if (Entry->State == TreeEntry::NeedToGather)
7308       continue;
7309 
7310     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7311 
7312     // For each lane:
7313     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7314       Value *Scalar = Entry->Scalars[Lane];
7315 
7316 #ifndef NDEBUG
7317       Type *Ty = Scalar->getType();
7318       if (!Ty->isVoidTy()) {
7319         for (User *U : Scalar->users()) {
7320           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7321 
7322           // It is legal to delete users in the ignorelist.
7323           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7324                   (isa_and_nonnull<Instruction>(U) &&
7325                    isDeleted(cast<Instruction>(U)))) &&
7326                  "Deleting out-of-tree value");
7327         }
7328       }
7329 #endif
7330       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7331       eraseInstruction(cast<Instruction>(Scalar));
7332     }
7333   }
7334 
7335   Builder.ClearInsertionPoint();
7336   InstrElementSize.clear();
7337 
7338   return VectorizableTree[0]->VectorizedValue;
7339 }
7340 
7341 void BoUpSLP::optimizeGatherSequence() {
7342   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7343                     << " gather sequences instructions.\n");
7344   // LICM InsertElementInst sequences.
7345   for (Instruction *I : GatherShuffleSeq) {
7346     if (isDeleted(I))
7347       continue;
7348 
7349     // Check if this block is inside a loop.
7350     Loop *L = LI->getLoopFor(I->getParent());
7351     if (!L)
7352       continue;
7353 
7354     // Check if it has a preheader.
7355     BasicBlock *PreHeader = L->getLoopPreheader();
7356     if (!PreHeader)
7357       continue;
7358 
7359     // If the vector or the element that we insert into it are
7360     // instructions that are defined in this basic block then we can't
7361     // hoist this instruction.
7362     if (any_of(I->operands(), [L](Value *V) {
7363           auto *OpI = dyn_cast<Instruction>(V);
7364           return OpI && L->contains(OpI);
7365         }))
7366       continue;
7367 
7368     // We can hoist this instruction. Move it to the pre-header.
7369     I->moveBefore(PreHeader->getTerminator());
7370   }
7371 
7372   // Make a list of all reachable blocks in our CSE queue.
7373   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7374   CSEWorkList.reserve(CSEBlocks.size());
7375   for (BasicBlock *BB : CSEBlocks)
7376     if (DomTreeNode *N = DT->getNode(BB)) {
7377       assert(DT->isReachableFromEntry(N));
7378       CSEWorkList.push_back(N);
7379     }
7380 
7381   // Sort blocks by domination. This ensures we visit a block after all blocks
7382   // dominating it are visited.
7383   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7384     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7385            "Different nodes should have different DFS numbers");
7386     return A->getDFSNumIn() < B->getDFSNumIn();
7387   });
7388 
7389   // Less defined shuffles can be replaced by the more defined copies.
7390   // Between two shuffles one is less defined if it has the same vector operands
7391   // and its mask indeces are the same as in the first one or undefs. E.g.
7392   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7393   // poison, <0, 0, 0, 0>.
7394   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7395                                            SmallVectorImpl<int> &NewMask) {
7396     if (I1->getType() != I2->getType())
7397       return false;
7398     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7399     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7400     if (!SI1 || !SI2)
7401       return I1->isIdenticalTo(I2);
7402     if (SI1->isIdenticalTo(SI2))
7403       return true;
7404     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7405       if (SI1->getOperand(I) != SI2->getOperand(I))
7406         return false;
7407     // Check if the second instruction is more defined than the first one.
7408     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7409     ArrayRef<int> SM1 = SI1->getShuffleMask();
7410     // Count trailing undefs in the mask to check the final number of used
7411     // registers.
7412     unsigned LastUndefsCnt = 0;
7413     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7414       if (SM1[I] == UndefMaskElem)
7415         ++LastUndefsCnt;
7416       else
7417         LastUndefsCnt = 0;
7418       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7419           NewMask[I] != SM1[I])
7420         return false;
7421       if (NewMask[I] == UndefMaskElem)
7422         NewMask[I] = SM1[I];
7423     }
7424     // Check if the last undefs actually change the final number of used vector
7425     // registers.
7426     return SM1.size() - LastUndefsCnt > 1 &&
7427            TTI->getNumberOfParts(SI1->getType()) ==
7428                TTI->getNumberOfParts(
7429                    FixedVectorType::get(SI1->getType()->getElementType(),
7430                                         SM1.size() - LastUndefsCnt));
7431   };
7432   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7433   // instructions. TODO: We can further optimize this scan if we split the
7434   // instructions into different buckets based on the insert lane.
7435   SmallVector<Instruction *, 16> Visited;
7436   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7437     assert(*I &&
7438            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7439            "Worklist not sorted properly!");
7440     BasicBlock *BB = (*I)->getBlock();
7441     // For all instructions in blocks containing gather sequences:
7442     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7443       if (isDeleted(&In))
7444         continue;
7445       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7446           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7447         continue;
7448 
7449       // Check if we can replace this instruction with any of the
7450       // visited instructions.
7451       bool Replaced = false;
7452       for (Instruction *&V : Visited) {
7453         SmallVector<int> NewMask;
7454         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7455             DT->dominates(V->getParent(), In.getParent())) {
7456           In.replaceAllUsesWith(V);
7457           eraseInstruction(&In);
7458           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7459             if (!NewMask.empty())
7460               SI->setShuffleMask(NewMask);
7461           Replaced = true;
7462           break;
7463         }
7464         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7465             GatherShuffleSeq.contains(V) &&
7466             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7467             DT->dominates(In.getParent(), V->getParent())) {
7468           In.moveAfter(V);
7469           V->replaceAllUsesWith(&In);
7470           eraseInstruction(V);
7471           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7472             if (!NewMask.empty())
7473               SI->setShuffleMask(NewMask);
7474           V = &In;
7475           Replaced = true;
7476           break;
7477         }
7478       }
7479       if (!Replaced) {
7480         assert(!is_contained(Visited, &In));
7481         Visited.push_back(&In);
7482       }
7483     }
7484   }
7485   CSEBlocks.clear();
7486   GatherShuffleSeq.clear();
7487 }
7488 
7489 BoUpSLP::ScheduleData *
7490 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7491   ScheduleData *Bundle = nullptr;
7492   ScheduleData *PrevInBundle = nullptr;
7493   for (Value *V : VL) {
7494     ScheduleData *BundleMember = getScheduleData(V);
7495     assert(BundleMember &&
7496            "no ScheduleData for bundle member "
7497            "(maybe not in same basic block)");
7498     assert(BundleMember->isSchedulingEntity() &&
7499            "bundle member already part of other bundle");
7500     if (PrevInBundle) {
7501       PrevInBundle->NextInBundle = BundleMember;
7502     } else {
7503       Bundle = BundleMember;
7504     }
7505     BundleMember->UnscheduledDepsInBundle = 0;
7506     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7507 
7508     // Group the instructions to a bundle.
7509     BundleMember->FirstInBundle = Bundle;
7510     PrevInBundle = BundleMember;
7511   }
7512   assert(Bundle && "Failed to find schedule bundle");
7513   return Bundle;
7514 }
7515 
7516 // Groups the instructions to a bundle (which is then a single scheduling entity)
7517 // and schedules instructions until the bundle gets ready.
7518 Optional<BoUpSLP::ScheduleData *>
7519 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7520                                             const InstructionsState &S) {
7521   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7522   // instructions.
7523   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7524     return nullptr;
7525 
7526   // Initialize the instruction bundle.
7527   Instruction *OldScheduleEnd = ScheduleEnd;
7528   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7529 
7530   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7531                                                          ScheduleData *Bundle) {
7532     // The scheduling region got new instructions at the lower end (or it is a
7533     // new region for the first bundle). This makes it necessary to
7534     // recalculate all dependencies.
7535     // It is seldom that this needs to be done a second time after adding the
7536     // initial bundle to the region.
7537     if (ScheduleEnd != OldScheduleEnd) {
7538       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7539         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7540       ReSchedule = true;
7541     }
7542     if (ReSchedule) {
7543       resetSchedule();
7544       initialFillReadyList(ReadyInsts);
7545     }
7546     if (Bundle) {
7547       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7548                         << " in block " << BB->getName() << "\n");
7549       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7550     }
7551 
7552     // Now try to schedule the new bundle or (if no bundle) just calculate
7553     // dependencies. As soon as the bundle is "ready" it means that there are no
7554     // cyclic dependencies and we can schedule it. Note that's important that we
7555     // don't "schedule" the bundle yet (see cancelScheduling).
7556     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7557            !ReadyInsts.empty()) {
7558       ScheduleData *Picked = ReadyInsts.pop_back_val();
7559       if (Picked->isSchedulingEntity() && Picked->isReady())
7560         schedule(Picked, ReadyInsts);
7561     }
7562   };
7563 
7564   // Make sure that the scheduling region contains all
7565   // instructions of the bundle.
7566   for (Value *V : VL) {
7567     if (!extendSchedulingRegion(V, S)) {
7568       // If the scheduling region got new instructions at the lower end (or it
7569       // is a new region for the first bundle). This makes it necessary to
7570       // recalculate all dependencies.
7571       // Otherwise the compiler may crash trying to incorrectly calculate
7572       // dependencies and emit instruction in the wrong order at the actual
7573       // scheduling.
7574       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7575       return None;
7576     }
7577   }
7578 
7579   bool ReSchedule = false;
7580   for (Value *V : VL) {
7581     ScheduleData *BundleMember = getScheduleData(V);
7582     assert(BundleMember &&
7583            "no ScheduleData for bundle member (maybe not in same basic block)");
7584     if (!BundleMember->IsScheduled)
7585       continue;
7586     // A bundle member was scheduled as single instruction before and now
7587     // needs to be scheduled as part of the bundle. We just get rid of the
7588     // existing schedule.
7589     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7590                       << " was already scheduled\n");
7591     ReSchedule = true;
7592   }
7593 
7594   auto *Bundle = buildBundle(VL);
7595   TryScheduleBundleImpl(ReSchedule, Bundle);
7596   if (!Bundle->isReady()) {
7597     cancelScheduling(VL, S.OpValue);
7598     return None;
7599   }
7600   return Bundle;
7601 }
7602 
7603 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7604                                                 Value *OpValue) {
7605   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7606     return;
7607 
7608   ScheduleData *Bundle = getScheduleData(OpValue);
7609   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7610   assert(!Bundle->IsScheduled &&
7611          "Can't cancel bundle which is already scheduled");
7612   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7613          "tried to unbundle something which is not a bundle");
7614 
7615   // Un-bundle: make single instructions out of the bundle.
7616   ScheduleData *BundleMember = Bundle;
7617   while (BundleMember) {
7618     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7619     BundleMember->FirstInBundle = BundleMember;
7620     ScheduleData *Next = BundleMember->NextInBundle;
7621     BundleMember->NextInBundle = nullptr;
7622     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7623     if (BundleMember->UnscheduledDepsInBundle == 0) {
7624       ReadyInsts.insert(BundleMember);
7625     }
7626     BundleMember = Next;
7627   }
7628 }
7629 
7630 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7631   // Allocate a new ScheduleData for the instruction.
7632   if (ChunkPos >= ChunkSize) {
7633     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7634     ChunkPos = 0;
7635   }
7636   return &(ScheduleDataChunks.back()[ChunkPos++]);
7637 }
7638 
7639 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7640                                                       const InstructionsState &S) {
7641   if (getScheduleData(V, isOneOf(S, V)))
7642     return true;
7643   Instruction *I = dyn_cast<Instruction>(V);
7644   assert(I && "bundle member must be an instruction");
7645   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7646          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7647          "be scheduled");
7648   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7649     ScheduleData *ISD = getScheduleData(I);
7650     if (!ISD)
7651       return false;
7652     assert(isInSchedulingRegion(ISD) &&
7653            "ScheduleData not in scheduling region");
7654     ScheduleData *SD = allocateScheduleDataChunks();
7655     SD->Inst = I;
7656     SD->init(SchedulingRegionID, S.OpValue);
7657     ExtraScheduleDataMap[I][S.OpValue] = SD;
7658     return true;
7659   };
7660   if (CheckSheduleForI(I))
7661     return true;
7662   if (!ScheduleStart) {
7663     // It's the first instruction in the new region.
7664     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7665     ScheduleStart = I;
7666     ScheduleEnd = I->getNextNode();
7667     if (isOneOf(S, I) != I)
7668       CheckSheduleForI(I);
7669     assert(ScheduleEnd && "tried to vectorize a terminator?");
7670     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7671     return true;
7672   }
7673   // Search up and down at the same time, because we don't know if the new
7674   // instruction is above or below the existing scheduling region.
7675   BasicBlock::reverse_iterator UpIter =
7676       ++ScheduleStart->getIterator().getReverse();
7677   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7678   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7679   BasicBlock::iterator LowerEnd = BB->end();
7680   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7681          &*DownIter != I) {
7682     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7683       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7684       return false;
7685     }
7686 
7687     ++UpIter;
7688     ++DownIter;
7689   }
7690   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7691     assert(I->getParent() == ScheduleStart->getParent() &&
7692            "Instruction is in wrong basic block.");
7693     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7694     ScheduleStart = I;
7695     if (isOneOf(S, I) != I)
7696       CheckSheduleForI(I);
7697     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7698                       << "\n");
7699     return true;
7700   }
7701   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7702          "Expected to reach top of the basic block or instruction down the "
7703          "lower end.");
7704   assert(I->getParent() == ScheduleEnd->getParent() &&
7705          "Instruction is in wrong basic block.");
7706   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7707                    nullptr);
7708   ScheduleEnd = I->getNextNode();
7709   if (isOneOf(S, I) != I)
7710     CheckSheduleForI(I);
7711   assert(ScheduleEnd && "tried to vectorize a terminator?");
7712   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7713   return true;
7714 }
7715 
7716 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7717                                                 Instruction *ToI,
7718                                                 ScheduleData *PrevLoadStore,
7719                                                 ScheduleData *NextLoadStore) {
7720   ScheduleData *CurrentLoadStore = PrevLoadStore;
7721   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7722     ScheduleData *SD = ScheduleDataMap[I];
7723     if (!SD) {
7724       SD = allocateScheduleDataChunks();
7725       ScheduleDataMap[I] = SD;
7726       SD->Inst = I;
7727     }
7728     assert(!isInSchedulingRegion(SD) &&
7729            "new ScheduleData already in scheduling region");
7730     SD->init(SchedulingRegionID, I);
7731 
7732     if (I->mayReadOrWriteMemory() &&
7733         (!isa<IntrinsicInst>(I) ||
7734          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7735           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7736               Intrinsic::pseudoprobe))) {
7737       // Update the linked list of memory accessing instructions.
7738       if (CurrentLoadStore) {
7739         CurrentLoadStore->NextLoadStore = SD;
7740       } else {
7741         FirstLoadStoreInRegion = SD;
7742       }
7743       CurrentLoadStore = SD;
7744     }
7745   }
7746   if (NextLoadStore) {
7747     if (CurrentLoadStore)
7748       CurrentLoadStore->NextLoadStore = NextLoadStore;
7749   } else {
7750     LastLoadStoreInRegion = CurrentLoadStore;
7751   }
7752 }
7753 
7754 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7755                                                      bool InsertInReadyList,
7756                                                      BoUpSLP *SLP) {
7757   assert(SD->isSchedulingEntity());
7758 
7759   SmallVector<ScheduleData *, 10> WorkList;
7760   WorkList.push_back(SD);
7761 
7762   while (!WorkList.empty()) {
7763     ScheduleData *SD = WorkList.pop_back_val();
7764     for (ScheduleData *BundleMember = SD; BundleMember;
7765          BundleMember = BundleMember->NextInBundle) {
7766       assert(isInSchedulingRegion(BundleMember));
7767       if (BundleMember->hasValidDependencies())
7768         continue;
7769 
7770       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7771                  << "\n");
7772       BundleMember->Dependencies = 0;
7773       BundleMember->resetUnscheduledDeps();
7774 
7775       // Handle def-use chain dependencies.
7776       if (BundleMember->OpValue != BundleMember->Inst) {
7777         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7778         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7779           BundleMember->Dependencies++;
7780           ScheduleData *DestBundle = UseSD->FirstInBundle;
7781           if (!DestBundle->IsScheduled)
7782             BundleMember->incrementUnscheduledDeps(1);
7783           if (!DestBundle->hasValidDependencies())
7784             WorkList.push_back(DestBundle);
7785         }
7786       } else {
7787         for (User *U : BundleMember->Inst->users()) {
7788           assert(isa<Instruction>(U) &&
7789                  "user of instruction must be instruction");
7790           ScheduleData *UseSD = getScheduleData(U);
7791           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7792             BundleMember->Dependencies++;
7793             ScheduleData *DestBundle = UseSD->FirstInBundle;
7794             if (!DestBundle->IsScheduled)
7795               BundleMember->incrementUnscheduledDeps(1);
7796             if (!DestBundle->hasValidDependencies())
7797               WorkList.push_back(DestBundle);
7798           }
7799         }
7800       }
7801 
7802       // Handle the memory dependencies (if any).
7803       ScheduleData *DepDest = BundleMember->NextLoadStore;
7804       if (!DepDest)
7805         continue;
7806       Instruction *SrcInst = BundleMember->Inst;
7807       assert(SrcInst->mayReadOrWriteMemory() &&
7808              "NextLoadStore list for non memory effecting bundle?");
7809       MemoryLocation SrcLoc = getLocation(SrcInst);
7810       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7811       unsigned numAliased = 0;
7812       unsigned DistToSrc = 1;
7813 
7814       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7815         assert(isInSchedulingRegion(DepDest));
7816 
7817         // We have two limits to reduce the complexity:
7818         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7819         //    SLP->isAliased (which is the expensive part in this loop).
7820         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7821         //    the whole loop (even if the loop is fast, it's quadratic).
7822         //    It's important for the loop break condition (see below) to
7823         //    check this limit even between two read-only instructions.
7824         if (DistToSrc >= MaxMemDepDistance ||
7825             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7826              (numAliased >= AliasedCheckLimit ||
7827               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7828 
7829           // We increment the counter only if the locations are aliased
7830           // (instead of counting all alias checks). This gives a better
7831           // balance between reduced runtime and accurate dependencies.
7832           numAliased++;
7833 
7834           DepDest->MemoryDependencies.push_back(BundleMember);
7835           BundleMember->Dependencies++;
7836           ScheduleData *DestBundle = DepDest->FirstInBundle;
7837           if (!DestBundle->IsScheduled) {
7838             BundleMember->incrementUnscheduledDeps(1);
7839           }
7840           if (!DestBundle->hasValidDependencies()) {
7841             WorkList.push_back(DestBundle);
7842           }
7843         }
7844 
7845         // Example, explaining the loop break condition: Let's assume our
7846         // starting instruction is i0 and MaxMemDepDistance = 3.
7847         //
7848         //                      +--------v--v--v
7849         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7850         //             +--------^--^--^
7851         //
7852         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7853         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7854         // Previously we already added dependencies from i3 to i6,i7,i8
7855         // (because of MaxMemDepDistance). As we added a dependency from
7856         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7857         // and we can abort this loop at i6.
7858         if (DistToSrc >= 2 * MaxMemDepDistance)
7859           break;
7860         DistToSrc++;
7861       }
7862     }
7863     if (InsertInReadyList && SD->isReady()) {
7864       ReadyInsts.push_back(SD);
7865       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7866                         << "\n");
7867     }
7868   }
7869 }
7870 
7871 void BoUpSLP::BlockScheduling::resetSchedule() {
7872   assert(ScheduleStart &&
7873          "tried to reset schedule on block which has not been scheduled");
7874   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7875     doForAllOpcodes(I, [&](ScheduleData *SD) {
7876       assert(isInSchedulingRegion(SD) &&
7877              "ScheduleData not in scheduling region");
7878       SD->IsScheduled = false;
7879       SD->resetUnscheduledDeps();
7880     });
7881   }
7882   ReadyInsts.clear();
7883 }
7884 
7885 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7886   if (!BS->ScheduleStart)
7887     return;
7888 
7889   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7890 
7891   BS->resetSchedule();
7892 
7893   // For the real scheduling we use a more sophisticated ready-list: it is
7894   // sorted by the original instruction location. This lets the final schedule
7895   // be as  close as possible to the original instruction order.
7896   struct ScheduleDataCompare {
7897     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7898       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7899     }
7900   };
7901   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7902 
7903   // Ensure that all dependency data is updated and fill the ready-list with
7904   // initial instructions.
7905   int Idx = 0;
7906   int NumToSchedule = 0;
7907   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7908        I = I->getNextNode()) {
7909     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7910       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7911               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7912              "scheduler and vectorizer bundle mismatch");
7913       SD->FirstInBundle->SchedulingPriority = Idx++;
7914       if (SD->isSchedulingEntity()) {
7915         BS->calculateDependencies(SD, false, this);
7916         NumToSchedule++;
7917       }
7918     });
7919   }
7920   BS->initialFillReadyList(ReadyInsts);
7921 
7922   Instruction *LastScheduledInst = BS->ScheduleEnd;
7923 
7924   // Do the "real" scheduling.
7925   while (!ReadyInsts.empty()) {
7926     ScheduleData *picked = *ReadyInsts.begin();
7927     ReadyInsts.erase(ReadyInsts.begin());
7928 
7929     // Move the scheduled instruction(s) to their dedicated places, if not
7930     // there yet.
7931     for (ScheduleData *BundleMember = picked; BundleMember;
7932          BundleMember = BundleMember->NextInBundle) {
7933       Instruction *pickedInst = BundleMember->Inst;
7934       if (pickedInst->getNextNode() != LastScheduledInst)
7935         pickedInst->moveBefore(LastScheduledInst);
7936       LastScheduledInst = pickedInst;
7937     }
7938 
7939     BS->schedule(picked, ReadyInsts);
7940     NumToSchedule--;
7941   }
7942   assert(NumToSchedule == 0 && "could not schedule all instructions");
7943 
7944   // Check that we didn't break any of our invariants.
7945 #ifdef EXPENSIVE_CHECKS
7946   BS->verify();
7947 #endif
7948 
7949   // Avoid duplicate scheduling of the block.
7950   BS->ScheduleStart = nullptr;
7951 }
7952 
7953 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7954   // If V is a store, just return the width of the stored value (or value
7955   // truncated just before storing) without traversing the expression tree.
7956   // This is the common case.
7957   if (auto *Store = dyn_cast<StoreInst>(V)) {
7958     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7959       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7960     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7961   }
7962 
7963   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7964     return getVectorElementSize(IEI->getOperand(1));
7965 
7966   auto E = InstrElementSize.find(V);
7967   if (E != InstrElementSize.end())
7968     return E->second;
7969 
7970   // If V is not a store, we can traverse the expression tree to find loads
7971   // that feed it. The type of the loaded value may indicate a more suitable
7972   // width than V's type. We want to base the vector element size on the width
7973   // of memory operations where possible.
7974   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7975   SmallPtrSet<Instruction *, 16> Visited;
7976   if (auto *I = dyn_cast<Instruction>(V)) {
7977     Worklist.emplace_back(I, I->getParent());
7978     Visited.insert(I);
7979   }
7980 
7981   // Traverse the expression tree in bottom-up order looking for loads. If we
7982   // encounter an instruction we don't yet handle, we give up.
7983   auto Width = 0u;
7984   while (!Worklist.empty()) {
7985     Instruction *I;
7986     BasicBlock *Parent;
7987     std::tie(I, Parent) = Worklist.pop_back_val();
7988 
7989     // We should only be looking at scalar instructions here. If the current
7990     // instruction has a vector type, skip.
7991     auto *Ty = I->getType();
7992     if (isa<VectorType>(Ty))
7993       continue;
7994 
7995     // If the current instruction is a load, update MaxWidth to reflect the
7996     // width of the loaded value.
7997     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7998         isa<ExtractValueInst>(I))
7999       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8000 
8001     // Otherwise, we need to visit the operands of the instruction. We only
8002     // handle the interesting cases from buildTree here. If an operand is an
8003     // instruction we haven't yet visited and from the same basic block as the
8004     // user or the use is a PHI node, we add it to the worklist.
8005     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8006              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8007              isa<UnaryOperator>(I)) {
8008       for (Use &U : I->operands())
8009         if (auto *J = dyn_cast<Instruction>(U.get()))
8010           if (Visited.insert(J).second &&
8011               (isa<PHINode>(I) || J->getParent() == Parent))
8012             Worklist.emplace_back(J, J->getParent());
8013     } else {
8014       break;
8015     }
8016   }
8017 
8018   // If we didn't encounter a memory access in the expression tree, or if we
8019   // gave up for some reason, just return the width of V. Otherwise, return the
8020   // maximum width we found.
8021   if (!Width) {
8022     if (auto *CI = dyn_cast<CmpInst>(V))
8023       V = CI->getOperand(0);
8024     Width = DL->getTypeSizeInBits(V->getType());
8025   }
8026 
8027   for (Instruction *I : Visited)
8028     InstrElementSize[I] = Width;
8029 
8030   return Width;
8031 }
8032 
8033 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8034 // smaller type with a truncation. We collect the values that will be demoted
8035 // in ToDemote and additional roots that require investigating in Roots.
8036 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8037                                   SmallVectorImpl<Value *> &ToDemote,
8038                                   SmallVectorImpl<Value *> &Roots) {
8039   // We can always demote constants.
8040   if (isa<Constant>(V)) {
8041     ToDemote.push_back(V);
8042     return true;
8043   }
8044 
8045   // If the value is not an instruction in the expression with only one use, it
8046   // cannot be demoted.
8047   auto *I = dyn_cast<Instruction>(V);
8048   if (!I || !I->hasOneUse() || !Expr.count(I))
8049     return false;
8050 
8051   switch (I->getOpcode()) {
8052 
8053   // We can always demote truncations and extensions. Since truncations can
8054   // seed additional demotion, we save the truncated value.
8055   case Instruction::Trunc:
8056     Roots.push_back(I->getOperand(0));
8057     break;
8058   case Instruction::ZExt:
8059   case Instruction::SExt:
8060     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8061         isa<InsertElementInst>(I->getOperand(0)))
8062       return false;
8063     break;
8064 
8065   // We can demote certain binary operations if we can demote both of their
8066   // operands.
8067   case Instruction::Add:
8068   case Instruction::Sub:
8069   case Instruction::Mul:
8070   case Instruction::And:
8071   case Instruction::Or:
8072   case Instruction::Xor:
8073     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8074         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8075       return false;
8076     break;
8077 
8078   // We can demote selects if we can demote their true and false values.
8079   case Instruction::Select: {
8080     SelectInst *SI = cast<SelectInst>(I);
8081     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8082         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8083       return false;
8084     break;
8085   }
8086 
8087   // We can demote phis if we can demote all their incoming operands. Note that
8088   // we don't need to worry about cycles since we ensure single use above.
8089   case Instruction::PHI: {
8090     PHINode *PN = cast<PHINode>(I);
8091     for (Value *IncValue : PN->incoming_values())
8092       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8093         return false;
8094     break;
8095   }
8096 
8097   // Otherwise, conservatively give up.
8098   default:
8099     return false;
8100   }
8101 
8102   // Record the value that we can demote.
8103   ToDemote.push_back(V);
8104   return true;
8105 }
8106 
8107 void BoUpSLP::computeMinimumValueSizes() {
8108   // If there are no external uses, the expression tree must be rooted by a
8109   // store. We can't demote in-memory values, so there is nothing to do here.
8110   if (ExternalUses.empty())
8111     return;
8112 
8113   // We only attempt to truncate integer expressions.
8114   auto &TreeRoot = VectorizableTree[0]->Scalars;
8115   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8116   if (!TreeRootIT)
8117     return;
8118 
8119   // If the expression is not rooted by a store, these roots should have
8120   // external uses. We will rely on InstCombine to rewrite the expression in
8121   // the narrower type. However, InstCombine only rewrites single-use values.
8122   // This means that if a tree entry other than a root is used externally, it
8123   // must have multiple uses and InstCombine will not rewrite it. The code
8124   // below ensures that only the roots are used externally.
8125   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8126   for (auto &EU : ExternalUses)
8127     if (!Expr.erase(EU.Scalar))
8128       return;
8129   if (!Expr.empty())
8130     return;
8131 
8132   // Collect the scalar values of the vectorizable expression. We will use this
8133   // context to determine which values can be demoted. If we see a truncation,
8134   // we mark it as seeding another demotion.
8135   for (auto &EntryPtr : VectorizableTree)
8136     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8137 
8138   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8139   // have a single external user that is not in the vectorizable tree.
8140   for (auto *Root : TreeRoot)
8141     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8142       return;
8143 
8144   // Conservatively determine if we can actually truncate the roots of the
8145   // expression. Collect the values that can be demoted in ToDemote and
8146   // additional roots that require investigating in Roots.
8147   SmallVector<Value *, 32> ToDemote;
8148   SmallVector<Value *, 4> Roots;
8149   for (auto *Root : TreeRoot)
8150     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8151       return;
8152 
8153   // The maximum bit width required to represent all the values that can be
8154   // demoted without loss of precision. It would be safe to truncate the roots
8155   // of the expression to this width.
8156   auto MaxBitWidth = 8u;
8157 
8158   // We first check if all the bits of the roots are demanded. If they're not,
8159   // we can truncate the roots to this narrower type.
8160   for (auto *Root : TreeRoot) {
8161     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8162     MaxBitWidth = std::max<unsigned>(
8163         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8164   }
8165 
8166   // True if the roots can be zero-extended back to their original type, rather
8167   // than sign-extended. We know that if the leading bits are not demanded, we
8168   // can safely zero-extend. So we initialize IsKnownPositive to True.
8169   bool IsKnownPositive = true;
8170 
8171   // If all the bits of the roots are demanded, we can try a little harder to
8172   // compute a narrower type. This can happen, for example, if the roots are
8173   // getelementptr indices. InstCombine promotes these indices to the pointer
8174   // width. Thus, all their bits are technically demanded even though the
8175   // address computation might be vectorized in a smaller type.
8176   //
8177   // We start by looking at each entry that can be demoted. We compute the
8178   // maximum bit width required to store the scalar by using ValueTracking to
8179   // compute the number of high-order bits we can truncate.
8180   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8181       llvm::all_of(TreeRoot, [](Value *R) {
8182         assert(R->hasOneUse() && "Root should have only one use!");
8183         return isa<GetElementPtrInst>(R->user_back());
8184       })) {
8185     MaxBitWidth = 8u;
8186 
8187     // Determine if the sign bit of all the roots is known to be zero. If not,
8188     // IsKnownPositive is set to False.
8189     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8190       KnownBits Known = computeKnownBits(R, *DL);
8191       return Known.isNonNegative();
8192     });
8193 
8194     // Determine the maximum number of bits required to store the scalar
8195     // values.
8196     for (auto *Scalar : ToDemote) {
8197       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8198       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8199       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8200     }
8201 
8202     // If we can't prove that the sign bit is zero, we must add one to the
8203     // maximum bit width to account for the unknown sign bit. This preserves
8204     // the existing sign bit so we can safely sign-extend the root back to the
8205     // original type. Otherwise, if we know the sign bit is zero, we will
8206     // zero-extend the root instead.
8207     //
8208     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8209     //        one to the maximum bit width will yield a larger-than-necessary
8210     //        type. In general, we need to add an extra bit only if we can't
8211     //        prove that the upper bit of the original type is equal to the
8212     //        upper bit of the proposed smaller type. If these two bits are the
8213     //        same (either zero or one) we know that sign-extending from the
8214     //        smaller type will result in the same value. Here, since we can't
8215     //        yet prove this, we are just making the proposed smaller type
8216     //        larger to ensure correctness.
8217     if (!IsKnownPositive)
8218       ++MaxBitWidth;
8219   }
8220 
8221   // Round MaxBitWidth up to the next power-of-two.
8222   if (!isPowerOf2_64(MaxBitWidth))
8223     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8224 
8225   // If the maximum bit width we compute is less than the with of the roots'
8226   // type, we can proceed with the narrowing. Otherwise, do nothing.
8227   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8228     return;
8229 
8230   // If we can truncate the root, we must collect additional values that might
8231   // be demoted as a result. That is, those seeded by truncations we will
8232   // modify.
8233   while (!Roots.empty())
8234     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8235 
8236   // Finally, map the values we can demote to the maximum bit with we computed.
8237   for (auto *Scalar : ToDemote)
8238     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8239 }
8240 
8241 namespace {
8242 
8243 /// The SLPVectorizer Pass.
8244 struct SLPVectorizer : public FunctionPass {
8245   SLPVectorizerPass Impl;
8246 
8247   /// Pass identification, replacement for typeid
8248   static char ID;
8249 
8250   explicit SLPVectorizer() : FunctionPass(ID) {
8251     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8252   }
8253 
8254   bool doInitialization(Module &M) override { return false; }
8255 
8256   bool runOnFunction(Function &F) override {
8257     if (skipFunction(F))
8258       return false;
8259 
8260     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8261     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8262     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8263     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8264     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8265     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8266     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8267     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8268     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8269     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8270 
8271     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8272   }
8273 
8274   void getAnalysisUsage(AnalysisUsage &AU) const override {
8275     FunctionPass::getAnalysisUsage(AU);
8276     AU.addRequired<AssumptionCacheTracker>();
8277     AU.addRequired<ScalarEvolutionWrapperPass>();
8278     AU.addRequired<AAResultsWrapperPass>();
8279     AU.addRequired<TargetTransformInfoWrapperPass>();
8280     AU.addRequired<LoopInfoWrapperPass>();
8281     AU.addRequired<DominatorTreeWrapperPass>();
8282     AU.addRequired<DemandedBitsWrapperPass>();
8283     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8284     AU.addRequired<InjectTLIMappingsLegacy>();
8285     AU.addPreserved<LoopInfoWrapperPass>();
8286     AU.addPreserved<DominatorTreeWrapperPass>();
8287     AU.addPreserved<AAResultsWrapperPass>();
8288     AU.addPreserved<GlobalsAAWrapperPass>();
8289     AU.setPreservesCFG();
8290   }
8291 };
8292 
8293 } // end anonymous namespace
8294 
8295 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8296   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8297   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8298   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8299   auto *AA = &AM.getResult<AAManager>(F);
8300   auto *LI = &AM.getResult<LoopAnalysis>(F);
8301   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8302   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8303   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8304   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8305 
8306   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8307   if (!Changed)
8308     return PreservedAnalyses::all();
8309 
8310   PreservedAnalyses PA;
8311   PA.preserveSet<CFGAnalyses>();
8312   return PA;
8313 }
8314 
8315 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8316                                 TargetTransformInfo *TTI_,
8317                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8318                                 LoopInfo *LI_, DominatorTree *DT_,
8319                                 AssumptionCache *AC_, DemandedBits *DB_,
8320                                 OptimizationRemarkEmitter *ORE_) {
8321   if (!RunSLPVectorization)
8322     return false;
8323   SE = SE_;
8324   TTI = TTI_;
8325   TLI = TLI_;
8326   AA = AA_;
8327   LI = LI_;
8328   DT = DT_;
8329   AC = AC_;
8330   DB = DB_;
8331   DL = &F.getParent()->getDataLayout();
8332 
8333   Stores.clear();
8334   GEPs.clear();
8335   bool Changed = false;
8336 
8337   // If the target claims to have no vector registers don't attempt
8338   // vectorization.
8339   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8340     LLVM_DEBUG(
8341         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8342     return false;
8343   }
8344 
8345   // Don't vectorize when the attribute NoImplicitFloat is used.
8346   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8347     return false;
8348 
8349   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8350 
8351   // Use the bottom up slp vectorizer to construct chains that start with
8352   // store instructions.
8353   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8354 
8355   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8356   // delete instructions.
8357 
8358   // Update DFS numbers now so that we can use them for ordering.
8359   DT->updateDFSNumbers();
8360 
8361   // Scan the blocks in the function in post order.
8362   for (auto BB : post_order(&F.getEntryBlock())) {
8363     collectSeedInstructions(BB);
8364 
8365     // Vectorize trees that end at stores.
8366     if (!Stores.empty()) {
8367       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8368                         << " underlying objects.\n");
8369       Changed |= vectorizeStoreChains(R);
8370     }
8371 
8372     // Vectorize trees that end at reductions.
8373     Changed |= vectorizeChainsInBlock(BB, R);
8374 
8375     // Vectorize the index computations of getelementptr instructions. This
8376     // is primarily intended to catch gather-like idioms ending at
8377     // non-consecutive loads.
8378     if (!GEPs.empty()) {
8379       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8380                         << " underlying objects.\n");
8381       Changed |= vectorizeGEPIndices(BB, R);
8382     }
8383   }
8384 
8385   if (Changed) {
8386     R.optimizeGatherSequence();
8387     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8388   }
8389   return Changed;
8390 }
8391 
8392 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8393                                             unsigned Idx) {
8394   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8395                     << "\n");
8396   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8397   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8398   unsigned VF = Chain.size();
8399 
8400   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8401     return false;
8402 
8403   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8404                     << "\n");
8405 
8406   R.buildTree(Chain);
8407   if (R.isTreeTinyAndNotFullyVectorizable())
8408     return false;
8409   if (R.isLoadCombineCandidate())
8410     return false;
8411   R.reorderTopToBottom();
8412   R.reorderBottomToTop();
8413   R.buildExternalUses();
8414 
8415   R.computeMinimumValueSizes();
8416 
8417   InstructionCost Cost = R.getTreeCost();
8418 
8419   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8420   if (Cost < -SLPCostThreshold) {
8421     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8422 
8423     using namespace ore;
8424 
8425     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8426                                         cast<StoreInst>(Chain[0]))
8427                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8428                      << " and with tree size "
8429                      << NV("TreeSize", R.getTreeSize()));
8430 
8431     R.vectorizeTree();
8432     return true;
8433   }
8434 
8435   return false;
8436 }
8437 
8438 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8439                                         BoUpSLP &R) {
8440   // We may run into multiple chains that merge into a single chain. We mark the
8441   // stores that we vectorized so that we don't visit the same store twice.
8442   BoUpSLP::ValueSet VectorizedStores;
8443   bool Changed = false;
8444 
8445   int E = Stores.size();
8446   SmallBitVector Tails(E, false);
8447   int MaxIter = MaxStoreLookup.getValue();
8448   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8449       E, std::make_pair(E, INT_MAX));
8450   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8451   int IterCnt;
8452   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8453                                   &CheckedPairs,
8454                                   &ConsecutiveChain](int K, int Idx) {
8455     if (IterCnt >= MaxIter)
8456       return true;
8457     if (CheckedPairs[Idx].test(K))
8458       return ConsecutiveChain[K].second == 1 &&
8459              ConsecutiveChain[K].first == Idx;
8460     ++IterCnt;
8461     CheckedPairs[Idx].set(K);
8462     CheckedPairs[K].set(Idx);
8463     Optional<int> Diff = getPointersDiff(
8464         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8465         Stores[Idx]->getValueOperand()->getType(),
8466         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8467     if (!Diff || *Diff == 0)
8468       return false;
8469     int Val = *Diff;
8470     if (Val < 0) {
8471       if (ConsecutiveChain[Idx].second > -Val) {
8472         Tails.set(K);
8473         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8474       }
8475       return false;
8476     }
8477     if (ConsecutiveChain[K].second <= Val)
8478       return false;
8479 
8480     Tails.set(Idx);
8481     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8482     return Val == 1;
8483   };
8484   // Do a quadratic search on all of the given stores in reverse order and find
8485   // all of the pairs of stores that follow each other.
8486   for (int Idx = E - 1; Idx >= 0; --Idx) {
8487     // If a store has multiple consecutive store candidates, search according
8488     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8489     // This is because usually pairing with immediate succeeding or preceding
8490     // candidate create the best chance to find slp vectorization opportunity.
8491     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8492     IterCnt = 0;
8493     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8494       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8495           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8496         break;
8497   }
8498 
8499   // Tracks if we tried to vectorize stores starting from the given tail
8500   // already.
8501   SmallBitVector TriedTails(E, false);
8502   // For stores that start but don't end a link in the chain:
8503   for (int Cnt = E; Cnt > 0; --Cnt) {
8504     int I = Cnt - 1;
8505     if (ConsecutiveChain[I].first == E || Tails.test(I))
8506       continue;
8507     // We found a store instr that starts a chain. Now follow the chain and try
8508     // to vectorize it.
8509     BoUpSLP::ValueList Operands;
8510     // Collect the chain into a list.
8511     while (I != E && !VectorizedStores.count(Stores[I])) {
8512       Operands.push_back(Stores[I]);
8513       Tails.set(I);
8514       if (ConsecutiveChain[I].second != 1) {
8515         // Mark the new end in the chain and go back, if required. It might be
8516         // required if the original stores come in reversed order, for example.
8517         if (ConsecutiveChain[I].first != E &&
8518             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8519             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8520           TriedTails.set(I);
8521           Tails.reset(ConsecutiveChain[I].first);
8522           if (Cnt < ConsecutiveChain[I].first + 2)
8523             Cnt = ConsecutiveChain[I].first + 2;
8524         }
8525         break;
8526       }
8527       // Move to the next value in the chain.
8528       I = ConsecutiveChain[I].first;
8529     }
8530     assert(!Operands.empty() && "Expected non-empty list of stores.");
8531 
8532     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8533     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8534     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8535 
8536     unsigned MinVF = R.getMinVF(EltSize);
8537     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8538                               MaxElts);
8539 
8540     // FIXME: Is division-by-2 the correct step? Should we assert that the
8541     // register size is a power-of-2?
8542     unsigned StartIdx = 0;
8543     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8544       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8545         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8546         if (!VectorizedStores.count(Slice.front()) &&
8547             !VectorizedStores.count(Slice.back()) &&
8548             vectorizeStoreChain(Slice, R, Cnt)) {
8549           // Mark the vectorized stores so that we don't vectorize them again.
8550           VectorizedStores.insert(Slice.begin(), Slice.end());
8551           Changed = true;
8552           // If we vectorized initial block, no need to try to vectorize it
8553           // again.
8554           if (Cnt == StartIdx)
8555             StartIdx += Size;
8556           Cnt += Size;
8557           continue;
8558         }
8559         ++Cnt;
8560       }
8561       // Check if the whole array was vectorized already - exit.
8562       if (StartIdx >= Operands.size())
8563         break;
8564     }
8565   }
8566 
8567   return Changed;
8568 }
8569 
8570 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8571   // Initialize the collections. We will make a single pass over the block.
8572   Stores.clear();
8573   GEPs.clear();
8574 
8575   // Visit the store and getelementptr instructions in BB and organize them in
8576   // Stores and GEPs according to the underlying objects of their pointer
8577   // operands.
8578   for (Instruction &I : *BB) {
8579     // Ignore store instructions that are volatile or have a pointer operand
8580     // that doesn't point to a scalar type.
8581     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8582       if (!SI->isSimple())
8583         continue;
8584       if (!isValidElementType(SI->getValueOperand()->getType()))
8585         continue;
8586       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8587     }
8588 
8589     // Ignore getelementptr instructions that have more than one index, a
8590     // constant index, or a pointer operand that doesn't point to a scalar
8591     // type.
8592     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8593       auto Idx = GEP->idx_begin()->get();
8594       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8595         continue;
8596       if (!isValidElementType(Idx->getType()))
8597         continue;
8598       if (GEP->getType()->isVectorTy())
8599         continue;
8600       GEPs[GEP->getPointerOperand()].push_back(GEP);
8601     }
8602   }
8603 }
8604 
8605 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8606   if (!A || !B)
8607     return false;
8608   Value *VL[] = {A, B};
8609   return tryToVectorizeList(VL, R);
8610 }
8611 
8612 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8613                                            bool LimitForRegisterSize) {
8614   if (VL.size() < 2)
8615     return false;
8616 
8617   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8618                     << VL.size() << ".\n");
8619 
8620   // Check that all of the parts are instructions of the same type,
8621   // we permit an alternate opcode via InstructionsState.
8622   InstructionsState S = getSameOpcode(VL);
8623   if (!S.getOpcode())
8624     return false;
8625 
8626   Instruction *I0 = cast<Instruction>(S.OpValue);
8627   // Make sure invalid types (including vector type) are rejected before
8628   // determining vectorization factor for scalar instructions.
8629   for (Value *V : VL) {
8630     Type *Ty = V->getType();
8631     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8632       // NOTE: the following will give user internal llvm type name, which may
8633       // not be useful.
8634       R.getORE()->emit([&]() {
8635         std::string type_str;
8636         llvm::raw_string_ostream rso(type_str);
8637         Ty->print(rso);
8638         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8639                << "Cannot SLP vectorize list: type "
8640                << rso.str() + " is unsupported by vectorizer";
8641       });
8642       return false;
8643     }
8644   }
8645 
8646   unsigned Sz = R.getVectorElementSize(I0);
8647   unsigned MinVF = R.getMinVF(Sz);
8648   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8649   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8650   if (MaxVF < 2) {
8651     R.getORE()->emit([&]() {
8652       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8653              << "Cannot SLP vectorize list: vectorization factor "
8654              << "less than 2 is not supported";
8655     });
8656     return false;
8657   }
8658 
8659   bool Changed = false;
8660   bool CandidateFound = false;
8661   InstructionCost MinCost = SLPCostThreshold.getValue();
8662   Type *ScalarTy = VL[0]->getType();
8663   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8664     ScalarTy = IE->getOperand(1)->getType();
8665 
8666   unsigned NextInst = 0, MaxInst = VL.size();
8667   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8668     // No actual vectorization should happen, if number of parts is the same as
8669     // provided vectorization factor (i.e. the scalar type is used for vector
8670     // code during codegen).
8671     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8672     if (TTI->getNumberOfParts(VecTy) == VF)
8673       continue;
8674     for (unsigned I = NextInst; I < MaxInst; ++I) {
8675       unsigned OpsWidth = 0;
8676 
8677       if (I + VF > MaxInst)
8678         OpsWidth = MaxInst - I;
8679       else
8680         OpsWidth = VF;
8681 
8682       if (!isPowerOf2_32(OpsWidth))
8683         continue;
8684 
8685       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8686           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8687         break;
8688 
8689       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8690       // Check that a previous iteration of this loop did not delete the Value.
8691       if (llvm::any_of(Ops, [&R](Value *V) {
8692             auto *I = dyn_cast<Instruction>(V);
8693             return I && R.isDeleted(I);
8694           }))
8695         continue;
8696 
8697       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8698                         << "\n");
8699 
8700       R.buildTree(Ops);
8701       if (R.isTreeTinyAndNotFullyVectorizable())
8702         continue;
8703       R.reorderTopToBottom();
8704       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8705       R.buildExternalUses();
8706 
8707       R.computeMinimumValueSizes();
8708       InstructionCost Cost = R.getTreeCost();
8709       CandidateFound = true;
8710       MinCost = std::min(MinCost, Cost);
8711 
8712       if (Cost < -SLPCostThreshold) {
8713         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8714         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8715                                                     cast<Instruction>(Ops[0]))
8716                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8717                                  << " and with tree size "
8718                                  << ore::NV("TreeSize", R.getTreeSize()));
8719 
8720         R.vectorizeTree();
8721         // Move to the next bundle.
8722         I += VF - 1;
8723         NextInst = I + 1;
8724         Changed = true;
8725       }
8726     }
8727   }
8728 
8729   if (!Changed && CandidateFound) {
8730     R.getORE()->emit([&]() {
8731       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8732              << "List vectorization was possible but not beneficial with cost "
8733              << ore::NV("Cost", MinCost) << " >= "
8734              << ore::NV("Treshold", -SLPCostThreshold);
8735     });
8736   } else if (!Changed) {
8737     R.getORE()->emit([&]() {
8738       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8739              << "Cannot SLP vectorize list: vectorization was impossible"
8740              << " with available vectorization factors";
8741     });
8742   }
8743   return Changed;
8744 }
8745 
8746 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8747   if (!I)
8748     return false;
8749 
8750   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8751     return false;
8752 
8753   Value *P = I->getParent();
8754 
8755   // Vectorize in current basic block only.
8756   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8757   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8758   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8759     return false;
8760 
8761   // Try to vectorize V.
8762   if (tryToVectorizePair(Op0, Op1, R))
8763     return true;
8764 
8765   auto *A = dyn_cast<BinaryOperator>(Op0);
8766   auto *B = dyn_cast<BinaryOperator>(Op1);
8767   // Try to skip B.
8768   if (B && B->hasOneUse()) {
8769     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8770     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8771     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8772       return true;
8773     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8774       return true;
8775   }
8776 
8777   // Try to skip A.
8778   if (A && A->hasOneUse()) {
8779     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8780     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8781     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8782       return true;
8783     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8784       return true;
8785   }
8786   return false;
8787 }
8788 
8789 namespace {
8790 
8791 /// Model horizontal reductions.
8792 ///
8793 /// A horizontal reduction is a tree of reduction instructions that has values
8794 /// that can be put into a vector as its leaves. For example:
8795 ///
8796 /// mul mul mul mul
8797 ///  \  /    \  /
8798 ///   +       +
8799 ///    \     /
8800 ///       +
8801 /// This tree has "mul" as its leaf values and "+" as its reduction
8802 /// instructions. A reduction can feed into a store or a binary operation
8803 /// feeding a phi.
8804 ///    ...
8805 ///    \  /
8806 ///     +
8807 ///     |
8808 ///  phi +=
8809 ///
8810 ///  Or:
8811 ///    ...
8812 ///    \  /
8813 ///     +
8814 ///     |
8815 ///   *p =
8816 ///
8817 class HorizontalReduction {
8818   using ReductionOpsType = SmallVector<Value *, 16>;
8819   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8820   ReductionOpsListType ReductionOps;
8821   SmallVector<Value *, 32> ReducedVals;
8822   // Use map vector to make stable output.
8823   MapVector<Instruction *, Value *> ExtraArgs;
8824   WeakTrackingVH ReductionRoot;
8825   /// The type of reduction operation.
8826   RecurKind RdxKind;
8827 
8828   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8829 
8830   static bool isCmpSelMinMax(Instruction *I) {
8831     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8832            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8833   }
8834 
8835   // And/or are potentially poison-safe logical patterns like:
8836   // select x, y, false
8837   // select x, true, y
8838   static bool isBoolLogicOp(Instruction *I) {
8839     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8840            match(I, m_LogicalOr(m_Value(), m_Value()));
8841   }
8842 
8843   /// Checks if instruction is associative and can be vectorized.
8844   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8845     if (Kind == RecurKind::None)
8846       return false;
8847 
8848     // Integer ops that map to select instructions or intrinsics are fine.
8849     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8850         isBoolLogicOp(I))
8851       return true;
8852 
8853     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8854       // FP min/max are associative except for NaN and -0.0. We do not
8855       // have to rule out -0.0 here because the intrinsic semantics do not
8856       // specify a fixed result for it.
8857       return I->getFastMathFlags().noNaNs();
8858     }
8859 
8860     return I->isAssociative();
8861   }
8862 
8863   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8864     // Poison-safe 'or' takes the form: select X, true, Y
8865     // To make that work with the normal operand processing, we skip the
8866     // true value operand.
8867     // TODO: Change the code and data structures to handle this without a hack.
8868     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8869       return I->getOperand(2);
8870     return I->getOperand(Index);
8871   }
8872 
8873   /// Checks if the ParentStackElem.first should be marked as a reduction
8874   /// operation with an extra argument or as extra argument itself.
8875   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8876                     Value *ExtraArg) {
8877     if (ExtraArgs.count(ParentStackElem.first)) {
8878       ExtraArgs[ParentStackElem.first] = nullptr;
8879       // We ran into something like:
8880       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8881       // The whole ParentStackElem.first should be considered as an extra value
8882       // in this case.
8883       // Do not perform analysis of remaining operands of ParentStackElem.first
8884       // instruction, this whole instruction is an extra argument.
8885       ParentStackElem.second = INVALID_OPERAND_INDEX;
8886     } else {
8887       // We ran into something like:
8888       // ParentStackElem.first += ... + ExtraArg + ...
8889       ExtraArgs[ParentStackElem.first] = ExtraArg;
8890     }
8891   }
8892 
8893   /// Creates reduction operation with the current opcode.
8894   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8895                          Value *RHS, const Twine &Name, bool UseSelect) {
8896     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8897     switch (Kind) {
8898     case RecurKind::Or:
8899       if (UseSelect &&
8900           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8901         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8902       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8903                                  Name);
8904     case RecurKind::And:
8905       if (UseSelect &&
8906           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8907         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8908       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8909                                  Name);
8910     case RecurKind::Add:
8911     case RecurKind::Mul:
8912     case RecurKind::Xor:
8913     case RecurKind::FAdd:
8914     case RecurKind::FMul:
8915       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8916                                  Name);
8917     case RecurKind::FMax:
8918       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8919     case RecurKind::FMin:
8920       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8921     case RecurKind::SMax:
8922       if (UseSelect) {
8923         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8924         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8925       }
8926       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8927     case RecurKind::SMin:
8928       if (UseSelect) {
8929         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8930         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8931       }
8932       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8933     case RecurKind::UMax:
8934       if (UseSelect) {
8935         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8936         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8937       }
8938       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8939     case RecurKind::UMin:
8940       if (UseSelect) {
8941         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8942         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8943       }
8944       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8945     default:
8946       llvm_unreachable("Unknown reduction operation.");
8947     }
8948   }
8949 
8950   /// Creates reduction operation with the current opcode with the IR flags
8951   /// from \p ReductionOps.
8952   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8953                          Value *RHS, const Twine &Name,
8954                          const ReductionOpsListType &ReductionOps) {
8955     bool UseSelect = ReductionOps.size() == 2 ||
8956                      // Logical or/and.
8957                      (ReductionOps.size() == 1 &&
8958                       isa<SelectInst>(ReductionOps.front().front()));
8959     assert((!UseSelect || ReductionOps.size() != 2 ||
8960             isa<SelectInst>(ReductionOps[1][0])) &&
8961            "Expected cmp + select pairs for reduction");
8962     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8963     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8964       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8965         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8966         propagateIRFlags(Op, ReductionOps[1]);
8967         return Op;
8968       }
8969     }
8970     propagateIRFlags(Op, ReductionOps[0]);
8971     return Op;
8972   }
8973 
8974   /// Creates reduction operation with the current opcode with the IR flags
8975   /// from \p I.
8976   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8977                          Value *RHS, const Twine &Name, Instruction *I) {
8978     auto *SelI = dyn_cast<SelectInst>(I);
8979     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8980     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8981       if (auto *Sel = dyn_cast<SelectInst>(Op))
8982         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8983     }
8984     propagateIRFlags(Op, I);
8985     return Op;
8986   }
8987 
8988   static RecurKind getRdxKind(Instruction *I) {
8989     assert(I && "Expected instruction for reduction matching");
8990     if (match(I, m_Add(m_Value(), m_Value())))
8991       return RecurKind::Add;
8992     if (match(I, m_Mul(m_Value(), m_Value())))
8993       return RecurKind::Mul;
8994     if (match(I, m_And(m_Value(), m_Value())) ||
8995         match(I, m_LogicalAnd(m_Value(), m_Value())))
8996       return RecurKind::And;
8997     if (match(I, m_Or(m_Value(), m_Value())) ||
8998         match(I, m_LogicalOr(m_Value(), m_Value())))
8999       return RecurKind::Or;
9000     if (match(I, m_Xor(m_Value(), m_Value())))
9001       return RecurKind::Xor;
9002     if (match(I, m_FAdd(m_Value(), m_Value())))
9003       return RecurKind::FAdd;
9004     if (match(I, m_FMul(m_Value(), m_Value())))
9005       return RecurKind::FMul;
9006 
9007     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9008       return RecurKind::FMax;
9009     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9010       return RecurKind::FMin;
9011 
9012     // This matches either cmp+select or intrinsics. SLP is expected to handle
9013     // either form.
9014     // TODO: If we are canonicalizing to intrinsics, we can remove several
9015     //       special-case paths that deal with selects.
9016     if (match(I, m_SMax(m_Value(), m_Value())))
9017       return RecurKind::SMax;
9018     if (match(I, m_SMin(m_Value(), m_Value())))
9019       return RecurKind::SMin;
9020     if (match(I, m_UMax(m_Value(), m_Value())))
9021       return RecurKind::UMax;
9022     if (match(I, m_UMin(m_Value(), m_Value())))
9023       return RecurKind::UMin;
9024 
9025     if (auto *Select = dyn_cast<SelectInst>(I)) {
9026       // Try harder: look for min/max pattern based on instructions producing
9027       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9028       // During the intermediate stages of SLP, it's very common to have
9029       // pattern like this (since optimizeGatherSequence is run only once
9030       // at the end):
9031       // %1 = extractelement <2 x i32> %a, i32 0
9032       // %2 = extractelement <2 x i32> %a, i32 1
9033       // %cond = icmp sgt i32 %1, %2
9034       // %3 = extractelement <2 x i32> %a, i32 0
9035       // %4 = extractelement <2 x i32> %a, i32 1
9036       // %select = select i1 %cond, i32 %3, i32 %4
9037       CmpInst::Predicate Pred;
9038       Instruction *L1;
9039       Instruction *L2;
9040 
9041       Value *LHS = Select->getTrueValue();
9042       Value *RHS = Select->getFalseValue();
9043       Value *Cond = Select->getCondition();
9044 
9045       // TODO: Support inverse predicates.
9046       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9047         if (!isa<ExtractElementInst>(RHS) ||
9048             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9049           return RecurKind::None;
9050       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9051         if (!isa<ExtractElementInst>(LHS) ||
9052             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9053           return RecurKind::None;
9054       } else {
9055         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9056           return RecurKind::None;
9057         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9058             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9059             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9060           return RecurKind::None;
9061       }
9062 
9063       switch (Pred) {
9064       default:
9065         return RecurKind::None;
9066       case CmpInst::ICMP_SGT:
9067       case CmpInst::ICMP_SGE:
9068         return RecurKind::SMax;
9069       case CmpInst::ICMP_SLT:
9070       case CmpInst::ICMP_SLE:
9071         return RecurKind::SMin;
9072       case CmpInst::ICMP_UGT:
9073       case CmpInst::ICMP_UGE:
9074         return RecurKind::UMax;
9075       case CmpInst::ICMP_ULT:
9076       case CmpInst::ICMP_ULE:
9077         return RecurKind::UMin;
9078       }
9079     }
9080     return RecurKind::None;
9081   }
9082 
9083   /// Get the index of the first operand.
9084   static unsigned getFirstOperandIndex(Instruction *I) {
9085     return isCmpSelMinMax(I) ? 1 : 0;
9086   }
9087 
9088   /// Total number of operands in the reduction operation.
9089   static unsigned getNumberOfOperands(Instruction *I) {
9090     return isCmpSelMinMax(I) ? 3 : 2;
9091   }
9092 
9093   /// Checks if the instruction is in basic block \p BB.
9094   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9095   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9096     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9097       auto *Sel = cast<SelectInst>(I);
9098       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9099       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9100     }
9101     return I->getParent() == BB;
9102   }
9103 
9104   /// Expected number of uses for reduction operations/reduced values.
9105   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9106     if (IsCmpSelMinMax) {
9107       // SelectInst must be used twice while the condition op must have single
9108       // use only.
9109       if (auto *Sel = dyn_cast<SelectInst>(I))
9110         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9111       return I->hasNUses(2);
9112     }
9113 
9114     // Arithmetic reduction operation must be used once only.
9115     return I->hasOneUse();
9116   }
9117 
9118   /// Initializes the list of reduction operations.
9119   void initReductionOps(Instruction *I) {
9120     if (isCmpSelMinMax(I))
9121       ReductionOps.assign(2, ReductionOpsType());
9122     else
9123       ReductionOps.assign(1, ReductionOpsType());
9124   }
9125 
9126   /// Add all reduction operations for the reduction instruction \p I.
9127   void addReductionOps(Instruction *I) {
9128     if (isCmpSelMinMax(I)) {
9129       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9130       ReductionOps[1].emplace_back(I);
9131     } else {
9132       ReductionOps[0].emplace_back(I);
9133     }
9134   }
9135 
9136   static Value *getLHS(RecurKind Kind, Instruction *I) {
9137     if (Kind == RecurKind::None)
9138       return nullptr;
9139     return I->getOperand(getFirstOperandIndex(I));
9140   }
9141   static Value *getRHS(RecurKind Kind, Instruction *I) {
9142     if (Kind == RecurKind::None)
9143       return nullptr;
9144     return I->getOperand(getFirstOperandIndex(I) + 1);
9145   }
9146 
9147 public:
9148   HorizontalReduction() = default;
9149 
9150   /// Try to find a reduction tree.
9151   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9152     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9153            "Phi needs to use the binary operator");
9154     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9155             isa<IntrinsicInst>(Inst)) &&
9156            "Expected binop, select, or intrinsic for reduction matching");
9157     RdxKind = getRdxKind(Inst);
9158 
9159     // We could have a initial reductions that is not an add.
9160     //  r *= v1 + v2 + v3 + v4
9161     // In such a case start looking for a tree rooted in the first '+'.
9162     if (Phi) {
9163       if (getLHS(RdxKind, Inst) == Phi) {
9164         Phi = nullptr;
9165         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9166         if (!Inst)
9167           return false;
9168         RdxKind = getRdxKind(Inst);
9169       } else if (getRHS(RdxKind, Inst) == Phi) {
9170         Phi = nullptr;
9171         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9172         if (!Inst)
9173           return false;
9174         RdxKind = getRdxKind(Inst);
9175       }
9176     }
9177 
9178     if (!isVectorizable(RdxKind, Inst))
9179       return false;
9180 
9181     // Analyze "regular" integer/FP types for reductions - no target-specific
9182     // types or pointers.
9183     Type *Ty = Inst->getType();
9184     if (!isValidElementType(Ty) || Ty->isPointerTy())
9185       return false;
9186 
9187     // Though the ultimate reduction may have multiple uses, its condition must
9188     // have only single use.
9189     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9190       if (!Sel->getCondition()->hasOneUse())
9191         return false;
9192 
9193     ReductionRoot = Inst;
9194 
9195     // The opcode for leaf values that we perform a reduction on.
9196     // For example: load(x) + load(y) + load(z) + fptoui(w)
9197     // The leaf opcode for 'w' does not match, so we don't include it as a
9198     // potential candidate for the reduction.
9199     unsigned LeafOpcode = 0;
9200 
9201     // Post-order traverse the reduction tree starting at Inst. We only handle
9202     // true trees containing binary operators or selects.
9203     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9204     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9205     initReductionOps(Inst);
9206     while (!Stack.empty()) {
9207       Instruction *TreeN = Stack.back().first;
9208       unsigned EdgeToVisit = Stack.back().second++;
9209       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9210       bool IsReducedValue = TreeRdxKind != RdxKind;
9211 
9212       // Postorder visit.
9213       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9214         if (IsReducedValue)
9215           ReducedVals.push_back(TreeN);
9216         else {
9217           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9218           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9219             // Check if TreeN is an extra argument of its parent operation.
9220             if (Stack.size() <= 1) {
9221               // TreeN can't be an extra argument as it is a root reduction
9222               // operation.
9223               return false;
9224             }
9225             // Yes, TreeN is an extra argument, do not add it to a list of
9226             // reduction operations.
9227             // Stack[Stack.size() - 2] always points to the parent operation.
9228             markExtraArg(Stack[Stack.size() - 2], TreeN);
9229             ExtraArgs.erase(TreeN);
9230           } else
9231             addReductionOps(TreeN);
9232         }
9233         // Retract.
9234         Stack.pop_back();
9235         continue;
9236       }
9237 
9238       // Visit operands.
9239       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9240       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9241       if (!EdgeInst) {
9242         // Edge value is not a reduction instruction or a leaf instruction.
9243         // (It may be a constant, function argument, or something else.)
9244         markExtraArg(Stack.back(), EdgeVal);
9245         continue;
9246       }
9247       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9248       // Continue analysis if the next operand is a reduction operation or
9249       // (possibly) a leaf value. If the leaf value opcode is not set,
9250       // the first met operation != reduction operation is considered as the
9251       // leaf opcode.
9252       // Only handle trees in the current basic block.
9253       // Each tree node needs to have minimal number of users except for the
9254       // ultimate reduction.
9255       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9256       if (EdgeInst != Phi && EdgeInst != Inst &&
9257           hasSameParent(EdgeInst, Inst->getParent()) &&
9258           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9259           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9260         if (IsRdxInst) {
9261           // We need to be able to reassociate the reduction operations.
9262           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9263             // I is an extra argument for TreeN (its parent operation).
9264             markExtraArg(Stack.back(), EdgeInst);
9265             continue;
9266           }
9267         } else if (!LeafOpcode) {
9268           LeafOpcode = EdgeInst->getOpcode();
9269         }
9270         Stack.push_back(
9271             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9272         continue;
9273       }
9274       // I is an extra argument for TreeN (its parent operation).
9275       markExtraArg(Stack.back(), EdgeInst);
9276     }
9277     return true;
9278   }
9279 
9280   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9281   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9282     // If there are a sufficient number of reduction values, reduce
9283     // to a nearby power-of-2. We can safely generate oversized
9284     // vectors and rely on the backend to split them to legal sizes.
9285     unsigned NumReducedVals = ReducedVals.size();
9286     if (NumReducedVals < 4)
9287       return nullptr;
9288 
9289     // Intersect the fast-math-flags from all reduction operations.
9290     FastMathFlags RdxFMF;
9291     RdxFMF.set();
9292     for (ReductionOpsType &RdxOp : ReductionOps) {
9293       for (Value *RdxVal : RdxOp) {
9294         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9295           RdxFMF &= FPMO->getFastMathFlags();
9296       }
9297     }
9298 
9299     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9300     Builder.setFastMathFlags(RdxFMF);
9301 
9302     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9303     // The same extra argument may be used several times, so log each attempt
9304     // to use it.
9305     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9306       assert(Pair.first && "DebugLoc must be set.");
9307       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9308     }
9309 
9310     // The compare instruction of a min/max is the insertion point for new
9311     // instructions and may be replaced with a new compare instruction.
9312     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9313       assert(isa<SelectInst>(RdxRootInst) &&
9314              "Expected min/max reduction to have select root instruction");
9315       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9316       assert(isa<Instruction>(ScalarCond) &&
9317              "Expected min/max reduction to have compare condition");
9318       return cast<Instruction>(ScalarCond);
9319     };
9320 
9321     // The reduction root is used as the insertion point for new instructions,
9322     // so set it as externally used to prevent it from being deleted.
9323     ExternallyUsedValues[ReductionRoot];
9324     SmallVector<Value *, 16> IgnoreList;
9325     for (ReductionOpsType &RdxOp : ReductionOps)
9326       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9327 
9328     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9329     if (NumReducedVals > ReduxWidth) {
9330       // In the loop below, we are building a tree based on a window of
9331       // 'ReduxWidth' values.
9332       // If the operands of those values have common traits (compare predicate,
9333       // constant operand, etc), then we want to group those together to
9334       // minimize the cost of the reduction.
9335 
9336       // TODO: This should be extended to count common operands for
9337       //       compares and binops.
9338 
9339       // Step 1: Count the number of times each compare predicate occurs.
9340       SmallDenseMap<unsigned, unsigned> PredCountMap;
9341       for (Value *RdxVal : ReducedVals) {
9342         CmpInst::Predicate Pred;
9343         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9344           ++PredCountMap[Pred];
9345       }
9346       // Step 2: Sort the values so the most common predicates come first.
9347       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9348         CmpInst::Predicate PredA, PredB;
9349         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9350             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9351           return PredCountMap[PredA] > PredCountMap[PredB];
9352         }
9353         return false;
9354       });
9355     }
9356 
9357     Value *VectorizedTree = nullptr;
9358     unsigned i = 0;
9359     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9360       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9361       V.buildTree(VL, IgnoreList);
9362       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9363         break;
9364       if (V.isLoadCombineReductionCandidate(RdxKind))
9365         break;
9366       V.reorderTopToBottom();
9367       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9368       V.buildExternalUses(ExternallyUsedValues);
9369 
9370       // For a poison-safe boolean logic reduction, do not replace select
9371       // instructions with logic ops. All reduced values will be frozen (see
9372       // below) to prevent leaking poison.
9373       if (isa<SelectInst>(ReductionRoot) &&
9374           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9375           NumReducedVals != ReduxWidth)
9376         break;
9377 
9378       V.computeMinimumValueSizes();
9379 
9380       // Estimate cost.
9381       InstructionCost TreeCost =
9382           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9383       InstructionCost ReductionCost =
9384           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9385       InstructionCost Cost = TreeCost + ReductionCost;
9386       if (!Cost.isValid()) {
9387         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9388         return nullptr;
9389       }
9390       if (Cost >= -SLPCostThreshold) {
9391         V.getORE()->emit([&]() {
9392           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9393                                           cast<Instruction>(VL[0]))
9394                  << "Vectorizing horizontal reduction is possible"
9395                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9396                  << " and threshold "
9397                  << ore::NV("Threshold", -SLPCostThreshold);
9398         });
9399         break;
9400       }
9401 
9402       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9403                         << Cost << ". (HorRdx)\n");
9404       V.getORE()->emit([&]() {
9405         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9406                                   cast<Instruction>(VL[0]))
9407                << "Vectorized horizontal reduction with cost "
9408                << ore::NV("Cost", Cost) << " and with tree size "
9409                << ore::NV("TreeSize", V.getTreeSize());
9410       });
9411 
9412       // Vectorize a tree.
9413       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9414       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9415 
9416       // Emit a reduction. If the root is a select (min/max idiom), the insert
9417       // point is the compare condition of that select.
9418       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9419       if (isCmpSelMinMax(RdxRootInst))
9420         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9421       else
9422         Builder.SetInsertPoint(RdxRootInst);
9423 
9424       // To prevent poison from leaking across what used to be sequential, safe,
9425       // scalar boolean logic operations, the reduction operand must be frozen.
9426       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9427         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9428 
9429       Value *ReducedSubTree =
9430           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9431 
9432       if (!VectorizedTree) {
9433         // Initialize the final value in the reduction.
9434         VectorizedTree = ReducedSubTree;
9435       } else {
9436         // Update the final value in the reduction.
9437         Builder.SetCurrentDebugLocation(Loc);
9438         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9439                                   ReducedSubTree, "op.rdx", ReductionOps);
9440       }
9441       i += ReduxWidth;
9442       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9443     }
9444 
9445     if (VectorizedTree) {
9446       // Finish the reduction.
9447       for (; i < NumReducedVals; ++i) {
9448         auto *I = cast<Instruction>(ReducedVals[i]);
9449         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9450         VectorizedTree =
9451             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9452       }
9453       for (auto &Pair : ExternallyUsedValues) {
9454         // Add each externally used value to the final reduction.
9455         for (auto *I : Pair.second) {
9456           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9457           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9458                                     Pair.first, "op.extra", I);
9459         }
9460       }
9461 
9462       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9463 
9464       // Mark all scalar reduction ops for deletion, they are replaced by the
9465       // vector reductions.
9466       V.eraseInstructions(IgnoreList);
9467     }
9468     return VectorizedTree;
9469   }
9470 
9471   unsigned numReductionValues() const { return ReducedVals.size(); }
9472 
9473 private:
9474   /// Calculate the cost of a reduction.
9475   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9476                                    Value *FirstReducedVal, unsigned ReduxWidth,
9477                                    FastMathFlags FMF) {
9478     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9479     Type *ScalarTy = FirstReducedVal->getType();
9480     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9481     InstructionCost VectorCost, ScalarCost;
9482     switch (RdxKind) {
9483     case RecurKind::Add:
9484     case RecurKind::Mul:
9485     case RecurKind::Or:
9486     case RecurKind::And:
9487     case RecurKind::Xor:
9488     case RecurKind::FAdd:
9489     case RecurKind::FMul: {
9490       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9491       VectorCost =
9492           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9493       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9494       break;
9495     }
9496     case RecurKind::FMax:
9497     case RecurKind::FMin: {
9498       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9499       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9500       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9501                                                /*IsUnsigned=*/false, CostKind);
9502       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9503       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9504                                            SclCondTy, RdxPred, CostKind) +
9505                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9506                                            SclCondTy, RdxPred, CostKind);
9507       break;
9508     }
9509     case RecurKind::SMax:
9510     case RecurKind::SMin:
9511     case RecurKind::UMax:
9512     case RecurKind::UMin: {
9513       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9514       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9515       bool IsUnsigned =
9516           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9517       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9518                                                CostKind);
9519       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9520       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9521                                            SclCondTy, RdxPred, CostKind) +
9522                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9523                                            SclCondTy, RdxPred, CostKind);
9524       break;
9525     }
9526     default:
9527       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9528     }
9529 
9530     // Scalar cost is repeated for N-1 elements.
9531     ScalarCost *= (ReduxWidth - 1);
9532     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9533                       << " for reduction that starts with " << *FirstReducedVal
9534                       << " (It is a splitting reduction)\n");
9535     return VectorCost - ScalarCost;
9536   }
9537 
9538   /// Emit a horizontal reduction of the vectorized value.
9539   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9540                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9541     assert(VectorizedValue && "Need to have a vectorized tree node");
9542     assert(isPowerOf2_32(ReduxWidth) &&
9543            "We only handle power-of-two reductions for now");
9544     assert(RdxKind != RecurKind::FMulAdd &&
9545            "A call to the llvm.fmuladd intrinsic is not handled yet");
9546 
9547     ++NumVectorInstructions;
9548     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9549   }
9550 };
9551 
9552 } // end anonymous namespace
9553 
9554 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9555   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9556     return cast<FixedVectorType>(IE->getType())->getNumElements();
9557 
9558   unsigned AggregateSize = 1;
9559   auto *IV = cast<InsertValueInst>(InsertInst);
9560   Type *CurrentType = IV->getType();
9561   do {
9562     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9563       for (auto *Elt : ST->elements())
9564         if (Elt != ST->getElementType(0)) // check homogeneity
9565           return None;
9566       AggregateSize *= ST->getNumElements();
9567       CurrentType = ST->getElementType(0);
9568     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9569       AggregateSize *= AT->getNumElements();
9570       CurrentType = AT->getElementType();
9571     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9572       AggregateSize *= VT->getNumElements();
9573       return AggregateSize;
9574     } else if (CurrentType->isSingleValueType()) {
9575       return AggregateSize;
9576     } else {
9577       return None;
9578     }
9579   } while (true);
9580 }
9581 
9582 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9583                                    TargetTransformInfo *TTI,
9584                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9585                                    SmallVectorImpl<Value *> &InsertElts,
9586                                    unsigned OperandOffset) {
9587   do {
9588     Value *InsertedOperand = LastInsertInst->getOperand(1);
9589     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9590     if (!OperandIndex)
9591       return false;
9592     if (isa<InsertElementInst>(InsertedOperand) ||
9593         isa<InsertValueInst>(InsertedOperand)) {
9594       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9595                                   BuildVectorOpds, InsertElts, *OperandIndex))
9596         return false;
9597     } else {
9598       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9599       InsertElts[*OperandIndex] = LastInsertInst;
9600     }
9601     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9602   } while (LastInsertInst != nullptr &&
9603            (isa<InsertValueInst>(LastInsertInst) ||
9604             isa<InsertElementInst>(LastInsertInst)) &&
9605            LastInsertInst->hasOneUse());
9606   return true;
9607 }
9608 
9609 /// Recognize construction of vectors like
9610 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9611 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9612 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9613 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9614 ///  starting from the last insertelement or insertvalue instruction.
9615 ///
9616 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9617 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9618 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9619 ///
9620 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9621 ///
9622 /// \return true if it matches.
9623 static bool findBuildAggregate(Instruction *LastInsertInst,
9624                                TargetTransformInfo *TTI,
9625                                SmallVectorImpl<Value *> &BuildVectorOpds,
9626                                SmallVectorImpl<Value *> &InsertElts) {
9627 
9628   assert((isa<InsertElementInst>(LastInsertInst) ||
9629           isa<InsertValueInst>(LastInsertInst)) &&
9630          "Expected insertelement or insertvalue instruction!");
9631 
9632   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9633          "Expected empty result vectors!");
9634 
9635   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9636   if (!AggregateSize)
9637     return false;
9638   BuildVectorOpds.resize(*AggregateSize);
9639   InsertElts.resize(*AggregateSize);
9640 
9641   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9642                              0)) {
9643     llvm::erase_value(BuildVectorOpds, nullptr);
9644     llvm::erase_value(InsertElts, nullptr);
9645     if (BuildVectorOpds.size() >= 2)
9646       return true;
9647   }
9648 
9649   return false;
9650 }
9651 
9652 /// Try and get a reduction value from a phi node.
9653 ///
9654 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9655 /// if they come from either \p ParentBB or a containing loop latch.
9656 ///
9657 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9658 /// if not possible.
9659 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9660                                 BasicBlock *ParentBB, LoopInfo *LI) {
9661   // There are situations where the reduction value is not dominated by the
9662   // reduction phi. Vectorizing such cases has been reported to cause
9663   // miscompiles. See PR25787.
9664   auto DominatedReduxValue = [&](Value *R) {
9665     return isa<Instruction>(R) &&
9666            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9667   };
9668 
9669   Value *Rdx = nullptr;
9670 
9671   // Return the incoming value if it comes from the same BB as the phi node.
9672   if (P->getIncomingBlock(0) == ParentBB) {
9673     Rdx = P->getIncomingValue(0);
9674   } else if (P->getIncomingBlock(1) == ParentBB) {
9675     Rdx = P->getIncomingValue(1);
9676   }
9677 
9678   if (Rdx && DominatedReduxValue(Rdx))
9679     return Rdx;
9680 
9681   // Otherwise, check whether we have a loop latch to look at.
9682   Loop *BBL = LI->getLoopFor(ParentBB);
9683   if (!BBL)
9684     return nullptr;
9685   BasicBlock *BBLatch = BBL->getLoopLatch();
9686   if (!BBLatch)
9687     return nullptr;
9688 
9689   // There is a loop latch, return the incoming value if it comes from
9690   // that. This reduction pattern occasionally turns up.
9691   if (P->getIncomingBlock(0) == BBLatch) {
9692     Rdx = P->getIncomingValue(0);
9693   } else if (P->getIncomingBlock(1) == BBLatch) {
9694     Rdx = P->getIncomingValue(1);
9695   }
9696 
9697   if (Rdx && DominatedReduxValue(Rdx))
9698     return Rdx;
9699 
9700   return nullptr;
9701 }
9702 
9703 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9704   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9705     return true;
9706   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9707     return true;
9708   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9709     return true;
9710   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9711     return true;
9712   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9713     return true;
9714   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9715     return true;
9716   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9717     return true;
9718   return false;
9719 }
9720 
9721 /// Attempt to reduce a horizontal reduction.
9722 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9723 /// with reduction operators \a Root (or one of its operands) in a basic block
9724 /// \a BB, then check if it can be done. If horizontal reduction is not found
9725 /// and root instruction is a binary operation, vectorization of the operands is
9726 /// attempted.
9727 /// \returns true if a horizontal reduction was matched and reduced or operands
9728 /// of one of the binary instruction were vectorized.
9729 /// \returns false if a horizontal reduction was not matched (or not possible)
9730 /// or no vectorization of any binary operation feeding \a Root instruction was
9731 /// performed.
9732 static bool tryToVectorizeHorReductionOrInstOperands(
9733     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9734     TargetTransformInfo *TTI,
9735     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9736   if (!ShouldVectorizeHor)
9737     return false;
9738 
9739   if (!Root)
9740     return false;
9741 
9742   if (Root->getParent() != BB || isa<PHINode>(Root))
9743     return false;
9744   // Start analysis starting from Root instruction. If horizontal reduction is
9745   // found, try to vectorize it. If it is not a horizontal reduction or
9746   // vectorization is not possible or not effective, and currently analyzed
9747   // instruction is a binary operation, try to vectorize the operands, using
9748   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9749   // the same procedure considering each operand as a possible root of the
9750   // horizontal reduction.
9751   // Interrupt the process if the Root instruction itself was vectorized or all
9752   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9753   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9754   // CmpInsts so we can skip extra attempts in
9755   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9756   std::queue<std::pair<Instruction *, unsigned>> Stack;
9757   Stack.emplace(Root, 0);
9758   SmallPtrSet<Value *, 8> VisitedInstrs;
9759   SmallVector<WeakTrackingVH> PostponedInsts;
9760   bool Res = false;
9761   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9762                                      Value *&B1) -> Value * {
9763     bool IsBinop = matchRdxBop(Inst, B0, B1);
9764     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9765     if (IsBinop || IsSelect) {
9766       HorizontalReduction HorRdx;
9767       if (HorRdx.matchAssociativeReduction(P, Inst))
9768         return HorRdx.tryToReduce(R, TTI);
9769     }
9770     return nullptr;
9771   };
9772   while (!Stack.empty()) {
9773     Instruction *Inst;
9774     unsigned Level;
9775     std::tie(Inst, Level) = Stack.front();
9776     Stack.pop();
9777     // Do not try to analyze instruction that has already been vectorized.
9778     // This may happen when we vectorize instruction operands on a previous
9779     // iteration while stack was populated before that happened.
9780     if (R.isDeleted(Inst))
9781       continue;
9782     Value *B0 = nullptr, *B1 = nullptr;
9783     if (Value *V = TryToReduce(Inst, B0, B1)) {
9784       Res = true;
9785       // Set P to nullptr to avoid re-analysis of phi node in
9786       // matchAssociativeReduction function unless this is the root node.
9787       P = nullptr;
9788       if (auto *I = dyn_cast<Instruction>(V)) {
9789         // Try to find another reduction.
9790         Stack.emplace(I, Level);
9791         continue;
9792       }
9793     } else {
9794       bool IsBinop = B0 && B1;
9795       if (P && IsBinop) {
9796         Inst = dyn_cast<Instruction>(B0);
9797         if (Inst == P)
9798           Inst = dyn_cast<Instruction>(B1);
9799         if (!Inst) {
9800           // Set P to nullptr to avoid re-analysis of phi node in
9801           // matchAssociativeReduction function unless this is the root node.
9802           P = nullptr;
9803           continue;
9804         }
9805       }
9806       // Set P to nullptr to avoid re-analysis of phi node in
9807       // matchAssociativeReduction function unless this is the root node.
9808       P = nullptr;
9809       // Do not try to vectorize CmpInst operands, this is done separately.
9810       // Final attempt for binop args vectorization should happen after the loop
9811       // to try to find reductions.
9812       if (!isa<CmpInst>(Inst))
9813         PostponedInsts.push_back(Inst);
9814     }
9815 
9816     // Try to vectorize operands.
9817     // Continue analysis for the instruction from the same basic block only to
9818     // save compile time.
9819     if (++Level < RecursionMaxDepth)
9820       for (auto *Op : Inst->operand_values())
9821         if (VisitedInstrs.insert(Op).second)
9822           if (auto *I = dyn_cast<Instruction>(Op))
9823             // Do not try to vectorize CmpInst operands,  this is done
9824             // separately.
9825             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9826                 I->getParent() == BB)
9827               Stack.emplace(I, Level);
9828   }
9829   // Try to vectorized binops where reductions were not found.
9830   for (Value *V : PostponedInsts)
9831     if (auto *Inst = dyn_cast<Instruction>(V))
9832       if (!R.isDeleted(Inst))
9833         Res |= Vectorize(Inst, R);
9834   return Res;
9835 }
9836 
9837 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9838                                                  BasicBlock *BB, BoUpSLP &R,
9839                                                  TargetTransformInfo *TTI) {
9840   auto *I = dyn_cast_or_null<Instruction>(V);
9841   if (!I)
9842     return false;
9843 
9844   if (!isa<BinaryOperator>(I))
9845     P = nullptr;
9846   // Try to match and vectorize a horizontal reduction.
9847   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9848     return tryToVectorize(I, R);
9849   };
9850   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9851                                                   ExtraVectorization);
9852 }
9853 
9854 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9855                                                  BasicBlock *BB, BoUpSLP &R) {
9856   const DataLayout &DL = BB->getModule()->getDataLayout();
9857   if (!R.canMapToVector(IVI->getType(), DL))
9858     return false;
9859 
9860   SmallVector<Value *, 16> BuildVectorOpds;
9861   SmallVector<Value *, 16> BuildVectorInsts;
9862   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9863     return false;
9864 
9865   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9866   // Aggregate value is unlikely to be processed in vector register.
9867   return tryToVectorizeList(BuildVectorOpds, R);
9868 }
9869 
9870 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9871                                                    BasicBlock *BB, BoUpSLP &R) {
9872   SmallVector<Value *, 16> BuildVectorInsts;
9873   SmallVector<Value *, 16> BuildVectorOpds;
9874   SmallVector<int> Mask;
9875   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9876       (llvm::all_of(
9877            BuildVectorOpds,
9878            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9879        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9880     return false;
9881 
9882   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9883   return tryToVectorizeList(BuildVectorInsts, R);
9884 }
9885 
9886 template <typename T>
9887 static bool
9888 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9889                        function_ref<unsigned(T *)> Limit,
9890                        function_ref<bool(T *, T *)> Comparator,
9891                        function_ref<bool(T *, T *)> AreCompatible,
9892                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9893                        bool LimitForRegisterSize) {
9894   bool Changed = false;
9895   // Sort by type, parent, operands.
9896   stable_sort(Incoming, Comparator);
9897 
9898   // Try to vectorize elements base on their type.
9899   SmallVector<T *> Candidates;
9900   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9901     // Look for the next elements with the same type, parent and operand
9902     // kinds.
9903     auto *SameTypeIt = IncIt;
9904     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9905       ++SameTypeIt;
9906 
9907     // Try to vectorize them.
9908     unsigned NumElts = (SameTypeIt - IncIt);
9909     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9910                       << NumElts << ")\n");
9911     // The vectorization is a 3-state attempt:
9912     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9913     // size of maximal register at first.
9914     // 2. Try to vectorize remaining instructions with the same type, if
9915     // possible. This may result in the better vectorization results rather than
9916     // if we try just to vectorize instructions with the same/alternate opcodes.
9917     // 3. Final attempt to try to vectorize all instructions with the
9918     // same/alternate ops only, this may result in some extra final
9919     // vectorization.
9920     if (NumElts > 1 &&
9921         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9922       // Success start over because instructions might have been changed.
9923       Changed = true;
9924     } else if (NumElts < Limit(*IncIt) &&
9925                (Candidates.empty() ||
9926                 Candidates.front()->getType() == (*IncIt)->getType())) {
9927       Candidates.append(IncIt, std::next(IncIt, NumElts));
9928     }
9929     // Final attempt to vectorize instructions with the same types.
9930     if (Candidates.size() > 1 &&
9931         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9932       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9933         // Success start over because instructions might have been changed.
9934         Changed = true;
9935       } else if (LimitForRegisterSize) {
9936         // Try to vectorize using small vectors.
9937         for (auto *It = Candidates.begin(), *End = Candidates.end();
9938              It != End;) {
9939           auto *SameTypeIt = It;
9940           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9941             ++SameTypeIt;
9942           unsigned NumElts = (SameTypeIt - It);
9943           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9944                                             /*LimitForRegisterSize=*/false))
9945             Changed = true;
9946           It = SameTypeIt;
9947         }
9948       }
9949       Candidates.clear();
9950     }
9951 
9952     // Start over at the next instruction of a different type (or the end).
9953     IncIt = SameTypeIt;
9954   }
9955   return Changed;
9956 }
9957 
9958 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9959 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9960 /// operands. If IsCompatibility is false, function implements strict weak
9961 /// ordering relation between two cmp instructions, returning true if the first
9962 /// instruction is "less" than the second, i.e. its predicate is less than the
9963 /// predicate of the second or the operands IDs are less than the operands IDs
9964 /// of the second cmp instruction.
9965 template <bool IsCompatibility>
9966 static bool compareCmp(Value *V, Value *V2,
9967                        function_ref<bool(Instruction *)> IsDeleted) {
9968   auto *CI1 = cast<CmpInst>(V);
9969   auto *CI2 = cast<CmpInst>(V2);
9970   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9971     return false;
9972   if (CI1->getOperand(0)->getType()->getTypeID() <
9973       CI2->getOperand(0)->getType()->getTypeID())
9974     return !IsCompatibility;
9975   if (CI1->getOperand(0)->getType()->getTypeID() >
9976       CI2->getOperand(0)->getType()->getTypeID())
9977     return false;
9978   CmpInst::Predicate Pred1 = CI1->getPredicate();
9979   CmpInst::Predicate Pred2 = CI2->getPredicate();
9980   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9981   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9982   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9983   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9984   if (BasePred1 < BasePred2)
9985     return !IsCompatibility;
9986   if (BasePred1 > BasePred2)
9987     return false;
9988   // Compare operands.
9989   bool LEPreds = Pred1 <= Pred2;
9990   bool GEPreds = Pred1 >= Pred2;
9991   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9992     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9993     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9994     if (Op1->getValueID() < Op2->getValueID())
9995       return !IsCompatibility;
9996     if (Op1->getValueID() > Op2->getValueID())
9997       return false;
9998     if (auto *I1 = dyn_cast<Instruction>(Op1))
9999       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10000         if (I1->getParent() != I2->getParent())
10001           return false;
10002         InstructionsState S = getSameOpcode({I1, I2});
10003         if (S.getOpcode())
10004           continue;
10005         return false;
10006       }
10007   }
10008   return IsCompatibility;
10009 }
10010 
10011 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10012     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10013     bool AtTerminator) {
10014   bool OpsChanged = false;
10015   SmallVector<Instruction *, 4> PostponedCmps;
10016   for (auto *I : reverse(Instructions)) {
10017     if (R.isDeleted(I))
10018       continue;
10019     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10020       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10021     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10022       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10023     else if (isa<CmpInst>(I))
10024       PostponedCmps.push_back(I);
10025   }
10026   if (AtTerminator) {
10027     // Try to find reductions first.
10028     for (Instruction *I : PostponedCmps) {
10029       if (R.isDeleted(I))
10030         continue;
10031       for (Value *Op : I->operands())
10032         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10033     }
10034     // Try to vectorize operands as vector bundles.
10035     for (Instruction *I : PostponedCmps) {
10036       if (R.isDeleted(I))
10037         continue;
10038       OpsChanged |= tryToVectorize(I, R);
10039     }
10040     // Try to vectorize list of compares.
10041     // Sort by type, compare predicate, etc.
10042     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10043       return compareCmp<false>(V, V2,
10044                                [&R](Instruction *I) { return R.isDeleted(I); });
10045     };
10046 
10047     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10048       if (V1 == V2)
10049         return true;
10050       return compareCmp<true>(V1, V2,
10051                               [&R](Instruction *I) { return R.isDeleted(I); });
10052     };
10053     auto Limit = [&R](Value *V) {
10054       unsigned EltSize = R.getVectorElementSize(V);
10055       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10056     };
10057 
10058     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10059     OpsChanged |= tryToVectorizeSequence<Value>(
10060         Vals, Limit, CompareSorter, AreCompatibleCompares,
10061         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10062           // Exclude possible reductions from other blocks.
10063           bool ArePossiblyReducedInOtherBlock =
10064               any_of(Candidates, [](Value *V) {
10065                 return any_of(V->users(), [V](User *U) {
10066                   return isa<SelectInst>(U) &&
10067                          cast<SelectInst>(U)->getParent() !=
10068                              cast<Instruction>(V)->getParent();
10069                 });
10070               });
10071           if (ArePossiblyReducedInOtherBlock)
10072             return false;
10073           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10074         },
10075         /*LimitForRegisterSize=*/true);
10076     Instructions.clear();
10077   } else {
10078     // Insert in reverse order since the PostponedCmps vector was filled in
10079     // reverse order.
10080     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10081   }
10082   return OpsChanged;
10083 }
10084 
10085 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10086   bool Changed = false;
10087   SmallVector<Value *, 4> Incoming;
10088   SmallPtrSet<Value *, 16> VisitedInstrs;
10089   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10090   // node. Allows better to identify the chains that can be vectorized in the
10091   // better way.
10092   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10093   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10094     assert(isValidElementType(V1->getType()) &&
10095            isValidElementType(V2->getType()) &&
10096            "Expected vectorizable types only.");
10097     // It is fine to compare type IDs here, since we expect only vectorizable
10098     // types, like ints, floats and pointers, we don't care about other type.
10099     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10100       return true;
10101     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10102       return false;
10103     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10104     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10105     if (Opcodes1.size() < Opcodes2.size())
10106       return true;
10107     if (Opcodes1.size() > Opcodes2.size())
10108       return false;
10109     Optional<bool> ConstOrder;
10110     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10111       // Undefs are compatible with any other value.
10112       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10113         if (!ConstOrder)
10114           ConstOrder =
10115               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10116         continue;
10117       }
10118       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10119         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10120           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10121           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10122           if (!NodeI1)
10123             return NodeI2 != nullptr;
10124           if (!NodeI2)
10125             return false;
10126           assert((NodeI1 == NodeI2) ==
10127                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10128                  "Different nodes should have different DFS numbers");
10129           if (NodeI1 != NodeI2)
10130             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10131           InstructionsState S = getSameOpcode({I1, I2});
10132           if (S.getOpcode())
10133             continue;
10134           return I1->getOpcode() < I2->getOpcode();
10135         }
10136       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10137         if (!ConstOrder)
10138           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10139         continue;
10140       }
10141       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10142         return true;
10143       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10144         return false;
10145     }
10146     return ConstOrder && *ConstOrder;
10147   };
10148   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10149     if (V1 == V2)
10150       return true;
10151     if (V1->getType() != V2->getType())
10152       return false;
10153     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10154     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10155     if (Opcodes1.size() != Opcodes2.size())
10156       return false;
10157     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10158       // Undefs are compatible with any other value.
10159       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10160         continue;
10161       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10162         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10163           if (I1->getParent() != I2->getParent())
10164             return false;
10165           InstructionsState S = getSameOpcode({I1, I2});
10166           if (S.getOpcode())
10167             continue;
10168           return false;
10169         }
10170       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10171         continue;
10172       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10173         return false;
10174     }
10175     return true;
10176   };
10177   auto Limit = [&R](Value *V) {
10178     unsigned EltSize = R.getVectorElementSize(V);
10179     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10180   };
10181 
10182   bool HaveVectorizedPhiNodes = false;
10183   do {
10184     // Collect the incoming values from the PHIs.
10185     Incoming.clear();
10186     for (Instruction &I : *BB) {
10187       PHINode *P = dyn_cast<PHINode>(&I);
10188       if (!P)
10189         break;
10190 
10191       // No need to analyze deleted, vectorized and non-vectorizable
10192       // instructions.
10193       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10194           isValidElementType(P->getType()))
10195         Incoming.push_back(P);
10196     }
10197 
10198     // Find the corresponding non-phi nodes for better matching when trying to
10199     // build the tree.
10200     for (Value *V : Incoming) {
10201       SmallVectorImpl<Value *> &Opcodes =
10202           PHIToOpcodes.try_emplace(V).first->getSecond();
10203       if (!Opcodes.empty())
10204         continue;
10205       SmallVector<Value *, 4> Nodes(1, V);
10206       SmallPtrSet<Value *, 4> Visited;
10207       while (!Nodes.empty()) {
10208         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10209         if (!Visited.insert(PHI).second)
10210           continue;
10211         for (Value *V : PHI->incoming_values()) {
10212           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10213             Nodes.push_back(PHI1);
10214             continue;
10215           }
10216           Opcodes.emplace_back(V);
10217         }
10218       }
10219     }
10220 
10221     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10222         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10223         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10224           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10225         },
10226         /*LimitForRegisterSize=*/true);
10227     Changed |= HaveVectorizedPhiNodes;
10228     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10229   } while (HaveVectorizedPhiNodes);
10230 
10231   VisitedInstrs.clear();
10232 
10233   SmallVector<Instruction *, 8> PostProcessInstructions;
10234   SmallDenseSet<Instruction *, 4> KeyNodes;
10235   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10236     // Skip instructions with scalable type. The num of elements is unknown at
10237     // compile-time for scalable type.
10238     if (isa<ScalableVectorType>(it->getType()))
10239       continue;
10240 
10241     // Skip instructions marked for the deletion.
10242     if (R.isDeleted(&*it))
10243       continue;
10244     // We may go through BB multiple times so skip the one we have checked.
10245     if (!VisitedInstrs.insert(&*it).second) {
10246       if (it->use_empty() && KeyNodes.contains(&*it) &&
10247           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10248                                       it->isTerminator())) {
10249         // We would like to start over since some instructions are deleted
10250         // and the iterator may become invalid value.
10251         Changed = true;
10252         it = BB->begin();
10253         e = BB->end();
10254       }
10255       continue;
10256     }
10257 
10258     if (isa<DbgInfoIntrinsic>(it))
10259       continue;
10260 
10261     // Try to vectorize reductions that use PHINodes.
10262     if (PHINode *P = dyn_cast<PHINode>(it)) {
10263       // Check that the PHI is a reduction PHI.
10264       if (P->getNumIncomingValues() == 2) {
10265         // Try to match and vectorize a horizontal reduction.
10266         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10267                                      TTI)) {
10268           Changed = true;
10269           it = BB->begin();
10270           e = BB->end();
10271           continue;
10272         }
10273       }
10274       // Try to vectorize the incoming values of the PHI, to catch reductions
10275       // that feed into PHIs.
10276       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10277         // Skip if the incoming block is the current BB for now. Also, bypass
10278         // unreachable IR for efficiency and to avoid crashing.
10279         // TODO: Collect the skipped incoming values and try to vectorize them
10280         // after processing BB.
10281         if (BB == P->getIncomingBlock(I) ||
10282             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10283           continue;
10284 
10285         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10286                                             P->getIncomingBlock(I), R, TTI);
10287       }
10288       continue;
10289     }
10290 
10291     // Ran into an instruction without users, like terminator, or function call
10292     // with ignored return value, store. Ignore unused instructions (basing on
10293     // instruction type, except for CallInst and InvokeInst).
10294     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10295                             isa<InvokeInst>(it))) {
10296       KeyNodes.insert(&*it);
10297       bool OpsChanged = false;
10298       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10299         for (auto *V : it->operand_values()) {
10300           // Try to match and vectorize a horizontal reduction.
10301           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10302         }
10303       }
10304       // Start vectorization of post-process list of instructions from the
10305       // top-tree instructions to try to vectorize as many instructions as
10306       // possible.
10307       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10308                                                 it->isTerminator());
10309       if (OpsChanged) {
10310         // We would like to start over since some instructions are deleted
10311         // and the iterator may become invalid value.
10312         Changed = true;
10313         it = BB->begin();
10314         e = BB->end();
10315         continue;
10316       }
10317     }
10318 
10319     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10320         isa<InsertValueInst>(it))
10321       PostProcessInstructions.push_back(&*it);
10322   }
10323 
10324   return Changed;
10325 }
10326 
10327 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10328   auto Changed = false;
10329   for (auto &Entry : GEPs) {
10330     // If the getelementptr list has fewer than two elements, there's nothing
10331     // to do.
10332     if (Entry.second.size() < 2)
10333       continue;
10334 
10335     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10336                       << Entry.second.size() << ".\n");
10337 
10338     // Process the GEP list in chunks suitable for the target's supported
10339     // vector size. If a vector register can't hold 1 element, we are done. We
10340     // are trying to vectorize the index computations, so the maximum number of
10341     // elements is based on the size of the index expression, rather than the
10342     // size of the GEP itself (the target's pointer size).
10343     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10344     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10345     if (MaxVecRegSize < EltSize)
10346       continue;
10347 
10348     unsigned MaxElts = MaxVecRegSize / EltSize;
10349     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10350       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10351       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10352 
10353       // Initialize a set a candidate getelementptrs. Note that we use a
10354       // SetVector here to preserve program order. If the index computations
10355       // are vectorizable and begin with loads, we want to minimize the chance
10356       // of having to reorder them later.
10357       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10358 
10359       // Some of the candidates may have already been vectorized after we
10360       // initially collected them. If so, they are marked as deleted, so remove
10361       // them from the set of candidates.
10362       Candidates.remove_if(
10363           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10364 
10365       // Remove from the set of candidates all pairs of getelementptrs with
10366       // constant differences. Such getelementptrs are likely not good
10367       // candidates for vectorization in a bottom-up phase since one can be
10368       // computed from the other. We also ensure all candidate getelementptr
10369       // indices are unique.
10370       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10371         auto *GEPI = GEPList[I];
10372         if (!Candidates.count(GEPI))
10373           continue;
10374         auto *SCEVI = SE->getSCEV(GEPList[I]);
10375         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10376           auto *GEPJ = GEPList[J];
10377           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10378           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10379             Candidates.remove(GEPI);
10380             Candidates.remove(GEPJ);
10381           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10382             Candidates.remove(GEPJ);
10383           }
10384         }
10385       }
10386 
10387       // We break out of the above computation as soon as we know there are
10388       // fewer than two candidates remaining.
10389       if (Candidates.size() < 2)
10390         continue;
10391 
10392       // Add the single, non-constant index of each candidate to the bundle. We
10393       // ensured the indices met these constraints when we originally collected
10394       // the getelementptrs.
10395       SmallVector<Value *, 16> Bundle(Candidates.size());
10396       auto BundleIndex = 0u;
10397       for (auto *V : Candidates) {
10398         auto *GEP = cast<GetElementPtrInst>(V);
10399         auto *GEPIdx = GEP->idx_begin()->get();
10400         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10401         Bundle[BundleIndex++] = GEPIdx;
10402       }
10403 
10404       // Try and vectorize the indices. We are currently only interested in
10405       // gather-like cases of the form:
10406       //
10407       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10408       //
10409       // where the loads of "a", the loads of "b", and the subtractions can be
10410       // performed in parallel. It's likely that detecting this pattern in a
10411       // bottom-up phase will be simpler and less costly than building a
10412       // full-blown top-down phase beginning at the consecutive loads.
10413       Changed |= tryToVectorizeList(Bundle, R);
10414     }
10415   }
10416   return Changed;
10417 }
10418 
10419 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10420   bool Changed = false;
10421   // Sort by type, base pointers and values operand. Value operands must be
10422   // compatible (have the same opcode, same parent), otherwise it is
10423   // definitely not profitable to try to vectorize them.
10424   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10425     if (V->getPointerOperandType()->getTypeID() <
10426         V2->getPointerOperandType()->getTypeID())
10427       return true;
10428     if (V->getPointerOperandType()->getTypeID() >
10429         V2->getPointerOperandType()->getTypeID())
10430       return false;
10431     // UndefValues are compatible with all other values.
10432     if (isa<UndefValue>(V->getValueOperand()) ||
10433         isa<UndefValue>(V2->getValueOperand()))
10434       return false;
10435     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10436       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10437         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10438             DT->getNode(I1->getParent());
10439         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10440             DT->getNode(I2->getParent());
10441         assert(NodeI1 && "Should only process reachable instructions");
10442         assert(NodeI1 && "Should only process reachable instructions");
10443         assert((NodeI1 == NodeI2) ==
10444                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10445                "Different nodes should have different DFS numbers");
10446         if (NodeI1 != NodeI2)
10447           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10448         InstructionsState S = getSameOpcode({I1, I2});
10449         if (S.getOpcode())
10450           return false;
10451         return I1->getOpcode() < I2->getOpcode();
10452       }
10453     if (isa<Constant>(V->getValueOperand()) &&
10454         isa<Constant>(V2->getValueOperand()))
10455       return false;
10456     return V->getValueOperand()->getValueID() <
10457            V2->getValueOperand()->getValueID();
10458   };
10459 
10460   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10461     if (V1 == V2)
10462       return true;
10463     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10464       return false;
10465     // Undefs are compatible with any other value.
10466     if (isa<UndefValue>(V1->getValueOperand()) ||
10467         isa<UndefValue>(V2->getValueOperand()))
10468       return true;
10469     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10470       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10471         if (I1->getParent() != I2->getParent())
10472           return false;
10473         InstructionsState S = getSameOpcode({I1, I2});
10474         return S.getOpcode() > 0;
10475       }
10476     if (isa<Constant>(V1->getValueOperand()) &&
10477         isa<Constant>(V2->getValueOperand()))
10478       return true;
10479     return V1->getValueOperand()->getValueID() ==
10480            V2->getValueOperand()->getValueID();
10481   };
10482   auto Limit = [&R, this](StoreInst *SI) {
10483     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10484     return R.getMinVF(EltSize);
10485   };
10486 
10487   // Attempt to sort and vectorize each of the store-groups.
10488   for (auto &Pair : Stores) {
10489     if (Pair.second.size() < 2)
10490       continue;
10491 
10492     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10493                       << Pair.second.size() << ".\n");
10494 
10495     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10496       continue;
10497 
10498     Changed |= tryToVectorizeSequence<StoreInst>(
10499         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10500         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10501           return vectorizeStores(Candidates, R);
10502         },
10503         /*LimitForRegisterSize=*/false);
10504   }
10505   return Changed;
10506 }
10507 
10508 char SLPVectorizer::ID = 0;
10509 
10510 static const char lv_name[] = "SLP Vectorizer";
10511 
10512 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10513 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10514 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10515 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10516 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10517 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10518 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10519 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10520 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10521 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10522 
10523 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10524