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