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/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.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<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper data structure to hold the operands of a vector of instructions.
1038   /// This supports a fixed vector length for all operand vectors.
1039   class VLOperands {
1040     /// For each operand we need (i) the value, and (ii) the opcode that it
1041     /// would be attached to if the expression was in a left-linearized form.
1042     /// This is required to avoid illegal operand reordering.
1043     /// For example:
1044     /// \verbatim
1045     ///                         0 Op1
1046     ///                         |/
1047     /// Op1 Op2   Linearized    + Op2
1048     ///   \ /     ---------->   |/
1049     ///    -                    -
1050     ///
1051     /// Op1 - Op2            (0 + Op1) - Op2
1052     /// \endverbatim
1053     ///
1054     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1055     ///
1056     /// Another way to think of this is to track all the operations across the
1057     /// path from the operand all the way to the root of the tree and to
1058     /// calculate the operation that corresponds to this path. For example, the
1059     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1060     /// corresponding operation is a '-' (which matches the one in the
1061     /// linearized tree, as shown above).
1062     ///
1063     /// For lack of a better term, we refer to this operation as Accumulated
1064     /// Path Operation (APO).
1065     struct OperandData {
1066       OperandData() = default;
1067       OperandData(Value *V, bool APO, bool IsUsed)
1068           : V(V), APO(APO), IsUsed(IsUsed) {}
1069       /// The operand value.
1070       Value *V = nullptr;
1071       /// TreeEntries only allow a single opcode, or an alternate sequence of
1072       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1073       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1074       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1075       /// (e.g., Add/Mul)
1076       bool APO = false;
1077       /// Helper data for the reordering function.
1078       bool IsUsed = false;
1079     };
1080 
1081     /// During operand reordering, we are trying to select the operand at lane
1082     /// that matches best with the operand at the neighboring lane. Our
1083     /// selection is based on the type of value we are looking for. For example,
1084     /// if the neighboring lane has a load, we need to look for a load that is
1085     /// accessing a consecutive address. These strategies are summarized in the
1086     /// 'ReorderingMode' enumerator.
1087     enum class ReorderingMode {
1088       Load,     ///< Matching loads to consecutive memory addresses
1089       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1090       Constant, ///< Matching constants
1091       Splat,    ///< Matching the same instruction multiple times (broadcast)
1092       Failed,   ///< We failed to create a vectorizable group
1093     };
1094 
1095     using OperandDataVec = SmallVector<OperandData, 2>;
1096 
1097     /// A vector of operand vectors.
1098     SmallVector<OperandDataVec, 4> OpsVec;
1099 
1100     const DataLayout &DL;
1101     ScalarEvolution &SE;
1102     const BoUpSLP &R;
1103 
1104     /// \returns the operand data at \p OpIdx and \p Lane.
1105     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1106       return OpsVec[OpIdx][Lane];
1107     }
1108 
1109     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1110     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1111       return OpsVec[OpIdx][Lane];
1112     }
1113 
1114     /// Clears the used flag for all entries.
1115     void clearUsed() {
1116       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1117            OpIdx != NumOperands; ++OpIdx)
1118         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1119              ++Lane)
1120           OpsVec[OpIdx][Lane].IsUsed = false;
1121     }
1122 
1123     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1124     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1125       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1126     }
1127 
1128     // The hard-coded scores listed here are not very important, though it shall
1129     // be higher for better matches to improve the resulting cost. When
1130     // computing the scores of matching one sub-tree with another, we are
1131     // basically counting the number of values that are matching. So even if all
1132     // scores are set to 1, we would still get a decent matching result.
1133     // However, sometimes we have to break ties. For example we may have to
1134     // choose between matching loads vs matching opcodes. This is what these
1135     // scores are helping us with: they provide the order of preference. Also,
1136     // this is important if the scalar is externally used or used in another
1137     // tree entry node in the different lane.
1138 
1139     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1140     static const int ScoreConsecutiveLoads = 4;
1141     /// The same load multiple times. This should have a better score than
1142     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1143     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1144     /// a vector load and 1.0 for a broadcast.
1145     static const int ScoreSplatLoads = 3;
1146     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1147     static const int ScoreReversedLoads = 3;
1148     /// ExtractElementInst from same vector and consecutive indexes.
1149     static const int ScoreConsecutiveExtracts = 4;
1150     /// ExtractElementInst from same vector and reversed indices.
1151     static const int ScoreReversedExtracts = 3;
1152     /// Constants.
1153     static const int ScoreConstants = 2;
1154     /// Instructions with the same opcode.
1155     static const int ScoreSameOpcode = 2;
1156     /// Instructions with alt opcodes (e.g, add + sub).
1157     static const int ScoreAltOpcodes = 1;
1158     /// Identical instructions (a.k.a. splat or broadcast).
1159     static const int ScoreSplat = 1;
1160     /// Matching with an undef is preferable to failing.
1161     static const int ScoreUndef = 1;
1162     /// Score for failing to find a decent match.
1163     static const int ScoreFail = 0;
1164     /// Score if all users are vectorized.
1165     static const int ScoreAllUserVectorized = 1;
1166 
1167     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1168     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1169     /// MainAltOps.
1170     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1171                                ScalarEvolution &SE, int NumLanes,
1172                                ArrayRef<Value *> MainAltOps,
1173                                const TargetTransformInfo *TTI) {
1174       if (V1 == V2) {
1175         if (isa<LoadInst>(V1)) {
1176           // A broadcast of a load can be cheaper on some targets.
1177           // TODO: For now accept a broadcast load with no other internal uses.
1178           if (TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1179               (int)V1->getNumUses() == NumLanes)
1180             return VLOperands::ScoreSplatLoads;
1181         }
1182         return VLOperands::ScoreSplat;
1183       }
1184 
1185       auto *LI1 = dyn_cast<LoadInst>(V1);
1186       auto *LI2 = dyn_cast<LoadInst>(V2);
1187       if (LI1 && LI2) {
1188         if (LI1->getParent() != LI2->getParent())
1189           return VLOperands::ScoreFail;
1190 
1191         Optional<int> Dist = getPointersDiff(
1192             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1193             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1194         if (!Dist || *Dist == 0)
1195           return VLOperands::ScoreFail;
1196         // The distance is too large - still may be profitable to use masked
1197         // loads/gathers.
1198         if (std::abs(*Dist) > NumLanes / 2)
1199           return VLOperands::ScoreAltOpcodes;
1200         // This still will detect consecutive loads, but we might have "holes"
1201         // in some cases. It is ok for non-power-2 vectorization and may produce
1202         // better results. It should not affect current vectorization.
1203         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1204                            : VLOperands::ScoreReversedLoads;
1205       }
1206 
1207       auto *C1 = dyn_cast<Constant>(V1);
1208       auto *C2 = dyn_cast<Constant>(V2);
1209       if (C1 && C2)
1210         return VLOperands::ScoreConstants;
1211 
1212       // Extracts from consecutive indexes of the same vector better score as
1213       // the extracts could be optimized away.
1214       Value *EV1;
1215       ConstantInt *Ex1Idx;
1216       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1217         // Undefs are always profitable for extractelements.
1218         if (isa<UndefValue>(V2))
1219           return VLOperands::ScoreConsecutiveExtracts;
1220         Value *EV2 = nullptr;
1221         ConstantInt *Ex2Idx = nullptr;
1222         if (match(V2,
1223                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1224                                                          m_Undef())))) {
1225           // Undefs are always profitable for extractelements.
1226           if (!Ex2Idx)
1227             return VLOperands::ScoreConsecutiveExtracts;
1228           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1229             return VLOperands::ScoreConsecutiveExtracts;
1230           if (EV2 == EV1) {
1231             int Idx1 = Ex1Idx->getZExtValue();
1232             int Idx2 = Ex2Idx->getZExtValue();
1233             int Dist = Idx2 - Idx1;
1234             // The distance is too large - still may be profitable to use
1235             // shuffles.
1236             if (std::abs(Dist) == 0)
1237               return VLOperands::ScoreSplat;
1238             if (std::abs(Dist) > NumLanes / 2)
1239               return VLOperands::ScoreSameOpcode;
1240             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1241                               : VLOperands::ScoreReversedExtracts;
1242           }
1243           return VLOperands::ScoreAltOpcodes;
1244         }
1245         return VLOperands::ScoreFail;
1246       }
1247 
1248       auto *I1 = dyn_cast<Instruction>(V1);
1249       auto *I2 = dyn_cast<Instruction>(V2);
1250       if (I1 && I2) {
1251         if (I1->getParent() != I2->getParent())
1252           return VLOperands::ScoreFail;
1253         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1254         Ops.push_back(I1);
1255         Ops.push_back(I2);
1256         InstructionsState S = getSameOpcode(Ops);
1257         // Note: Only consider instructions with <= 2 operands to avoid
1258         // complexity explosion.
1259         if (S.getOpcode() &&
1260             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1261              !S.isAltShuffle()) &&
1262             all_of(Ops, [&S](Value *V) {
1263               return cast<Instruction>(V)->getNumOperands() ==
1264                      S.MainOp->getNumOperands();
1265             }))
1266           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1267                                   : VLOperands::ScoreSameOpcode;
1268       }
1269 
1270       if (isa<UndefValue>(V2))
1271         return VLOperands::ScoreUndef;
1272 
1273       return VLOperands::ScoreFail;
1274     }
1275 
1276     /// \param Lane lane of the operands under analysis.
1277     /// \param OpIdx operand index in \p Lane lane we're looking the best
1278     /// candidate for.
1279     /// \param Idx operand index of the current candidate value.
1280     /// \returns The additional score due to possible broadcasting of the
1281     /// elements in the lane. It is more profitable to have power-of-2 unique
1282     /// elements in the lane, it will be vectorized with higher probability
1283     /// after removing duplicates. Currently the SLP vectorizer supports only
1284     /// vectorization of the power-of-2 number of unique scalars.
1285     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1286       Value *IdxLaneV = getData(Idx, Lane).V;
1287       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1288         return 0;
1289       SmallPtrSet<Value *, 4> Uniques;
1290       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1291         if (Ln == Lane)
1292           continue;
1293         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1294         if (!isa<Instruction>(OpIdxLnV))
1295           return 0;
1296         Uniques.insert(OpIdxLnV);
1297       }
1298       int UniquesCount = Uniques.size();
1299       int UniquesCntWithIdxLaneV =
1300           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1301       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1302       int UniquesCntWithOpIdxLaneV =
1303           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1304       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1305         return 0;
1306       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1307               UniquesCntWithOpIdxLaneV) -
1308              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1309     }
1310 
1311     /// \param Lane lane of the operands under analysis.
1312     /// \param OpIdx operand index in \p Lane lane we're looking the best
1313     /// candidate for.
1314     /// \param Idx operand index of the current candidate value.
1315     /// \returns The additional score for the scalar which users are all
1316     /// vectorized.
1317     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1318       Value *IdxLaneV = getData(Idx, Lane).V;
1319       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1320       // Do not care about number of uses for vector-like instructions
1321       // (extractelement/extractvalue with constant indices), they are extracts
1322       // themselves and already externally used. Vectorization of such
1323       // instructions does not add extra extractelement instruction, just may
1324       // remove it.
1325       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1326           isVectorLikeInstWithConstOps(OpIdxLaneV))
1327         return VLOperands::ScoreAllUserVectorized;
1328       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1329       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1330         return 0;
1331       return R.areAllUsersVectorized(IdxLaneI, None)
1332                  ? VLOperands::ScoreAllUserVectorized
1333                  : 0;
1334     }
1335 
1336     /// Go through the operands of \p LHS and \p RHS recursively until \p
1337     /// MaxLevel, and return the cummulative score. For example:
1338     /// \verbatim
1339     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1340     ///     \ /         \ /         \ /        \ /
1341     ///      +           +           +          +
1342     ///     G1          G2          G3         G4
1343     /// \endverbatim
1344     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1345     /// each level recursively, accumulating the score. It starts from matching
1346     /// the additions at level 0, then moves on to the loads (level 1). The
1347     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1348     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1349     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1350     /// Please note that the order of the operands does not matter, as we
1351     /// evaluate the score of all profitable combinations of operands. In
1352     /// other words the score of G1 and G4 is the same as G1 and G2. This
1353     /// heuristic is based on ideas described in:
1354     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1355     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1356     ///   Luís F. W. Góes
1357     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1358                            ArrayRef<Value *> MainAltOps) {
1359 
1360       // Get the shallow score of V1 and V2.
1361       int ShallowScoreAtThisLevel =
1362           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps, R.TTI);
1363 
1364       // If reached MaxLevel,
1365       //  or if V1 and V2 are not instructions,
1366       //  or if they are SPLAT,
1367       //  or if they are not consecutive,
1368       //  or if profitable to vectorize loads or extractelements, early return
1369       //  the current cost.
1370       auto *I1 = dyn_cast<Instruction>(LHS);
1371       auto *I2 = dyn_cast<Instruction>(RHS);
1372       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1373           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1374           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1375             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1376             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1377            ShallowScoreAtThisLevel))
1378         return ShallowScoreAtThisLevel;
1379       assert(I1 && I2 && "Should have early exited.");
1380 
1381       // Contains the I2 operand indexes that got matched with I1 operands.
1382       SmallSet<unsigned, 4> Op2Used;
1383 
1384       // Recursion towards the operands of I1 and I2. We are trying all possible
1385       // operand pairs, and keeping track of the best score.
1386       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1387            OpIdx1 != NumOperands1; ++OpIdx1) {
1388         // Try to pair op1I with the best operand of I2.
1389         int MaxTmpScore = 0;
1390         unsigned MaxOpIdx2 = 0;
1391         bool FoundBest = false;
1392         // If I2 is commutative try all combinations.
1393         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1394         unsigned ToIdx = isCommutative(I2)
1395                              ? I2->getNumOperands()
1396                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1397         assert(FromIdx <= ToIdx && "Bad index");
1398         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1399           // Skip operands already paired with OpIdx1.
1400           if (Op2Used.count(OpIdx2))
1401             continue;
1402           // Recursively calculate the cost at each level
1403           int TmpScore =
1404               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1405                                  CurrLevel + 1, MaxLevel, None);
1406           // Look for the best score.
1407           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1408             MaxTmpScore = TmpScore;
1409             MaxOpIdx2 = OpIdx2;
1410             FoundBest = true;
1411           }
1412         }
1413         if (FoundBest) {
1414           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1415           Op2Used.insert(MaxOpIdx2);
1416           ShallowScoreAtThisLevel += MaxTmpScore;
1417         }
1418       }
1419       return ShallowScoreAtThisLevel;
1420     }
1421 
1422     /// Score scaling factor for fully compatible instructions but with
1423     /// different number of external uses. Allows better selection of the
1424     /// instructions with less external uses.
1425     static const int ScoreScaleFactor = 10;
1426 
1427     /// \Returns the look-ahead score, which tells us how much the sub-trees
1428     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1429     /// score. This helps break ties in an informed way when we cannot decide on
1430     /// the order of the operands by just considering the immediate
1431     /// predecessors.
1432     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1433                           int Lane, unsigned OpIdx, unsigned Idx,
1434                           bool &IsUsed) {
1435       int Score =
1436           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1437       if (Score) {
1438         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1439         if (Score <= -SplatScore) {
1440           // Set the minimum score for splat-like sequence to avoid setting
1441           // failed state.
1442           Score = 1;
1443         } else {
1444           Score += SplatScore;
1445           // Scale score to see the difference between different operands
1446           // and similar operands but all vectorized/not all vectorized
1447           // uses. It does not affect actual selection of the best
1448           // compatible operand in general, just allows to select the
1449           // operand with all vectorized uses.
1450           Score *= ScoreScaleFactor;
1451           Score += getExternalUseScore(Lane, OpIdx, Idx);
1452           IsUsed = true;
1453         }
1454       }
1455       return Score;
1456     }
1457 
1458     /// Best defined scores per lanes between the passes. Used to choose the
1459     /// best operand (with the highest score) between the passes.
1460     /// The key - {Operand Index, Lane}.
1461     /// The value - the best score between the passes for the lane and the
1462     /// operand.
1463     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1464         BestScoresPerLanes;
1465 
1466     // Search all operands in Ops[*][Lane] for the one that matches best
1467     // Ops[OpIdx][LastLane] and return its opreand index.
1468     // If no good match can be found, return None.
1469     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1470                                       ArrayRef<ReorderingMode> ReorderingModes,
1471                                       ArrayRef<Value *> MainAltOps) {
1472       unsigned NumOperands = getNumOperands();
1473 
1474       // The operand of the previous lane at OpIdx.
1475       Value *OpLastLane = getData(OpIdx, LastLane).V;
1476 
1477       // Our strategy mode for OpIdx.
1478       ReorderingMode RMode = ReorderingModes[OpIdx];
1479       if (RMode == ReorderingMode::Failed)
1480         return None;
1481 
1482       // The linearized opcode of the operand at OpIdx, Lane.
1483       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1484 
1485       // The best operand index and its score.
1486       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1487       // are using the score to differentiate between the two.
1488       struct BestOpData {
1489         Optional<unsigned> Idx = None;
1490         unsigned Score = 0;
1491       } BestOp;
1492       BestOp.Score =
1493           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1494               .first->second;
1495 
1496       // Track if the operand must be marked as used. If the operand is set to
1497       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1498       // want to reestimate the operands again on the following iterations).
1499       bool IsUsed =
1500           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1501       // Iterate through all unused operands and look for the best.
1502       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1503         // Get the operand at Idx and Lane.
1504         OperandData &OpData = getData(Idx, Lane);
1505         Value *Op = OpData.V;
1506         bool OpAPO = OpData.APO;
1507 
1508         // Skip already selected operands.
1509         if (OpData.IsUsed)
1510           continue;
1511 
1512         // Skip if we are trying to move the operand to a position with a
1513         // different opcode in the linearized tree form. This would break the
1514         // semantics.
1515         if (OpAPO != OpIdxAPO)
1516           continue;
1517 
1518         // Look for an operand that matches the current mode.
1519         switch (RMode) {
1520         case ReorderingMode::Load:
1521         case ReorderingMode::Constant:
1522         case ReorderingMode::Opcode: {
1523           bool LeftToRight = Lane > LastLane;
1524           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1525           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1526           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1527                                         OpIdx, Idx, IsUsed);
1528           if (Score > static_cast<int>(BestOp.Score)) {
1529             BestOp.Idx = Idx;
1530             BestOp.Score = Score;
1531             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1532           }
1533           break;
1534         }
1535         case ReorderingMode::Splat:
1536           if (Op == OpLastLane)
1537             BestOp.Idx = Idx;
1538           break;
1539         case ReorderingMode::Failed:
1540           llvm_unreachable("Not expected Failed reordering mode.");
1541         }
1542       }
1543 
1544       if (BestOp.Idx) {
1545         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1546         return BestOp.Idx;
1547       }
1548       // If we could not find a good match return None.
1549       return None;
1550     }
1551 
1552     /// Helper for reorderOperandVecs.
1553     /// \returns the lane that we should start reordering from. This is the one
1554     /// which has the least number of operands that can freely move about or
1555     /// less profitable because it already has the most optimal set of operands.
1556     unsigned getBestLaneToStartReordering() const {
1557       unsigned Min = UINT_MAX;
1558       unsigned SameOpNumber = 0;
1559       // std::pair<unsigned, unsigned> is used to implement a simple voting
1560       // algorithm and choose the lane with the least number of operands that
1561       // can freely move about or less profitable because it already has the
1562       // most optimal set of operands. The first unsigned is a counter for
1563       // voting, the second unsigned is the counter of lanes with instructions
1564       // with same/alternate opcodes and same parent basic block.
1565       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1566       // Try to be closer to the original results, if we have multiple lanes
1567       // with same cost. If 2 lanes have the same cost, use the one with the
1568       // lowest index.
1569       for (int I = getNumLanes(); I > 0; --I) {
1570         unsigned Lane = I - 1;
1571         OperandsOrderData NumFreeOpsHash =
1572             getMaxNumOperandsThatCanBeReordered(Lane);
1573         // Compare the number of operands that can move and choose the one with
1574         // the least number.
1575         if (NumFreeOpsHash.NumOfAPOs < Min) {
1576           Min = NumFreeOpsHash.NumOfAPOs;
1577           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1578           HashMap.clear();
1579           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1580         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1581                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1582           // Select the most optimal lane in terms of number of operands that
1583           // should be moved around.
1584           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1585           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1586         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1587                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1588           auto It = HashMap.find(NumFreeOpsHash.Hash);
1589           if (It == HashMap.end())
1590             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1591           else
1592             ++It->second.first;
1593         }
1594       }
1595       // Select the lane with the minimum counter.
1596       unsigned BestLane = 0;
1597       unsigned CntMin = UINT_MAX;
1598       for (const auto &Data : reverse(HashMap)) {
1599         if (Data.second.first < CntMin) {
1600           CntMin = Data.second.first;
1601           BestLane = Data.second.second;
1602         }
1603       }
1604       return BestLane;
1605     }
1606 
1607     /// Data structure that helps to reorder operands.
1608     struct OperandsOrderData {
1609       /// The best number of operands with the same APOs, which can be
1610       /// reordered.
1611       unsigned NumOfAPOs = UINT_MAX;
1612       /// Number of operands with the same/alternate instruction opcode and
1613       /// parent.
1614       unsigned NumOpsWithSameOpcodeParent = 0;
1615       /// Hash for the actual operands ordering.
1616       /// Used to count operands, actually their position id and opcode
1617       /// value. It is used in the voting mechanism to find the lane with the
1618       /// least number of operands that can freely move about or less profitable
1619       /// because it already has the most optimal set of operands. Can be
1620       /// replaced with SmallVector<unsigned> instead but hash code is faster
1621       /// and requires less memory.
1622       unsigned Hash = 0;
1623     };
1624     /// \returns the maximum number of operands that are allowed to be reordered
1625     /// for \p Lane and the number of compatible instructions(with the same
1626     /// parent/opcode). This is used as a heuristic for selecting the first lane
1627     /// to start operand reordering.
1628     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1629       unsigned CntTrue = 0;
1630       unsigned NumOperands = getNumOperands();
1631       // Operands with the same APO can be reordered. We therefore need to count
1632       // how many of them we have for each APO, like this: Cnt[APO] = x.
1633       // Since we only have two APOs, namely true and false, we can avoid using
1634       // a map. Instead we can simply count the number of operands that
1635       // correspond to one of them (in this case the 'true' APO), and calculate
1636       // the other by subtracting it from the total number of operands.
1637       // Operands with the same instruction opcode and parent are more
1638       // profitable since we don't need to move them in many cases, with a high
1639       // probability such lane already can be vectorized effectively.
1640       bool AllUndefs = true;
1641       unsigned NumOpsWithSameOpcodeParent = 0;
1642       Instruction *OpcodeI = nullptr;
1643       BasicBlock *Parent = nullptr;
1644       unsigned Hash = 0;
1645       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1646         const OperandData &OpData = getData(OpIdx, Lane);
1647         if (OpData.APO)
1648           ++CntTrue;
1649         // Use Boyer-Moore majority voting for finding the majority opcode and
1650         // the number of times it occurs.
1651         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1652           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1653               I->getParent() != Parent) {
1654             if (NumOpsWithSameOpcodeParent == 0) {
1655               NumOpsWithSameOpcodeParent = 1;
1656               OpcodeI = I;
1657               Parent = I->getParent();
1658             } else {
1659               --NumOpsWithSameOpcodeParent;
1660             }
1661           } else {
1662             ++NumOpsWithSameOpcodeParent;
1663           }
1664         }
1665         Hash = hash_combine(
1666             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1667         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1668       }
1669       if (AllUndefs)
1670         return {};
1671       OperandsOrderData Data;
1672       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1673       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1674       Data.Hash = Hash;
1675       return Data;
1676     }
1677 
1678     /// Go through the instructions in VL and append their operands.
1679     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1680       assert(!VL.empty() && "Bad VL");
1681       assert((empty() || VL.size() == getNumLanes()) &&
1682              "Expected same number of lanes");
1683       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1684       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1685       OpsVec.resize(NumOperands);
1686       unsigned NumLanes = VL.size();
1687       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1688         OpsVec[OpIdx].resize(NumLanes);
1689         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1690           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1691           // Our tree has just 3 nodes: the root and two operands.
1692           // It is therefore trivial to get the APO. We only need to check the
1693           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1694           // RHS operand. The LHS operand of both add and sub is never attached
1695           // to an inversese operation in the linearized form, therefore its APO
1696           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1697 
1698           // Since operand reordering is performed on groups of commutative
1699           // operations or alternating sequences (e.g., +, -), we can safely
1700           // tell the inverse operations by checking commutativity.
1701           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1702           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1703           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1704                                  APO, false};
1705         }
1706       }
1707     }
1708 
1709     /// \returns the number of operands.
1710     unsigned getNumOperands() const { return OpsVec.size(); }
1711 
1712     /// \returns the number of lanes.
1713     unsigned getNumLanes() const { return OpsVec[0].size(); }
1714 
1715     /// \returns the operand value at \p OpIdx and \p Lane.
1716     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1717       return getData(OpIdx, Lane).V;
1718     }
1719 
1720     /// \returns true if the data structure is empty.
1721     bool empty() const { return OpsVec.empty(); }
1722 
1723     /// Clears the data.
1724     void clear() { OpsVec.clear(); }
1725 
1726     /// \Returns true if there are enough operands identical to \p Op to fill
1727     /// the whole vector.
1728     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1729     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1730       bool OpAPO = getData(OpIdx, Lane).APO;
1731       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1732         if (Ln == Lane)
1733           continue;
1734         // This is set to true if we found a candidate for broadcast at Lane.
1735         bool FoundCandidate = false;
1736         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1737           OperandData &Data = getData(OpI, Ln);
1738           if (Data.APO != OpAPO || Data.IsUsed)
1739             continue;
1740           if (Data.V == Op) {
1741             FoundCandidate = true;
1742             Data.IsUsed = true;
1743             break;
1744           }
1745         }
1746         if (!FoundCandidate)
1747           return false;
1748       }
1749       return true;
1750     }
1751 
1752   public:
1753     /// Initialize with all the operands of the instruction vector \p RootVL.
1754     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1755                ScalarEvolution &SE, const BoUpSLP &R)
1756         : DL(DL), SE(SE), R(R) {
1757       // Append all the operands of RootVL.
1758       appendOperandsOfVL(RootVL);
1759     }
1760 
1761     /// \Returns a value vector with the operands across all lanes for the
1762     /// opearnd at \p OpIdx.
1763     ValueList getVL(unsigned OpIdx) const {
1764       ValueList OpVL(OpsVec[OpIdx].size());
1765       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1766              "Expected same num of lanes across all operands");
1767       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1768         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1769       return OpVL;
1770     }
1771 
1772     // Performs operand reordering for 2 or more operands.
1773     // The original operands are in OrigOps[OpIdx][Lane].
1774     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1775     void reorder() {
1776       unsigned NumOperands = getNumOperands();
1777       unsigned NumLanes = getNumLanes();
1778       // Each operand has its own mode. We are using this mode to help us select
1779       // the instructions for each lane, so that they match best with the ones
1780       // we have selected so far.
1781       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1782 
1783       // This is a greedy single-pass algorithm. We are going over each lane
1784       // once and deciding on the best order right away with no back-tracking.
1785       // However, in order to increase its effectiveness, we start with the lane
1786       // that has operands that can move the least. For example, given the
1787       // following lanes:
1788       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1789       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1790       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1791       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1792       // we will start at Lane 1, since the operands of the subtraction cannot
1793       // be reordered. Then we will visit the rest of the lanes in a circular
1794       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1795 
1796       // Find the first lane that we will start our search from.
1797       unsigned FirstLane = getBestLaneToStartReordering();
1798 
1799       // Initialize the modes.
1800       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1801         Value *OpLane0 = getValue(OpIdx, FirstLane);
1802         // Keep track if we have instructions with all the same opcode on one
1803         // side.
1804         if (isa<LoadInst>(OpLane0))
1805           ReorderingModes[OpIdx] = ReorderingMode::Load;
1806         else if (isa<Instruction>(OpLane0)) {
1807           // Check if OpLane0 should be broadcast.
1808           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1809             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1810           else
1811             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1812         }
1813         else if (isa<Constant>(OpLane0))
1814           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1815         else if (isa<Argument>(OpLane0))
1816           // Our best hope is a Splat. It may save some cost in some cases.
1817           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1818         else
1819           // NOTE: This should be unreachable.
1820           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1821       }
1822 
1823       // Check that we don't have same operands. No need to reorder if operands
1824       // are just perfect diamond or shuffled diamond match. Do not do it only
1825       // for possible broadcasts or non-power of 2 number of scalars (just for
1826       // now).
1827       auto &&SkipReordering = [this]() {
1828         SmallPtrSet<Value *, 4> UniqueValues;
1829         ArrayRef<OperandData> Op0 = OpsVec.front();
1830         for (const OperandData &Data : Op0)
1831           UniqueValues.insert(Data.V);
1832         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1833           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1834                 return !UniqueValues.contains(Data.V);
1835               }))
1836             return false;
1837         }
1838         // TODO: Check if we can remove a check for non-power-2 number of
1839         // scalars after full support of non-power-2 vectorization.
1840         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1841       };
1842 
1843       // If the initial strategy fails for any of the operand indexes, then we
1844       // perform reordering again in a second pass. This helps avoid assigning
1845       // high priority to the failed strategy, and should improve reordering for
1846       // the non-failed operand indexes.
1847       for (int Pass = 0; Pass != 2; ++Pass) {
1848         // Check if no need to reorder operands since they're are perfect or
1849         // shuffled diamond match.
1850         // Need to to do it to avoid extra external use cost counting for
1851         // shuffled matches, which may cause regressions.
1852         if (SkipReordering())
1853           break;
1854         // Skip the second pass if the first pass did not fail.
1855         bool StrategyFailed = false;
1856         // Mark all operand data as free to use.
1857         clearUsed();
1858         // We keep the original operand order for the FirstLane, so reorder the
1859         // rest of the lanes. We are visiting the nodes in a circular fashion,
1860         // using FirstLane as the center point and increasing the radius
1861         // distance.
1862         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1863         for (unsigned I = 0; I < NumOperands; ++I)
1864           MainAltOps[I].push_back(getData(I, FirstLane).V);
1865 
1866         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1867           // Visit the lane on the right and then the lane on the left.
1868           for (int Direction : {+1, -1}) {
1869             int Lane = FirstLane + Direction * Distance;
1870             if (Lane < 0 || Lane >= (int)NumLanes)
1871               continue;
1872             int LastLane = Lane - Direction;
1873             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1874                    "Out of bounds");
1875             // Look for a good match for each operand.
1876             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1877               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1878               Optional<unsigned> BestIdx = getBestOperand(
1879                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1880               // By not selecting a value, we allow the operands that follow to
1881               // select a better matching value. We will get a non-null value in
1882               // the next run of getBestOperand().
1883               if (BestIdx) {
1884                 // Swap the current operand with the one returned by
1885                 // getBestOperand().
1886                 swap(OpIdx, BestIdx.getValue(), Lane);
1887               } else {
1888                 // We failed to find a best operand, set mode to 'Failed'.
1889                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1890                 // Enable the second pass.
1891                 StrategyFailed = true;
1892               }
1893               // Try to get the alternate opcode and follow it during analysis.
1894               if (MainAltOps[OpIdx].size() != 2) {
1895                 OperandData &AltOp = getData(OpIdx, Lane);
1896                 InstructionsState OpS =
1897                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1898                 if (OpS.getOpcode() && OpS.isAltShuffle())
1899                   MainAltOps[OpIdx].push_back(AltOp.V);
1900               }
1901             }
1902           }
1903         }
1904         // Skip second pass if the strategy did not fail.
1905         if (!StrategyFailed)
1906           break;
1907       }
1908     }
1909 
1910 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1911     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1912       switch (RMode) {
1913       case ReorderingMode::Load:
1914         return "Load";
1915       case ReorderingMode::Opcode:
1916         return "Opcode";
1917       case ReorderingMode::Constant:
1918         return "Constant";
1919       case ReorderingMode::Splat:
1920         return "Splat";
1921       case ReorderingMode::Failed:
1922         return "Failed";
1923       }
1924       llvm_unreachable("Unimplemented Reordering Type");
1925     }
1926 
1927     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1928                                                    raw_ostream &OS) {
1929       return OS << getModeStr(RMode);
1930     }
1931 
1932     /// Debug print.
1933     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1934       printMode(RMode, dbgs());
1935     }
1936 
1937     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1938       return printMode(RMode, OS);
1939     }
1940 
1941     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1942       const unsigned Indent = 2;
1943       unsigned Cnt = 0;
1944       for (const OperandDataVec &OpDataVec : OpsVec) {
1945         OS << "Operand " << Cnt++ << "\n";
1946         for (const OperandData &OpData : OpDataVec) {
1947           OS.indent(Indent) << "{";
1948           if (Value *V = OpData.V)
1949             OS << *V;
1950           else
1951             OS << "null";
1952           OS << ", APO:" << OpData.APO << "}\n";
1953         }
1954         OS << "\n";
1955       }
1956       return OS;
1957     }
1958 
1959     /// Debug print.
1960     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1961 #endif
1962   };
1963 
1964   /// Checks if the instruction is marked for deletion.
1965   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1966 
1967   /// Removes an instruction from its block and eventually deletes it.
1968   /// It's like Instruction::eraseFromParent() except that the actual deletion
1969   /// is delayed until BoUpSLP is destructed.
1970   void eraseInstruction(Instruction *I) {
1971     DeletedInstructions.insert(I);
1972   }
1973 
1974   ~BoUpSLP();
1975 
1976 private:
1977   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1978   /// reordering (i.e. the operands can be reordered because they have only one
1979   /// user and reordarable).
1980   /// \param ReorderableGathers List of all gather nodes that require reordering
1981   /// (e.g., gather of extractlements or partially vectorizable loads).
1982   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1983   /// reordering, subset of \p NonVectorized.
1984   bool
1985   canReorderOperands(TreeEntry *UserTE,
1986                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1987                      ArrayRef<TreeEntry *> ReorderableGathers,
1988                      SmallVectorImpl<TreeEntry *> &GatherOps);
1989 
1990   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1991   /// if any. If it is not vectorized (gather node), returns nullptr.
1992   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1993     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1994     TreeEntry *TE = nullptr;
1995     const auto *It = find_if(VL, [this, &TE](Value *V) {
1996       TE = getTreeEntry(V);
1997       return TE;
1998     });
1999     if (It != VL.end() && TE->isSame(VL))
2000       return TE;
2001     return nullptr;
2002   }
2003 
2004   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2005   /// if any. If it is not vectorized (gather node), returns nullptr.
2006   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2007                                         unsigned OpIdx) const {
2008     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2009         const_cast<TreeEntry *>(UserTE), OpIdx);
2010   }
2011 
2012   /// Checks if all users of \p I are the part of the vectorization tree.
2013   bool areAllUsersVectorized(Instruction *I,
2014                              ArrayRef<Value *> VectorizedVals) const;
2015 
2016   /// \returns the cost of the vectorizable entry.
2017   InstructionCost getEntryCost(const TreeEntry *E,
2018                                ArrayRef<Value *> VectorizedVals);
2019 
2020   /// This is the recursive part of buildTree.
2021   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2022                      const EdgeInfo &EI);
2023 
2024   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2025   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2026   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2027   /// returns false, setting \p CurrentOrder to either an empty vector or a
2028   /// non-identity permutation that allows to reuse extract instructions.
2029   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2030                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2031 
2032   /// Vectorize a single entry in the tree.
2033   Value *vectorizeTree(TreeEntry *E);
2034 
2035   /// Vectorize a single entry in the tree, starting in \p VL.
2036   Value *vectorizeTree(ArrayRef<Value *> VL);
2037 
2038   /// Create a new vector from a list of scalar values.  Produces a sequence
2039   /// which exploits values reused across lanes, and arranges the inserts
2040   /// for ease of later optimization.
2041   Value *createBuildVector(ArrayRef<Value *> VL);
2042 
2043   /// \returns the scalarization cost for this type. Scalarization in this
2044   /// context means the creation of vectors from a group of scalars. If \p
2045   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2046   /// vector elements.
2047   InstructionCost getGatherCost(FixedVectorType *Ty,
2048                                 const APInt &ShuffledIndices,
2049                                 bool NeedToShuffle) const;
2050 
2051   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2052   /// tree entries.
2053   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2054   /// previous tree entries. \p Mask is filled with the shuffle mask.
2055   Optional<TargetTransformInfo::ShuffleKind>
2056   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2057                         SmallVectorImpl<const TreeEntry *> &Entries);
2058 
2059   /// \returns the scalarization cost for this list of values. Assuming that
2060   /// this subtree gets vectorized, we may need to extract the values from the
2061   /// roots. This method calculates the cost of extracting the values.
2062   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2063 
2064   /// Set the Builder insert point to one after the last instruction in
2065   /// the bundle
2066   void setInsertPointAfterBundle(const TreeEntry *E);
2067 
2068   /// \returns a vector from a collection of scalars in \p VL.
2069   Value *gather(ArrayRef<Value *> VL);
2070 
2071   /// \returns whether the VectorizableTree is fully vectorizable and will
2072   /// be beneficial even the tree height is tiny.
2073   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2074 
2075   /// Reorder commutative or alt operands to get better probability of
2076   /// generating vectorized code.
2077   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2078                                              SmallVectorImpl<Value *> &Left,
2079                                              SmallVectorImpl<Value *> &Right,
2080                                              const DataLayout &DL,
2081                                              ScalarEvolution &SE,
2082                                              const BoUpSLP &R);
2083   struct TreeEntry {
2084     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2085     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2086 
2087     /// \returns true if the scalars in VL are equal to this entry.
2088     bool isSame(ArrayRef<Value *> VL) const {
2089       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2090         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2091           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2092         return VL.size() == Mask.size() &&
2093                std::equal(VL.begin(), VL.end(), Mask.begin(),
2094                           [Scalars](Value *V, int Idx) {
2095                             return (isa<UndefValue>(V) &&
2096                                     Idx == UndefMaskElem) ||
2097                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2098                           });
2099       };
2100       if (!ReorderIndices.empty()) {
2101         // TODO: implement matching if the nodes are just reordered, still can
2102         // treat the vector as the same if the list of scalars matches VL
2103         // directly, without reordering.
2104         SmallVector<int> Mask;
2105         inversePermutation(ReorderIndices, Mask);
2106         if (VL.size() == Scalars.size())
2107           return IsSame(Scalars, Mask);
2108         if (VL.size() == ReuseShuffleIndices.size()) {
2109           ::addMask(Mask, ReuseShuffleIndices);
2110           return IsSame(Scalars, Mask);
2111         }
2112         return false;
2113       }
2114       return IsSame(Scalars, ReuseShuffleIndices);
2115     }
2116 
2117     /// \returns true if current entry has same operands as \p TE.
2118     bool hasEqualOperands(const TreeEntry &TE) const {
2119       if (TE.getNumOperands() != getNumOperands())
2120         return false;
2121       SmallBitVector Used(getNumOperands());
2122       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2123         unsigned PrevCount = Used.count();
2124         for (unsigned K = 0; K < E; ++K) {
2125           if (Used.test(K))
2126             continue;
2127           if (getOperand(K) == TE.getOperand(I)) {
2128             Used.set(K);
2129             break;
2130           }
2131         }
2132         // Check if we actually found the matching operand.
2133         if (PrevCount == Used.count())
2134           return false;
2135       }
2136       return true;
2137     }
2138 
2139     /// \return Final vectorization factor for the node. Defined by the total
2140     /// number of vectorized scalars, including those, used several times in the
2141     /// entry and counted in the \a ReuseShuffleIndices, if any.
2142     unsigned getVectorFactor() const {
2143       if (!ReuseShuffleIndices.empty())
2144         return ReuseShuffleIndices.size();
2145       return Scalars.size();
2146     };
2147 
2148     /// A vector of scalars.
2149     ValueList Scalars;
2150 
2151     /// The Scalars are vectorized into this value. It is initialized to Null.
2152     Value *VectorizedValue = nullptr;
2153 
2154     /// Do we need to gather this sequence or vectorize it
2155     /// (either with vector instruction or with scatter/gather
2156     /// intrinsics for store/load)?
2157     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2158     EntryState State;
2159 
2160     /// Does this sequence require some shuffling?
2161     SmallVector<int, 4> ReuseShuffleIndices;
2162 
2163     /// Does this entry require reordering?
2164     SmallVector<unsigned, 4> ReorderIndices;
2165 
2166     /// Points back to the VectorizableTree.
2167     ///
2168     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2169     /// to be a pointer and needs to be able to initialize the child iterator.
2170     /// Thus we need a reference back to the container to translate the indices
2171     /// to entries.
2172     VecTreeTy &Container;
2173 
2174     /// The TreeEntry index containing the user of this entry.  We can actually
2175     /// have multiple users so the data structure is not truly a tree.
2176     SmallVector<EdgeInfo, 1> UserTreeIndices;
2177 
2178     /// The index of this treeEntry in VectorizableTree.
2179     int Idx = -1;
2180 
2181   private:
2182     /// The operands of each instruction in each lane Operands[op_index][lane].
2183     /// Note: This helps avoid the replication of the code that performs the
2184     /// reordering of operands during buildTree_rec() and vectorizeTree().
2185     SmallVector<ValueList, 2> Operands;
2186 
2187     /// The main/alternate instruction.
2188     Instruction *MainOp = nullptr;
2189     Instruction *AltOp = nullptr;
2190 
2191   public:
2192     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2193     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2194       if (Operands.size() < OpIdx + 1)
2195         Operands.resize(OpIdx + 1);
2196       assert(Operands[OpIdx].empty() && "Already resized?");
2197       assert(OpVL.size() <= Scalars.size() &&
2198              "Number of operands is greater than the number of scalars.");
2199       Operands[OpIdx].resize(OpVL.size());
2200       copy(OpVL, Operands[OpIdx].begin());
2201     }
2202 
2203     /// Set the operands of this bundle in their original order.
2204     void setOperandsInOrder() {
2205       assert(Operands.empty() && "Already initialized?");
2206       auto *I0 = cast<Instruction>(Scalars[0]);
2207       Operands.resize(I0->getNumOperands());
2208       unsigned NumLanes = Scalars.size();
2209       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2210            OpIdx != NumOperands; ++OpIdx) {
2211         Operands[OpIdx].resize(NumLanes);
2212         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2213           auto *I = cast<Instruction>(Scalars[Lane]);
2214           assert(I->getNumOperands() == NumOperands &&
2215                  "Expected same number of operands");
2216           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2217         }
2218       }
2219     }
2220 
2221     /// Reorders operands of the node to the given mask \p Mask.
2222     void reorderOperands(ArrayRef<int> Mask) {
2223       for (ValueList &Operand : Operands)
2224         reorderScalars(Operand, Mask);
2225     }
2226 
2227     /// \returns the \p OpIdx operand of this TreeEntry.
2228     ValueList &getOperand(unsigned OpIdx) {
2229       assert(OpIdx < Operands.size() && "Off bounds");
2230       return Operands[OpIdx];
2231     }
2232 
2233     /// \returns the \p OpIdx operand of this TreeEntry.
2234     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2235       assert(OpIdx < Operands.size() && "Off bounds");
2236       return Operands[OpIdx];
2237     }
2238 
2239     /// \returns the number of operands.
2240     unsigned getNumOperands() const { return Operands.size(); }
2241 
2242     /// \return the single \p OpIdx operand.
2243     Value *getSingleOperand(unsigned OpIdx) const {
2244       assert(OpIdx < Operands.size() && "Off bounds");
2245       assert(!Operands[OpIdx].empty() && "No operand available");
2246       return Operands[OpIdx][0];
2247     }
2248 
2249     /// Some of the instructions in the list have alternate opcodes.
2250     bool isAltShuffle() const { return MainOp != AltOp; }
2251 
2252     bool isOpcodeOrAlt(Instruction *I) const {
2253       unsigned CheckedOpcode = I->getOpcode();
2254       return (getOpcode() == CheckedOpcode ||
2255               getAltOpcode() == CheckedOpcode);
2256     }
2257 
2258     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2259     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2260     /// \p OpValue.
2261     Value *isOneOf(Value *Op) const {
2262       auto *I = dyn_cast<Instruction>(Op);
2263       if (I && isOpcodeOrAlt(I))
2264         return Op;
2265       return MainOp;
2266     }
2267 
2268     void setOperations(const InstructionsState &S) {
2269       MainOp = S.MainOp;
2270       AltOp = S.AltOp;
2271     }
2272 
2273     Instruction *getMainOp() const {
2274       return MainOp;
2275     }
2276 
2277     Instruction *getAltOp() const {
2278       return AltOp;
2279     }
2280 
2281     /// The main/alternate opcodes for the list of instructions.
2282     unsigned getOpcode() const {
2283       return MainOp ? MainOp->getOpcode() : 0;
2284     }
2285 
2286     unsigned getAltOpcode() const {
2287       return AltOp ? AltOp->getOpcode() : 0;
2288     }
2289 
2290     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2291     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2292     int findLaneForValue(Value *V) const {
2293       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2294       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2295       if (!ReorderIndices.empty())
2296         FoundLane = ReorderIndices[FoundLane];
2297       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2298       if (!ReuseShuffleIndices.empty()) {
2299         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2300                                   find(ReuseShuffleIndices, FoundLane));
2301       }
2302       return FoundLane;
2303     }
2304 
2305 #ifndef NDEBUG
2306     /// Debug printer.
2307     LLVM_DUMP_METHOD void dump() const {
2308       dbgs() << Idx << ".\n";
2309       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2310         dbgs() << "Operand " << OpI << ":\n";
2311         for (const Value *V : Operands[OpI])
2312           dbgs().indent(2) << *V << "\n";
2313       }
2314       dbgs() << "Scalars: \n";
2315       for (Value *V : Scalars)
2316         dbgs().indent(2) << *V << "\n";
2317       dbgs() << "State: ";
2318       switch (State) {
2319       case Vectorize:
2320         dbgs() << "Vectorize\n";
2321         break;
2322       case ScatterVectorize:
2323         dbgs() << "ScatterVectorize\n";
2324         break;
2325       case NeedToGather:
2326         dbgs() << "NeedToGather\n";
2327         break;
2328       }
2329       dbgs() << "MainOp: ";
2330       if (MainOp)
2331         dbgs() << *MainOp << "\n";
2332       else
2333         dbgs() << "NULL\n";
2334       dbgs() << "AltOp: ";
2335       if (AltOp)
2336         dbgs() << *AltOp << "\n";
2337       else
2338         dbgs() << "NULL\n";
2339       dbgs() << "VectorizedValue: ";
2340       if (VectorizedValue)
2341         dbgs() << *VectorizedValue << "\n";
2342       else
2343         dbgs() << "NULL\n";
2344       dbgs() << "ReuseShuffleIndices: ";
2345       if (ReuseShuffleIndices.empty())
2346         dbgs() << "Empty";
2347       else
2348         for (int ReuseIdx : ReuseShuffleIndices)
2349           dbgs() << ReuseIdx << ", ";
2350       dbgs() << "\n";
2351       dbgs() << "ReorderIndices: ";
2352       for (unsigned ReorderIdx : ReorderIndices)
2353         dbgs() << ReorderIdx << ", ";
2354       dbgs() << "\n";
2355       dbgs() << "UserTreeIndices: ";
2356       for (const auto &EInfo : UserTreeIndices)
2357         dbgs() << EInfo << ", ";
2358       dbgs() << "\n";
2359     }
2360 #endif
2361   };
2362 
2363 #ifndef NDEBUG
2364   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2365                      InstructionCost VecCost,
2366                      InstructionCost ScalarCost) const {
2367     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2368     dbgs() << "SLP: Costs:\n";
2369     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2370     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2371     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2372     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2373                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2374   }
2375 #endif
2376 
2377   /// Create a new VectorizableTree entry.
2378   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2379                           const InstructionsState &S,
2380                           const EdgeInfo &UserTreeIdx,
2381                           ArrayRef<int> ReuseShuffleIndices = None,
2382                           ArrayRef<unsigned> ReorderIndices = None) {
2383     TreeEntry::EntryState EntryState =
2384         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2385     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2386                         ReuseShuffleIndices, ReorderIndices);
2387   }
2388 
2389   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2390                           TreeEntry::EntryState EntryState,
2391                           Optional<ScheduleData *> Bundle,
2392                           const InstructionsState &S,
2393                           const EdgeInfo &UserTreeIdx,
2394                           ArrayRef<int> ReuseShuffleIndices = None,
2395                           ArrayRef<unsigned> ReorderIndices = None) {
2396     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2397             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2398            "Need to vectorize gather entry?");
2399     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2400     TreeEntry *Last = VectorizableTree.back().get();
2401     Last->Idx = VectorizableTree.size() - 1;
2402     Last->State = EntryState;
2403     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2404                                      ReuseShuffleIndices.end());
2405     if (ReorderIndices.empty()) {
2406       Last->Scalars.assign(VL.begin(), VL.end());
2407       Last->setOperations(S);
2408     } else {
2409       // Reorder scalars and build final mask.
2410       Last->Scalars.assign(VL.size(), nullptr);
2411       transform(ReorderIndices, Last->Scalars.begin(),
2412                 [VL](unsigned Idx) -> Value * {
2413                   if (Idx >= VL.size())
2414                     return UndefValue::get(VL.front()->getType());
2415                   return VL[Idx];
2416                 });
2417       InstructionsState S = getSameOpcode(Last->Scalars);
2418       Last->setOperations(S);
2419       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2420     }
2421     if (Last->State != TreeEntry::NeedToGather) {
2422       for (Value *V : VL) {
2423         assert(!getTreeEntry(V) && "Scalar already in tree!");
2424         ScalarToTreeEntry[V] = Last;
2425       }
2426       // Update the scheduler bundle to point to this TreeEntry.
2427       ScheduleData *BundleMember = Bundle.getValue();
2428       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2429               isVectorLikeInstWithConstOps(S.MainOp) ||
2430               doesNotNeedToSchedule(VL)) &&
2431              "Bundle and VL out of sync");
2432       if (BundleMember) {
2433         for (Value *V : VL) {
2434           if (doesNotNeedToBeScheduled(V))
2435             continue;
2436           assert(BundleMember && "Unexpected end of bundle.");
2437           BundleMember->TE = Last;
2438           BundleMember = BundleMember->NextInBundle;
2439         }
2440       }
2441       assert(!BundleMember && "Bundle and VL out of sync");
2442     } else {
2443       MustGather.insert(VL.begin(), VL.end());
2444     }
2445 
2446     if (UserTreeIdx.UserTE)
2447       Last->UserTreeIndices.push_back(UserTreeIdx);
2448 
2449     return Last;
2450   }
2451 
2452   /// -- Vectorization State --
2453   /// Holds all of the tree entries.
2454   TreeEntry::VecTreeTy VectorizableTree;
2455 
2456 #ifndef NDEBUG
2457   /// Debug printer.
2458   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2459     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2460       VectorizableTree[Id]->dump();
2461       dbgs() << "\n";
2462     }
2463   }
2464 #endif
2465 
2466   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2467 
2468   const TreeEntry *getTreeEntry(Value *V) const {
2469     return ScalarToTreeEntry.lookup(V);
2470   }
2471 
2472   /// Maps a specific scalar to its tree entry.
2473   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2474 
2475   /// Maps a value to the proposed vectorizable size.
2476   SmallDenseMap<Value *, unsigned> InstrElementSize;
2477 
2478   /// A list of scalars that we found that we need to keep as scalars.
2479   ValueSet MustGather;
2480 
2481   /// This POD struct describes one external user in the vectorized tree.
2482   struct ExternalUser {
2483     ExternalUser(Value *S, llvm::User *U, int L)
2484         : Scalar(S), User(U), Lane(L) {}
2485 
2486     // Which scalar in our function.
2487     Value *Scalar;
2488 
2489     // Which user that uses the scalar.
2490     llvm::User *User;
2491 
2492     // Which lane does the scalar belong to.
2493     int Lane;
2494   };
2495   using UserList = SmallVector<ExternalUser, 16>;
2496 
2497   /// Checks if two instructions may access the same memory.
2498   ///
2499   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2500   /// is invariant in the calling loop.
2501   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2502                  Instruction *Inst2) {
2503     // First check if the result is already in the cache.
2504     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2505     Optional<bool> &result = AliasCache[key];
2506     if (result.hasValue()) {
2507       return result.getValue();
2508     }
2509     bool aliased = true;
2510     if (Loc1.Ptr && isSimple(Inst1))
2511       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2512     // Store the result in the cache.
2513     result = aliased;
2514     return aliased;
2515   }
2516 
2517   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2518 
2519   /// Cache for alias results.
2520   /// TODO: consider moving this to the AliasAnalysis itself.
2521   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2522 
2523   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2524   // globally through SLP because we don't perform any action which
2525   // invalidates capture results.
2526   BatchAAResults BatchAA;
2527 
2528   /// Temporary store for deleted instructions. Instructions will be deleted
2529   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2530   /// ensure that there are no incorrect collisions in the AliasCache, which
2531   /// can happen if a new instruction is allocated at the same address as a
2532   /// previously deleted instruction.
2533   DenseSet<Instruction *> DeletedInstructions;
2534 
2535   /// A list of values that need to extracted out of the tree.
2536   /// This list holds pairs of (Internal Scalar : External User). External User
2537   /// can be nullptr, it means that this Internal Scalar will be used later,
2538   /// after vectorization.
2539   UserList ExternalUses;
2540 
2541   /// Values used only by @llvm.assume calls.
2542   SmallPtrSet<const Value *, 32> EphValues;
2543 
2544   /// Holds all of the instructions that we gathered.
2545   SetVector<Instruction *> GatherShuffleSeq;
2546 
2547   /// A list of blocks that we are going to CSE.
2548   SetVector<BasicBlock *> CSEBlocks;
2549 
2550   /// Contains all scheduling relevant data for an instruction.
2551   /// A ScheduleData either represents a single instruction or a member of an
2552   /// instruction bundle (= a group of instructions which is combined into a
2553   /// vector instruction).
2554   struct ScheduleData {
2555     // The initial value for the dependency counters. It means that the
2556     // dependencies are not calculated yet.
2557     enum { InvalidDeps = -1 };
2558 
2559     ScheduleData() = default;
2560 
2561     void init(int BlockSchedulingRegionID, Value *OpVal) {
2562       FirstInBundle = this;
2563       NextInBundle = nullptr;
2564       NextLoadStore = nullptr;
2565       IsScheduled = false;
2566       SchedulingRegionID = BlockSchedulingRegionID;
2567       clearDependencies();
2568       OpValue = OpVal;
2569       TE = nullptr;
2570     }
2571 
2572     /// Verify basic self consistency properties
2573     void verify() {
2574       if (hasValidDependencies()) {
2575         assert(UnscheduledDeps <= Dependencies && "invariant");
2576       } else {
2577         assert(UnscheduledDeps == Dependencies && "invariant");
2578       }
2579 
2580       if (IsScheduled) {
2581         assert(isSchedulingEntity() &&
2582                 "unexpected scheduled state");
2583         for (const ScheduleData *BundleMember = this; BundleMember;
2584              BundleMember = BundleMember->NextInBundle) {
2585           assert(BundleMember->hasValidDependencies() &&
2586                  BundleMember->UnscheduledDeps == 0 &&
2587                  "unexpected scheduled state");
2588           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2589                  "only bundle is marked scheduled");
2590         }
2591       }
2592 
2593       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2594              "all bundle members must be in same basic block");
2595     }
2596 
2597     /// Returns true if the dependency information has been calculated.
2598     /// Note that depenendency validity can vary between instructions within
2599     /// a single bundle.
2600     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2601 
2602     /// Returns true for single instructions and for bundle representatives
2603     /// (= the head of a bundle).
2604     bool isSchedulingEntity() const { return FirstInBundle == this; }
2605 
2606     /// Returns true if it represents an instruction bundle and not only a
2607     /// single instruction.
2608     bool isPartOfBundle() const {
2609       return NextInBundle != nullptr || FirstInBundle != this || TE;
2610     }
2611 
2612     /// Returns true if it is ready for scheduling, i.e. it has no more
2613     /// unscheduled depending instructions/bundles.
2614     bool isReady() const {
2615       assert(isSchedulingEntity() &&
2616              "can't consider non-scheduling entity for ready list");
2617       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2618     }
2619 
2620     /// Modifies the number of unscheduled dependencies for this instruction,
2621     /// and returns the number of remaining dependencies for the containing
2622     /// bundle.
2623     int incrementUnscheduledDeps(int Incr) {
2624       assert(hasValidDependencies() &&
2625              "increment of unscheduled deps would be meaningless");
2626       UnscheduledDeps += Incr;
2627       return FirstInBundle->unscheduledDepsInBundle();
2628     }
2629 
2630     /// Sets the number of unscheduled dependencies to the number of
2631     /// dependencies.
2632     void resetUnscheduledDeps() {
2633       UnscheduledDeps = Dependencies;
2634     }
2635 
2636     /// Clears all dependency information.
2637     void clearDependencies() {
2638       Dependencies = InvalidDeps;
2639       resetUnscheduledDeps();
2640       MemoryDependencies.clear();
2641       ControlDependencies.clear();
2642     }
2643 
2644     int unscheduledDepsInBundle() const {
2645       assert(isSchedulingEntity() && "only meaningful on the bundle");
2646       int Sum = 0;
2647       for (const ScheduleData *BundleMember = this; BundleMember;
2648            BundleMember = BundleMember->NextInBundle) {
2649         if (BundleMember->UnscheduledDeps == InvalidDeps)
2650           return InvalidDeps;
2651         Sum += BundleMember->UnscheduledDeps;
2652       }
2653       return Sum;
2654     }
2655 
2656     void dump(raw_ostream &os) const {
2657       if (!isSchedulingEntity()) {
2658         os << "/ " << *Inst;
2659       } else if (NextInBundle) {
2660         os << '[' << *Inst;
2661         ScheduleData *SD = NextInBundle;
2662         while (SD) {
2663           os << ';' << *SD->Inst;
2664           SD = SD->NextInBundle;
2665         }
2666         os << ']';
2667       } else {
2668         os << *Inst;
2669       }
2670     }
2671 
2672     Instruction *Inst = nullptr;
2673 
2674     /// Opcode of the current instruction in the schedule data.
2675     Value *OpValue = nullptr;
2676 
2677     /// The TreeEntry that this instruction corresponds to.
2678     TreeEntry *TE = nullptr;
2679 
2680     /// Points to the head in an instruction bundle (and always to this for
2681     /// single instructions).
2682     ScheduleData *FirstInBundle = nullptr;
2683 
2684     /// Single linked list of all instructions in a bundle. Null if it is a
2685     /// single instruction.
2686     ScheduleData *NextInBundle = nullptr;
2687 
2688     /// Single linked list of all memory instructions (e.g. load, store, call)
2689     /// in the block - until the end of the scheduling region.
2690     ScheduleData *NextLoadStore = nullptr;
2691 
2692     /// The dependent memory instructions.
2693     /// This list is derived on demand in calculateDependencies().
2694     SmallVector<ScheduleData *, 4> MemoryDependencies;
2695 
2696     /// List of instructions which this instruction could be control dependent
2697     /// on.  Allowing such nodes to be scheduled below this one could introduce
2698     /// a runtime fault which didn't exist in the original program.
2699     /// ex: this is a load or udiv following a readonly call which inf loops
2700     SmallVector<ScheduleData *, 4> ControlDependencies;
2701 
2702     /// This ScheduleData is in the current scheduling region if this matches
2703     /// the current SchedulingRegionID of BlockScheduling.
2704     int SchedulingRegionID = 0;
2705 
2706     /// Used for getting a "good" final ordering of instructions.
2707     int SchedulingPriority = 0;
2708 
2709     /// The number of dependencies. Constitutes of the number of users of the
2710     /// instruction plus the number of dependent memory instructions (if any).
2711     /// This value is calculated on demand.
2712     /// If InvalidDeps, the number of dependencies is not calculated yet.
2713     int Dependencies = InvalidDeps;
2714 
2715     /// The number of dependencies minus the number of dependencies of scheduled
2716     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2717     /// for scheduling.
2718     /// Note that this is negative as long as Dependencies is not calculated.
2719     int UnscheduledDeps = InvalidDeps;
2720 
2721     /// True if this instruction is scheduled (or considered as scheduled in the
2722     /// dry-run).
2723     bool IsScheduled = false;
2724   };
2725 
2726 #ifndef NDEBUG
2727   friend inline raw_ostream &operator<<(raw_ostream &os,
2728                                         const BoUpSLP::ScheduleData &SD) {
2729     SD.dump(os);
2730     return os;
2731   }
2732 #endif
2733 
2734   friend struct GraphTraits<BoUpSLP *>;
2735   friend struct DOTGraphTraits<BoUpSLP *>;
2736 
2737   /// Contains all scheduling data for a basic block.
2738   /// It does not schedules instructions, which are not memory read/write
2739   /// instructions and their operands are either constants, or arguments, or
2740   /// phis, or instructions from others blocks, or their users are phis or from
2741   /// the other blocks. The resulting vector instructions can be placed at the
2742   /// beginning of the basic block without scheduling (if operands does not need
2743   /// to be scheduled) or at the end of the block (if users are outside of the
2744   /// block). It allows to save some compile time and memory used by the
2745   /// compiler.
2746   /// ScheduleData is assigned for each instruction in between the boundaries of
2747   /// the tree entry, even for those, which are not part of the graph. It is
2748   /// required to correctly follow the dependencies between the instructions and
2749   /// their correct scheduling. The ScheduleData is not allocated for the
2750   /// instructions, which do not require scheduling, like phis, nodes with
2751   /// extractelements/insertelements only or nodes with instructions, with
2752   /// uses/operands outside of the block.
2753   struct BlockScheduling {
2754     BlockScheduling(BasicBlock *BB)
2755         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2756 
2757     void clear() {
2758       ReadyInsts.clear();
2759       ScheduleStart = nullptr;
2760       ScheduleEnd = nullptr;
2761       FirstLoadStoreInRegion = nullptr;
2762       LastLoadStoreInRegion = nullptr;
2763       RegionHasStackSave = false;
2764 
2765       // Reduce the maximum schedule region size by the size of the
2766       // previous scheduling run.
2767       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2768       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2769         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2770       ScheduleRegionSize = 0;
2771 
2772       // Make a new scheduling region, i.e. all existing ScheduleData is not
2773       // in the new region yet.
2774       ++SchedulingRegionID;
2775     }
2776 
2777     ScheduleData *getScheduleData(Instruction *I) {
2778       if (BB != I->getParent())
2779         // Avoid lookup if can't possibly be in map.
2780         return nullptr;
2781       ScheduleData *SD = ScheduleDataMap.lookup(I);
2782       if (SD && isInSchedulingRegion(SD))
2783         return SD;
2784       return nullptr;
2785     }
2786 
2787     ScheduleData *getScheduleData(Value *V) {
2788       if (auto *I = dyn_cast<Instruction>(V))
2789         return getScheduleData(I);
2790       return nullptr;
2791     }
2792 
2793     ScheduleData *getScheduleData(Value *V, Value *Key) {
2794       if (V == Key)
2795         return getScheduleData(V);
2796       auto I = ExtraScheduleDataMap.find(V);
2797       if (I != ExtraScheduleDataMap.end()) {
2798         ScheduleData *SD = I->second.lookup(Key);
2799         if (SD && isInSchedulingRegion(SD))
2800           return SD;
2801       }
2802       return nullptr;
2803     }
2804 
2805     bool isInSchedulingRegion(ScheduleData *SD) const {
2806       return SD->SchedulingRegionID == SchedulingRegionID;
2807     }
2808 
2809     /// Marks an instruction as scheduled and puts all dependent ready
2810     /// instructions into the ready-list.
2811     template <typename ReadyListType>
2812     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2813       SD->IsScheduled = true;
2814       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2815 
2816       for (ScheduleData *BundleMember = SD; BundleMember;
2817            BundleMember = BundleMember->NextInBundle) {
2818         if (BundleMember->Inst != BundleMember->OpValue)
2819           continue;
2820 
2821         // Handle the def-use chain dependencies.
2822 
2823         // Decrement the unscheduled counter and insert to ready list if ready.
2824         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2825           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2826             if (OpDef && OpDef->hasValidDependencies() &&
2827                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2828               // There are no more unscheduled dependencies after
2829               // decrementing, so we can put the dependent instruction
2830               // into the ready list.
2831               ScheduleData *DepBundle = OpDef->FirstInBundle;
2832               assert(!DepBundle->IsScheduled &&
2833                      "already scheduled bundle gets ready");
2834               ReadyList.insert(DepBundle);
2835               LLVM_DEBUG(dbgs()
2836                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2837             }
2838           });
2839         };
2840 
2841         // If BundleMember is a vector bundle, its operands may have been
2842         // reordered during buildTree(). We therefore need to get its operands
2843         // through the TreeEntry.
2844         if (TreeEntry *TE = BundleMember->TE) {
2845           // Need to search for the lane since the tree entry can be reordered.
2846           int Lane = std::distance(TE->Scalars.begin(),
2847                                    find(TE->Scalars, BundleMember->Inst));
2848           assert(Lane >= 0 && "Lane not set");
2849 
2850           // Since vectorization tree is being built recursively this assertion
2851           // ensures that the tree entry has all operands set before reaching
2852           // this code. Couple of exceptions known at the moment are extracts
2853           // where their second (immediate) operand is not added. Since
2854           // immediates do not affect scheduler behavior this is considered
2855           // okay.
2856           auto *In = BundleMember->Inst;
2857           assert(In &&
2858                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2859                   In->getNumOperands() == TE->getNumOperands()) &&
2860                  "Missed TreeEntry operands?");
2861           (void)In; // fake use to avoid build failure when assertions disabled
2862 
2863           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2864                OpIdx != NumOperands; ++OpIdx)
2865             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2866               DecrUnsched(I);
2867         } else {
2868           // If BundleMember is a stand-alone instruction, no operand reordering
2869           // has taken place, so we directly access its operands.
2870           for (Use &U : BundleMember->Inst->operands())
2871             if (auto *I = dyn_cast<Instruction>(U.get()))
2872               DecrUnsched(I);
2873         }
2874         // Handle the memory dependencies.
2875         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2876           if (MemoryDepSD->hasValidDependencies() &&
2877               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2878             // There are no more unscheduled dependencies after decrementing,
2879             // so we can put the dependent instruction into the ready list.
2880             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2881             assert(!DepBundle->IsScheduled &&
2882                    "already scheduled bundle gets ready");
2883             ReadyList.insert(DepBundle);
2884             LLVM_DEBUG(dbgs()
2885                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2886           }
2887         }
2888         // Handle the control dependencies.
2889         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2890           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2891             // There are no more unscheduled dependencies after decrementing,
2892             // so we can put the dependent instruction into the ready list.
2893             ScheduleData *DepBundle = DepSD->FirstInBundle;
2894             assert(!DepBundle->IsScheduled &&
2895                    "already scheduled bundle gets ready");
2896             ReadyList.insert(DepBundle);
2897             LLVM_DEBUG(dbgs()
2898                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2899           }
2900         }
2901 
2902       }
2903     }
2904 
2905     /// Verify basic self consistency properties of the data structure.
2906     void verify() {
2907       if (!ScheduleStart)
2908         return;
2909 
2910       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2911              ScheduleStart->comesBefore(ScheduleEnd) &&
2912              "Not a valid scheduling region?");
2913 
2914       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2915         auto *SD = getScheduleData(I);
2916         if (!SD)
2917           continue;
2918         assert(isInSchedulingRegion(SD) &&
2919                "primary schedule data not in window?");
2920         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2921                "entire bundle in window!");
2922         (void)SD;
2923         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2924       }
2925 
2926       for (auto *SD : ReadyInsts) {
2927         assert(SD->isSchedulingEntity() && SD->isReady() &&
2928                "item in ready list not ready?");
2929         (void)SD;
2930       }
2931     }
2932 
2933     void doForAllOpcodes(Value *V,
2934                          function_ref<void(ScheduleData *SD)> Action) {
2935       if (ScheduleData *SD = getScheduleData(V))
2936         Action(SD);
2937       auto I = ExtraScheduleDataMap.find(V);
2938       if (I != ExtraScheduleDataMap.end())
2939         for (auto &P : I->second)
2940           if (isInSchedulingRegion(P.second))
2941             Action(P.second);
2942     }
2943 
2944     /// Put all instructions into the ReadyList which are ready for scheduling.
2945     template <typename ReadyListType>
2946     void initialFillReadyList(ReadyListType &ReadyList) {
2947       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2948         doForAllOpcodes(I, [&](ScheduleData *SD) {
2949           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2950               SD->isReady()) {
2951             ReadyList.insert(SD);
2952             LLVM_DEBUG(dbgs()
2953                        << "SLP:    initially in ready list: " << *SD << "\n");
2954           }
2955         });
2956       }
2957     }
2958 
2959     /// Build a bundle from the ScheduleData nodes corresponding to the
2960     /// scalar instruction for each lane.
2961     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2962 
2963     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2964     /// cyclic dependencies. This is only a dry-run, no instructions are
2965     /// actually moved at this stage.
2966     /// \returns the scheduling bundle. The returned Optional value is non-None
2967     /// if \p VL is allowed to be scheduled.
2968     Optional<ScheduleData *>
2969     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2970                       const InstructionsState &S);
2971 
2972     /// Un-bundles a group of instructions.
2973     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2974 
2975     /// Allocates schedule data chunk.
2976     ScheduleData *allocateScheduleDataChunks();
2977 
2978     /// Extends the scheduling region so that V is inside the region.
2979     /// \returns true if the region size is within the limit.
2980     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2981 
2982     /// Initialize the ScheduleData structures for new instructions in the
2983     /// scheduling region.
2984     void initScheduleData(Instruction *FromI, Instruction *ToI,
2985                           ScheduleData *PrevLoadStore,
2986                           ScheduleData *NextLoadStore);
2987 
2988     /// Updates the dependency information of a bundle and of all instructions/
2989     /// bundles which depend on the original bundle.
2990     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2991                                BoUpSLP *SLP);
2992 
2993     /// Sets all instruction in the scheduling region to un-scheduled.
2994     void resetSchedule();
2995 
2996     BasicBlock *BB;
2997 
2998     /// Simple memory allocation for ScheduleData.
2999     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3000 
3001     /// The size of a ScheduleData array in ScheduleDataChunks.
3002     int ChunkSize;
3003 
3004     /// The allocator position in the current chunk, which is the last entry
3005     /// of ScheduleDataChunks.
3006     int ChunkPos;
3007 
3008     /// Attaches ScheduleData to Instruction.
3009     /// Note that the mapping survives during all vectorization iterations, i.e.
3010     /// ScheduleData structures are recycled.
3011     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3012 
3013     /// Attaches ScheduleData to Instruction with the leading key.
3014     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3015         ExtraScheduleDataMap;
3016 
3017     /// The ready-list for scheduling (only used for the dry-run).
3018     SetVector<ScheduleData *> ReadyInsts;
3019 
3020     /// The first instruction of the scheduling region.
3021     Instruction *ScheduleStart = nullptr;
3022 
3023     /// The first instruction _after_ the scheduling region.
3024     Instruction *ScheduleEnd = nullptr;
3025 
3026     /// The first memory accessing instruction in the scheduling region
3027     /// (can be null).
3028     ScheduleData *FirstLoadStoreInRegion = nullptr;
3029 
3030     /// The last memory accessing instruction in the scheduling region
3031     /// (can be null).
3032     ScheduleData *LastLoadStoreInRegion = nullptr;
3033 
3034     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3035     /// region?  Used to optimize the dependence calculation for the
3036     /// common case where there isn't.
3037     bool RegionHasStackSave = false;
3038 
3039     /// The current size of the scheduling region.
3040     int ScheduleRegionSize = 0;
3041 
3042     /// The maximum size allowed for the scheduling region.
3043     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3044 
3045     /// The ID of the scheduling region. For a new vectorization iteration this
3046     /// is incremented which "removes" all ScheduleData from the region.
3047     /// Make sure that the initial SchedulingRegionID is greater than the
3048     /// initial SchedulingRegionID in ScheduleData (which is 0).
3049     int SchedulingRegionID = 1;
3050   };
3051 
3052   /// Attaches the BlockScheduling structures to basic blocks.
3053   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3054 
3055   /// Performs the "real" scheduling. Done before vectorization is actually
3056   /// performed in a basic block.
3057   void scheduleBlock(BlockScheduling *BS);
3058 
3059   /// List of users to ignore during scheduling and that don't need extracting.
3060   ArrayRef<Value *> UserIgnoreList;
3061 
3062   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3063   /// sorted SmallVectors of unsigned.
3064   struct OrdersTypeDenseMapInfo {
3065     static OrdersType getEmptyKey() {
3066       OrdersType V;
3067       V.push_back(~1U);
3068       return V;
3069     }
3070 
3071     static OrdersType getTombstoneKey() {
3072       OrdersType V;
3073       V.push_back(~2U);
3074       return V;
3075     }
3076 
3077     static unsigned getHashValue(const OrdersType &V) {
3078       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3079     }
3080 
3081     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3082       return LHS == RHS;
3083     }
3084   };
3085 
3086   // Analysis and block reference.
3087   Function *F;
3088   ScalarEvolution *SE;
3089   TargetTransformInfo *TTI;
3090   TargetLibraryInfo *TLI;
3091   LoopInfo *LI;
3092   DominatorTree *DT;
3093   AssumptionCache *AC;
3094   DemandedBits *DB;
3095   const DataLayout *DL;
3096   OptimizationRemarkEmitter *ORE;
3097 
3098   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3099   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3100 
3101   /// Instruction builder to construct the vectorized tree.
3102   IRBuilder<> Builder;
3103 
3104   /// A map of scalar integer values to the smallest bit width with which they
3105   /// can legally be represented. The values map to (width, signed) pairs,
3106   /// where "width" indicates the minimum bit width and "signed" is True if the
3107   /// value must be signed-extended, rather than zero-extended, back to its
3108   /// original width.
3109   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3110 };
3111 
3112 } // end namespace slpvectorizer
3113 
3114 template <> struct GraphTraits<BoUpSLP *> {
3115   using TreeEntry = BoUpSLP::TreeEntry;
3116 
3117   /// NodeRef has to be a pointer per the GraphWriter.
3118   using NodeRef = TreeEntry *;
3119 
3120   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3121 
3122   /// Add the VectorizableTree to the index iterator to be able to return
3123   /// TreeEntry pointers.
3124   struct ChildIteratorType
3125       : public iterator_adaptor_base<
3126             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3127     ContainerTy &VectorizableTree;
3128 
3129     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3130                       ContainerTy &VT)
3131         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3132 
3133     NodeRef operator*() { return I->UserTE; }
3134   };
3135 
3136   static NodeRef getEntryNode(BoUpSLP &R) {
3137     return R.VectorizableTree[0].get();
3138   }
3139 
3140   static ChildIteratorType child_begin(NodeRef N) {
3141     return {N->UserTreeIndices.begin(), N->Container};
3142   }
3143 
3144   static ChildIteratorType child_end(NodeRef N) {
3145     return {N->UserTreeIndices.end(), N->Container};
3146   }
3147 
3148   /// For the node iterator we just need to turn the TreeEntry iterator into a
3149   /// TreeEntry* iterator so that it dereferences to NodeRef.
3150   class nodes_iterator {
3151     using ItTy = ContainerTy::iterator;
3152     ItTy It;
3153 
3154   public:
3155     nodes_iterator(const ItTy &It2) : It(It2) {}
3156     NodeRef operator*() { return It->get(); }
3157     nodes_iterator operator++() {
3158       ++It;
3159       return *this;
3160     }
3161     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3162   };
3163 
3164   static nodes_iterator nodes_begin(BoUpSLP *R) {
3165     return nodes_iterator(R->VectorizableTree.begin());
3166   }
3167 
3168   static nodes_iterator nodes_end(BoUpSLP *R) {
3169     return nodes_iterator(R->VectorizableTree.end());
3170   }
3171 
3172   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3173 };
3174 
3175 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3176   using TreeEntry = BoUpSLP::TreeEntry;
3177 
3178   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3179 
3180   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3181     std::string Str;
3182     raw_string_ostream OS(Str);
3183     if (isSplat(Entry->Scalars))
3184       OS << "<splat> ";
3185     for (auto V : Entry->Scalars) {
3186       OS << *V;
3187       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3188             return EU.Scalar == V;
3189           }))
3190         OS << " <extract>";
3191       OS << "\n";
3192     }
3193     return Str;
3194   }
3195 
3196   static std::string getNodeAttributes(const TreeEntry *Entry,
3197                                        const BoUpSLP *) {
3198     if (Entry->State == TreeEntry::NeedToGather)
3199       return "color=red";
3200     return "";
3201   }
3202 };
3203 
3204 } // end namespace llvm
3205 
3206 BoUpSLP::~BoUpSLP() {
3207   SmallVector<WeakTrackingVH> DeadInsts;
3208   for (auto *I : DeletedInstructions) {
3209     for (Use &U : I->operands()) {
3210       auto *Op = dyn_cast<Instruction>(U.get());
3211       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3212           wouldInstructionBeTriviallyDead(Op, TLI))
3213         DeadInsts.emplace_back(Op);
3214     }
3215     I->dropAllReferences();
3216   }
3217   for (auto *I : DeletedInstructions) {
3218     assert(I->use_empty() &&
3219            "trying to erase instruction with users.");
3220     I->eraseFromParent();
3221   }
3222 
3223   // Cleanup any dead scalar code feeding the vectorized instructions
3224   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3225 
3226 #ifdef EXPENSIVE_CHECKS
3227   // If we could guarantee that this call is not extremely slow, we could
3228   // remove the ifdef limitation (see PR47712).
3229   assert(!verifyFunction(*F, &dbgs()));
3230 #endif
3231 }
3232 
3233 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3234 /// contains original mask for the scalars reused in the node. Procedure
3235 /// transform this mask in accordance with the given \p Mask.
3236 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3237   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3238          "Expected non-empty mask.");
3239   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3240   Prev.swap(Reuses);
3241   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3242     if (Mask[I] != UndefMaskElem)
3243       Reuses[Mask[I]] = Prev[I];
3244 }
3245 
3246 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3247 /// the original order of the scalars. Procedure transforms the provided order
3248 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3249 /// identity order, \p Order is cleared.
3250 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3251   assert(!Mask.empty() && "Expected non-empty mask.");
3252   SmallVector<int> MaskOrder;
3253   if (Order.empty()) {
3254     MaskOrder.resize(Mask.size());
3255     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3256   } else {
3257     inversePermutation(Order, MaskOrder);
3258   }
3259   reorderReuses(MaskOrder, Mask);
3260   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3261     Order.clear();
3262     return;
3263   }
3264   Order.assign(Mask.size(), Mask.size());
3265   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3266     if (MaskOrder[I] != UndefMaskElem)
3267       Order[MaskOrder[I]] = I;
3268   fixupOrderingIndices(Order);
3269 }
3270 
3271 Optional<BoUpSLP::OrdersType>
3272 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3273   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3274   unsigned NumScalars = TE.Scalars.size();
3275   OrdersType CurrentOrder(NumScalars, NumScalars);
3276   SmallVector<int> Positions;
3277   SmallBitVector UsedPositions(NumScalars);
3278   const TreeEntry *STE = nullptr;
3279   // Try to find all gathered scalars that are gets vectorized in other
3280   // vectorize node. Here we can have only one single tree vector node to
3281   // correctly identify order of the gathered scalars.
3282   for (unsigned I = 0; I < NumScalars; ++I) {
3283     Value *V = TE.Scalars[I];
3284     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3285       continue;
3286     if (const auto *LocalSTE = getTreeEntry(V)) {
3287       if (!STE)
3288         STE = LocalSTE;
3289       else if (STE != LocalSTE)
3290         // Take the order only from the single vector node.
3291         return None;
3292       unsigned Lane =
3293           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3294       if (Lane >= NumScalars)
3295         return None;
3296       if (CurrentOrder[Lane] != NumScalars) {
3297         if (Lane != I)
3298           continue;
3299         UsedPositions.reset(CurrentOrder[Lane]);
3300       }
3301       // The partial identity (where only some elements of the gather node are
3302       // in the identity order) is good.
3303       CurrentOrder[Lane] = I;
3304       UsedPositions.set(I);
3305     }
3306   }
3307   // Need to keep the order if we have a vector entry and at least 2 scalars or
3308   // the vectorized entry has just 2 scalars.
3309   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3310     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3311       for (unsigned I = 0; I < NumScalars; ++I)
3312         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3313           return false;
3314       return true;
3315     };
3316     if (IsIdentityOrder(CurrentOrder)) {
3317       CurrentOrder.clear();
3318       return CurrentOrder;
3319     }
3320     auto *It = CurrentOrder.begin();
3321     for (unsigned I = 0; I < NumScalars;) {
3322       if (UsedPositions.test(I)) {
3323         ++I;
3324         continue;
3325       }
3326       if (*It == NumScalars) {
3327         *It = I;
3328         ++I;
3329       }
3330       ++It;
3331     }
3332     return CurrentOrder;
3333   }
3334   return None;
3335 }
3336 
3337 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3338                                                          bool TopToBottom) {
3339   // No need to reorder if need to shuffle reuses, still need to shuffle the
3340   // node.
3341   if (!TE.ReuseShuffleIndices.empty())
3342     return None;
3343   if (TE.State == TreeEntry::Vectorize &&
3344       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3345        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3346       !TE.isAltShuffle())
3347     return TE.ReorderIndices;
3348   if (TE.State == TreeEntry::NeedToGather) {
3349     // TODO: add analysis of other gather nodes with extractelement
3350     // instructions and other values/instructions, not only undefs.
3351     if (((TE.getOpcode() == Instruction::ExtractElement &&
3352           !TE.isAltShuffle()) ||
3353          (all_of(TE.Scalars,
3354                  [](Value *V) {
3355                    return isa<UndefValue, ExtractElementInst>(V);
3356                  }) &&
3357           any_of(TE.Scalars,
3358                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3359         all_of(TE.Scalars,
3360                [](Value *V) {
3361                  auto *EE = dyn_cast<ExtractElementInst>(V);
3362                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3363                }) &&
3364         allSameType(TE.Scalars)) {
3365       // Check that gather of extractelements can be represented as
3366       // just a shuffle of a single vector.
3367       OrdersType CurrentOrder;
3368       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3369       if (Reuse || !CurrentOrder.empty()) {
3370         if (!CurrentOrder.empty())
3371           fixupOrderingIndices(CurrentOrder);
3372         return CurrentOrder;
3373       }
3374     }
3375     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3376       return CurrentOrder;
3377   }
3378   return None;
3379 }
3380 
3381 void BoUpSLP::reorderTopToBottom() {
3382   // Maps VF to the graph nodes.
3383   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3384   // ExtractElement gather nodes which can be vectorized and need to handle
3385   // their ordering.
3386   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3387   // Find all reorderable nodes with the given VF.
3388   // Currently the are vectorized stores,loads,extracts + some gathering of
3389   // extracts.
3390   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3391                                  const std::unique_ptr<TreeEntry> &TE) {
3392     if (Optional<OrdersType> CurrentOrder =
3393             getReorderingData(*TE, /*TopToBottom=*/true)) {
3394       // Do not include ordering for nodes used in the alt opcode vectorization,
3395       // better to reorder them during bottom-to-top stage. If follow the order
3396       // here, it causes reordering of the whole graph though actually it is
3397       // profitable just to reorder the subgraph that starts from the alternate
3398       // opcode vectorization node. Such nodes already end-up with the shuffle
3399       // instruction and it is just enough to change this shuffle rather than
3400       // rotate the scalars for the whole graph.
3401       unsigned Cnt = 0;
3402       const TreeEntry *UserTE = TE.get();
3403       while (UserTE && Cnt < RecursionMaxDepth) {
3404         if (UserTE->UserTreeIndices.size() != 1)
3405           break;
3406         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3407               return EI.UserTE->State == TreeEntry::Vectorize &&
3408                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3409             }))
3410           return;
3411         if (UserTE->UserTreeIndices.empty())
3412           UserTE = nullptr;
3413         else
3414           UserTE = UserTE->UserTreeIndices.back().UserTE;
3415         ++Cnt;
3416       }
3417       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3418       if (TE->State != TreeEntry::Vectorize)
3419         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3420     }
3421   });
3422 
3423   // Reorder the graph nodes according to their vectorization factor.
3424   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3425        VF /= 2) {
3426     auto It = VFToOrderedEntries.find(VF);
3427     if (It == VFToOrderedEntries.end())
3428       continue;
3429     // Try to find the most profitable order. We just are looking for the most
3430     // used order and reorder scalar elements in the nodes according to this
3431     // mostly used order.
3432     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3433     // All operands are reordered and used only in this node - propagate the
3434     // most used order to the user node.
3435     MapVector<OrdersType, unsigned,
3436               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3437         OrdersUses;
3438     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3439     for (const TreeEntry *OpTE : OrderedEntries) {
3440       // No need to reorder this nodes, still need to extend and to use shuffle,
3441       // just need to merge reordering shuffle and the reuse shuffle.
3442       if (!OpTE->ReuseShuffleIndices.empty())
3443         continue;
3444       // Count number of orders uses.
3445       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3446         if (OpTE->State == TreeEntry::NeedToGather)
3447           return GathersToOrders.find(OpTE)->second;
3448         return OpTE->ReorderIndices;
3449       }();
3450       // Stores actually store the mask, not the order, need to invert.
3451       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3452           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3453         SmallVector<int> Mask;
3454         inversePermutation(Order, Mask);
3455         unsigned E = Order.size();
3456         OrdersType CurrentOrder(E, E);
3457         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3458           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3459         });
3460         fixupOrderingIndices(CurrentOrder);
3461         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3462       } else {
3463         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3464       }
3465     }
3466     // Set order of the user node.
3467     if (OrdersUses.empty())
3468       continue;
3469     // Choose the most used order.
3470     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3471     unsigned Cnt = OrdersUses.front().second;
3472     for (const auto &Pair : drop_begin(OrdersUses)) {
3473       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3474         BestOrder = Pair.first;
3475         Cnt = Pair.second;
3476       }
3477     }
3478     // Set order of the user node.
3479     if (BestOrder.empty())
3480       continue;
3481     SmallVector<int> Mask;
3482     inversePermutation(BestOrder, Mask);
3483     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3484     unsigned E = BestOrder.size();
3485     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3486       return I < E ? static_cast<int>(I) : UndefMaskElem;
3487     });
3488     // Do an actual reordering, if profitable.
3489     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3490       // Just do the reordering for the nodes with the given VF.
3491       if (TE->Scalars.size() != VF) {
3492         if (TE->ReuseShuffleIndices.size() == VF) {
3493           // Need to reorder the reuses masks of the operands with smaller VF to
3494           // be able to find the match between the graph nodes and scalar
3495           // operands of the given node during vectorization/cost estimation.
3496           assert(all_of(TE->UserTreeIndices,
3497                         [VF, &TE](const EdgeInfo &EI) {
3498                           return EI.UserTE->Scalars.size() == VF ||
3499                                  EI.UserTE->Scalars.size() ==
3500                                      TE->Scalars.size();
3501                         }) &&
3502                  "All users must be of VF size.");
3503           // Update ordering of the operands with the smaller VF than the given
3504           // one.
3505           reorderReuses(TE->ReuseShuffleIndices, Mask);
3506         }
3507         continue;
3508       }
3509       if (TE->State == TreeEntry::Vectorize &&
3510           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3511               InsertElementInst>(TE->getMainOp()) &&
3512           !TE->isAltShuffle()) {
3513         // Build correct orders for extract{element,value}, loads and
3514         // stores.
3515         reorderOrder(TE->ReorderIndices, Mask);
3516         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3517           TE->reorderOperands(Mask);
3518       } else {
3519         // Reorder the node and its operands.
3520         TE->reorderOperands(Mask);
3521         assert(TE->ReorderIndices.empty() &&
3522                "Expected empty reorder sequence.");
3523         reorderScalars(TE->Scalars, Mask);
3524       }
3525       if (!TE->ReuseShuffleIndices.empty()) {
3526         // Apply reversed order to keep the original ordering of the reused
3527         // elements to avoid extra reorder indices shuffling.
3528         OrdersType CurrentOrder;
3529         reorderOrder(CurrentOrder, MaskOrder);
3530         SmallVector<int> NewReuses;
3531         inversePermutation(CurrentOrder, NewReuses);
3532         addMask(NewReuses, TE->ReuseShuffleIndices);
3533         TE->ReuseShuffleIndices.swap(NewReuses);
3534       }
3535     }
3536   }
3537 }
3538 
3539 bool BoUpSLP::canReorderOperands(
3540     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3541     ArrayRef<TreeEntry *> ReorderableGathers,
3542     SmallVectorImpl<TreeEntry *> &GatherOps) {
3543   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3544     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3545           return OpData.first == I &&
3546                  OpData.second->State == TreeEntry::Vectorize;
3547         }))
3548       continue;
3549     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3550       // Do not reorder if operand node is used by many user nodes.
3551       if (any_of(TE->UserTreeIndices,
3552                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3553         return false;
3554       // Add the node to the list of the ordered nodes with the identity
3555       // order.
3556       Edges.emplace_back(I, TE);
3557       continue;
3558     }
3559     ArrayRef<Value *> VL = UserTE->getOperand(I);
3560     TreeEntry *Gather = nullptr;
3561     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3562           assert(TE->State != TreeEntry::Vectorize &&
3563                  "Only non-vectorized nodes are expected.");
3564           if (TE->isSame(VL)) {
3565             Gather = TE;
3566             return true;
3567           }
3568           return false;
3569         }) > 1)
3570       return false;
3571     if (Gather)
3572       GatherOps.push_back(Gather);
3573   }
3574   return true;
3575 }
3576 
3577 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3578   SetVector<TreeEntry *> OrderedEntries;
3579   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3580   // Find all reorderable leaf nodes with the given VF.
3581   // Currently the are vectorized loads,extracts without alternate operands +
3582   // some gathering of extracts.
3583   SmallVector<TreeEntry *> NonVectorized;
3584   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3585                               &NonVectorized](
3586                                  const std::unique_ptr<TreeEntry> &TE) {
3587     if (TE->State != TreeEntry::Vectorize)
3588       NonVectorized.push_back(TE.get());
3589     if (Optional<OrdersType> CurrentOrder =
3590             getReorderingData(*TE, /*TopToBottom=*/false)) {
3591       OrderedEntries.insert(TE.get());
3592       if (TE->State != TreeEntry::Vectorize)
3593         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3594     }
3595   });
3596 
3597   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3598   // I.e., if the node has operands, that are reordered, try to make at least
3599   // one operand order in the natural order and reorder others + reorder the
3600   // user node itself.
3601   SmallPtrSet<const TreeEntry *, 4> Visited;
3602   while (!OrderedEntries.empty()) {
3603     // 1. Filter out only reordered nodes.
3604     // 2. If the entry has multiple uses - skip it and jump to the next node.
3605     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3606     SmallVector<TreeEntry *> Filtered;
3607     for (TreeEntry *TE : OrderedEntries) {
3608       if (!(TE->State == TreeEntry::Vectorize ||
3609             (TE->State == TreeEntry::NeedToGather &&
3610              GathersToOrders.count(TE))) ||
3611           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3612           !all_of(drop_begin(TE->UserTreeIndices),
3613                   [TE](const EdgeInfo &EI) {
3614                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3615                   }) ||
3616           !Visited.insert(TE).second) {
3617         Filtered.push_back(TE);
3618         continue;
3619       }
3620       // Build a map between user nodes and their operands order to speedup
3621       // search. The graph currently does not provide this dependency directly.
3622       for (EdgeInfo &EI : TE->UserTreeIndices) {
3623         TreeEntry *UserTE = EI.UserTE;
3624         auto It = Users.find(UserTE);
3625         if (It == Users.end())
3626           It = Users.insert({UserTE, {}}).first;
3627         It->second.emplace_back(EI.EdgeIdx, TE);
3628       }
3629     }
3630     // Erase filtered entries.
3631     for_each(Filtered,
3632              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3633     for (auto &Data : Users) {
3634       // Check that operands are used only in the User node.
3635       SmallVector<TreeEntry *> GatherOps;
3636       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3637                               GatherOps)) {
3638         for_each(Data.second,
3639                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3640                    OrderedEntries.remove(Op.second);
3641                  });
3642         continue;
3643       }
3644       // All operands are reordered and used only in this node - propagate the
3645       // most used order to the user node.
3646       MapVector<OrdersType, unsigned,
3647                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3648           OrdersUses;
3649       // Do the analysis for each tree entry only once, otherwise the order of
3650       // the same node my be considered several times, though might be not
3651       // profitable.
3652       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3653       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3654       for (const auto &Op : Data.second) {
3655         TreeEntry *OpTE = Op.second;
3656         if (!VisitedOps.insert(OpTE).second)
3657           continue;
3658         if (!OpTE->ReuseShuffleIndices.empty() ||
3659             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3660           continue;
3661         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3662           if (OpTE->State == TreeEntry::NeedToGather)
3663             return GathersToOrders.find(OpTE)->second;
3664           return OpTE->ReorderIndices;
3665         }();
3666         unsigned NumOps = count_if(
3667             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3668               return P.second == OpTE;
3669             });
3670         // Stores actually store the mask, not the order, need to invert.
3671         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3672             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3673           SmallVector<int> Mask;
3674           inversePermutation(Order, Mask);
3675           unsigned E = Order.size();
3676           OrdersType CurrentOrder(E, E);
3677           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3678             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3679           });
3680           fixupOrderingIndices(CurrentOrder);
3681           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3682               NumOps;
3683         } else {
3684           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3685         }
3686         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3687         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3688                                             const TreeEntry *TE) {
3689           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3690               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3691               (IgnoreReorder && TE->Idx == 0))
3692             return true;
3693           if (TE->State == TreeEntry::NeedToGather) {
3694             auto It = GathersToOrders.find(TE);
3695             if (It != GathersToOrders.end())
3696               return !It->second.empty();
3697             return true;
3698           }
3699           return false;
3700         };
3701         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3702           TreeEntry *UserTE = EI.UserTE;
3703           if (!VisitedUsers.insert(UserTE).second)
3704             continue;
3705           // May reorder user node if it requires reordering, has reused
3706           // scalars, is an alternate op vectorize node or its op nodes require
3707           // reordering.
3708           if (AllowsReordering(UserTE))
3709             continue;
3710           // Check if users allow reordering.
3711           // Currently look up just 1 level of operands to avoid increase of
3712           // the compile time.
3713           // Profitable to reorder if definitely more operands allow
3714           // reordering rather than those with natural order.
3715           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3716           if (static_cast<unsigned>(count_if(
3717                   Ops, [UserTE, &AllowsReordering](
3718                            const std::pair<unsigned, TreeEntry *> &Op) {
3719                     return AllowsReordering(Op.second) &&
3720                            all_of(Op.second->UserTreeIndices,
3721                                   [UserTE](const EdgeInfo &EI) {
3722                                     return EI.UserTE == UserTE;
3723                                   });
3724                   })) <= Ops.size() / 2)
3725             ++Res.first->second;
3726         }
3727       }
3728       // If no orders - skip current nodes and jump to the next one, if any.
3729       if (OrdersUses.empty()) {
3730         for_each(Data.second,
3731                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3732                    OrderedEntries.remove(Op.second);
3733                  });
3734         continue;
3735       }
3736       // Choose the best order.
3737       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3738       unsigned Cnt = OrdersUses.front().second;
3739       for (const auto &Pair : drop_begin(OrdersUses)) {
3740         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3741           BestOrder = Pair.first;
3742           Cnt = Pair.second;
3743         }
3744       }
3745       // Set order of the user node (reordering of operands and user nodes).
3746       if (BestOrder.empty()) {
3747         for_each(Data.second,
3748                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3749                    OrderedEntries.remove(Op.second);
3750                  });
3751         continue;
3752       }
3753       // Erase operands from OrderedEntries list and adjust their orders.
3754       VisitedOps.clear();
3755       SmallVector<int> Mask;
3756       inversePermutation(BestOrder, Mask);
3757       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3758       unsigned E = BestOrder.size();
3759       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3760         return I < E ? static_cast<int>(I) : UndefMaskElem;
3761       });
3762       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3763         TreeEntry *TE = Op.second;
3764         OrderedEntries.remove(TE);
3765         if (!VisitedOps.insert(TE).second)
3766           continue;
3767         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3768           // Just reorder reuses indices.
3769           reorderReuses(TE->ReuseShuffleIndices, Mask);
3770           continue;
3771         }
3772         // Gathers are processed separately.
3773         if (TE->State != TreeEntry::Vectorize)
3774           continue;
3775         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3776                 TE->ReorderIndices.empty()) &&
3777                "Non-matching sizes of user/operand entries.");
3778         reorderOrder(TE->ReorderIndices, Mask);
3779       }
3780       // For gathers just need to reorder its scalars.
3781       for (TreeEntry *Gather : GatherOps) {
3782         assert(Gather->ReorderIndices.empty() &&
3783                "Unexpected reordering of gathers.");
3784         if (!Gather->ReuseShuffleIndices.empty()) {
3785           // Just reorder reuses indices.
3786           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3787           continue;
3788         }
3789         reorderScalars(Gather->Scalars, Mask);
3790         OrderedEntries.remove(Gather);
3791       }
3792       // Reorder operands of the user node and set the ordering for the user
3793       // node itself.
3794       if (Data.first->State != TreeEntry::Vectorize ||
3795           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3796               Data.first->getMainOp()) ||
3797           Data.first->isAltShuffle())
3798         Data.first->reorderOperands(Mask);
3799       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3800           Data.first->isAltShuffle()) {
3801         reorderScalars(Data.first->Scalars, Mask);
3802         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3803         if (Data.first->ReuseShuffleIndices.empty() &&
3804             !Data.first->ReorderIndices.empty() &&
3805             !Data.first->isAltShuffle()) {
3806           // Insert user node to the list to try to sink reordering deeper in
3807           // the graph.
3808           OrderedEntries.insert(Data.first);
3809         }
3810       } else {
3811         reorderOrder(Data.first->ReorderIndices, Mask);
3812       }
3813     }
3814   }
3815   // If the reordering is unnecessary, just remove the reorder.
3816   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3817       VectorizableTree.front()->ReuseShuffleIndices.empty())
3818     VectorizableTree.front()->ReorderIndices.clear();
3819 }
3820 
3821 void BoUpSLP::buildExternalUses(
3822     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3823   // Collect the values that we need to extract from the tree.
3824   for (auto &TEPtr : VectorizableTree) {
3825     TreeEntry *Entry = TEPtr.get();
3826 
3827     // No need to handle users of gathered values.
3828     if (Entry->State == TreeEntry::NeedToGather)
3829       continue;
3830 
3831     // For each lane:
3832     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3833       Value *Scalar = Entry->Scalars[Lane];
3834       int FoundLane = Entry->findLaneForValue(Scalar);
3835 
3836       // Check if the scalar is externally used as an extra arg.
3837       auto ExtI = ExternallyUsedValues.find(Scalar);
3838       if (ExtI != ExternallyUsedValues.end()) {
3839         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3840                           << Lane << " from " << *Scalar << ".\n");
3841         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3842       }
3843       for (User *U : Scalar->users()) {
3844         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3845 
3846         Instruction *UserInst = dyn_cast<Instruction>(U);
3847         if (!UserInst)
3848           continue;
3849 
3850         if (isDeleted(UserInst))
3851           continue;
3852 
3853         // Skip in-tree scalars that become vectors
3854         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3855           Value *UseScalar = UseEntry->Scalars[0];
3856           // Some in-tree scalars will remain as scalar in vectorized
3857           // instructions. If that is the case, the one in Lane 0 will
3858           // be used.
3859           if (UseScalar != U ||
3860               UseEntry->State == TreeEntry::ScatterVectorize ||
3861               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3862             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3863                               << ".\n");
3864             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3865             continue;
3866           }
3867         }
3868 
3869         // Ignore users in the user ignore list.
3870         if (is_contained(UserIgnoreList, UserInst))
3871           continue;
3872 
3873         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3874                           << Lane << " from " << *Scalar << ".\n");
3875         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3876       }
3877     }
3878   }
3879 }
3880 
3881 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3882                         ArrayRef<Value *> UserIgnoreLst) {
3883   deleteTree();
3884   UserIgnoreList = UserIgnoreLst;
3885   if (!allSameType(Roots))
3886     return;
3887   buildTree_rec(Roots, 0, EdgeInfo());
3888 }
3889 
3890 namespace {
3891 /// Tracks the state we can represent the loads in the given sequence.
3892 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3893 } // anonymous namespace
3894 
3895 /// Checks if the given array of loads can be represented as a vectorized,
3896 /// scatter or just simple gather.
3897 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3898                                     const TargetTransformInfo &TTI,
3899                                     const DataLayout &DL, ScalarEvolution &SE,
3900                                     SmallVectorImpl<unsigned> &Order,
3901                                     SmallVectorImpl<Value *> &PointerOps) {
3902   // Check that a vectorized load would load the same memory as a scalar
3903   // load. For example, we don't want to vectorize loads that are smaller
3904   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3905   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3906   // from such a struct, we read/write packed bits disagreeing with the
3907   // unvectorized version.
3908   Type *ScalarTy = VL0->getType();
3909 
3910   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3911     return LoadsState::Gather;
3912 
3913   // Make sure all loads in the bundle are simple - we can't vectorize
3914   // atomic or volatile loads.
3915   PointerOps.clear();
3916   PointerOps.resize(VL.size());
3917   auto *POIter = PointerOps.begin();
3918   for (Value *V : VL) {
3919     auto *L = cast<LoadInst>(V);
3920     if (!L->isSimple())
3921       return LoadsState::Gather;
3922     *POIter = L->getPointerOperand();
3923     ++POIter;
3924   }
3925 
3926   Order.clear();
3927   // Check the order of pointer operands.
3928   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3929     Value *Ptr0;
3930     Value *PtrN;
3931     if (Order.empty()) {
3932       Ptr0 = PointerOps.front();
3933       PtrN = PointerOps.back();
3934     } else {
3935       Ptr0 = PointerOps[Order.front()];
3936       PtrN = PointerOps[Order.back()];
3937     }
3938     Optional<int> Diff =
3939         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3940     // Check that the sorted loads are consecutive.
3941     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3942       return LoadsState::Vectorize;
3943     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3944     for (Value *V : VL)
3945       CommonAlignment =
3946           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3947     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3948                                 CommonAlignment))
3949       return LoadsState::ScatterVectorize;
3950   }
3951 
3952   return LoadsState::Gather;
3953 }
3954 
3955 /// \return true if the specified list of values has only one instruction that
3956 /// requires scheduling, false otherwise.
3957 #ifndef NDEBUG
3958 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3959   Value *NeedsScheduling = nullptr;
3960   for (Value *V : VL) {
3961     if (doesNotNeedToBeScheduled(V))
3962       continue;
3963     if (!NeedsScheduling) {
3964       NeedsScheduling = V;
3965       continue;
3966     }
3967     return false;
3968   }
3969   return NeedsScheduling;
3970 }
3971 #endif
3972 
3973 /// Generates key/subkey pair for the given value to provide effective sorting
3974 /// of the values and better detection of the vectorizable values sequences. The
3975 /// keys/subkeys can be used for better sorting of the values themselves (keys)
3976 /// and in values subgroups (subkeys).
3977 static std::pair<size_t, size_t> generateKeySubkey(
3978     Value *V, const TargetLibraryInfo *TLI,
3979     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
3980     bool AllowAlternate) {
3981   hash_code Key = hash_value(V->getValueID() + 2);
3982   hash_code SubKey = hash_value(0);
3983   // Sort the loads by the distance between the pointers.
3984   if (auto *LI = dyn_cast<LoadInst>(V)) {
3985     Key = hash_combine(hash_value(LI->getParent()), Key);
3986     if (LI->isSimple())
3987       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
3988     else
3989       SubKey = hash_value(LI);
3990   } else if (isVectorLikeInstWithConstOps(V)) {
3991     // Sort extracts by the vector operands.
3992     if (isa<ExtractElementInst, UndefValue>(V))
3993       Key = hash_value(Value::UndefValueVal + 1);
3994     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
3995       if (!isUndefVector(EI->getVectorOperand()) &&
3996           !isa<UndefValue>(EI->getIndexOperand()))
3997         SubKey = hash_value(EI->getVectorOperand());
3998     }
3999   } else if (auto *I = dyn_cast<Instruction>(V)) {
4000     // Sort other instructions just by the opcodes except for CMPInst.
4001     // For CMP also sort by the predicate kind.
4002     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4003         isValidForAlternation(I->getOpcode())) {
4004       if (AllowAlternate)
4005         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4006       else
4007         Key = hash_combine(hash_value(I->getOpcode()), Key);
4008       SubKey = hash_combine(
4009           hash_value(I->getOpcode()), hash_value(I->getType()),
4010           hash_value(isa<BinaryOperator>(I)
4011                          ? I->getType()
4012                          : cast<CastInst>(I)->getOperand(0)->getType()));
4013     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4014       CmpInst::Predicate Pred = CI->getPredicate();
4015       if (CI->isCommutative())
4016         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4017       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4018       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4019                             hash_value(SwapPred),
4020                             hash_value(CI->getOperand(0)->getType()));
4021     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4022       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4023       if (isTriviallyVectorizable(ID))
4024         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4025       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4026         SubKey = hash_combine(hash_value(I->getOpcode()),
4027                               hash_value(Call->getCalledFunction()));
4028       else
4029         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4030       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4031         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4032                               hash_value(Op.Tag), SubKey);
4033     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4034       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4035         SubKey = hash_value(Gep->getPointerOperand());
4036       else
4037         SubKey = hash_value(Gep);
4038     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4039                !isa<ConstantInt>(I->getOperand(1))) {
4040       // Do not try to vectorize instructions with potentially high cost.
4041       SubKey = hash_value(I);
4042     } else {
4043       SubKey = hash_value(I->getOpcode());
4044     }
4045     Key = hash_combine(hash_value(I->getParent()), Key);
4046   }
4047   return std::make_pair(Key, SubKey);
4048 }
4049 
4050 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4051                             const EdgeInfo &UserTreeIdx) {
4052   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4053 
4054   SmallVector<int> ReuseShuffleIndicies;
4055   SmallVector<Value *> UniqueValues;
4056   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4057                                 &UserTreeIdx,
4058                                 this](const InstructionsState &S) {
4059     // Check that every instruction appears once in this bundle.
4060     DenseMap<Value *, unsigned> UniquePositions;
4061     for (Value *V : VL) {
4062       if (isConstant(V)) {
4063         ReuseShuffleIndicies.emplace_back(
4064             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4065         UniqueValues.emplace_back(V);
4066         continue;
4067       }
4068       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4069       ReuseShuffleIndicies.emplace_back(Res.first->second);
4070       if (Res.second)
4071         UniqueValues.emplace_back(V);
4072     }
4073     size_t NumUniqueScalarValues = UniqueValues.size();
4074     if (NumUniqueScalarValues == VL.size()) {
4075       ReuseShuffleIndicies.clear();
4076     } else {
4077       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4078       if (NumUniqueScalarValues <= 1 ||
4079           (UniquePositions.size() == 1 && all_of(UniqueValues,
4080                                                  [](Value *V) {
4081                                                    return isa<UndefValue>(V) ||
4082                                                           !isConstant(V);
4083                                                  })) ||
4084           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4085         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4086         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4087         return false;
4088       }
4089       VL = UniqueValues;
4090     }
4091     return true;
4092   };
4093 
4094   InstructionsState S = getSameOpcode(VL);
4095   if (Depth == RecursionMaxDepth) {
4096     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4097     if (TryToFindDuplicates(S))
4098       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4099                    ReuseShuffleIndicies);
4100     return;
4101   }
4102 
4103   // Don't handle scalable vectors
4104   if (S.getOpcode() == Instruction::ExtractElement &&
4105       isa<ScalableVectorType>(
4106           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4107     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4108     if (TryToFindDuplicates(S))
4109       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4110                    ReuseShuffleIndicies);
4111     return;
4112   }
4113 
4114   // Don't handle vectors.
4115   if (S.OpValue->getType()->isVectorTy() &&
4116       !isa<InsertElementInst>(S.OpValue)) {
4117     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4118     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4119     return;
4120   }
4121 
4122   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4123     if (SI->getValueOperand()->getType()->isVectorTy()) {
4124       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4125       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4126       return;
4127     }
4128 
4129   // If all of the operands are identical or constant we have a simple solution.
4130   // If we deal with insert/extract instructions, they all must have constant
4131   // indices, otherwise we should gather them, not try to vectorize.
4132   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4133       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4134        !all_of(VL, isVectorLikeInstWithConstOps))) {
4135     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4136     if (TryToFindDuplicates(S))
4137       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4138                    ReuseShuffleIndicies);
4139     return;
4140   }
4141 
4142   // We now know that this is a vector of instructions of the same type from
4143   // the same block.
4144 
4145   // Don't vectorize ephemeral values.
4146   for (Value *V : VL) {
4147     if (EphValues.count(V)) {
4148       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4149                         << ") is ephemeral.\n");
4150       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4151       return;
4152     }
4153   }
4154 
4155   // Check if this is a duplicate of another entry.
4156   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4157     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4158     if (!E->isSame(VL)) {
4159       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4160       if (TryToFindDuplicates(S))
4161         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4162                      ReuseShuffleIndicies);
4163       return;
4164     }
4165     // Record the reuse of the tree node.  FIXME, currently this is only used to
4166     // properly draw the graph rather than for the actual vectorization.
4167     E->UserTreeIndices.push_back(UserTreeIdx);
4168     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4169                       << ".\n");
4170     return;
4171   }
4172 
4173   // Check that none of the instructions in the bundle are already in the tree.
4174   for (Value *V : VL) {
4175     auto *I = dyn_cast<Instruction>(V);
4176     if (!I)
4177       continue;
4178     if (getTreeEntry(I)) {
4179       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4180                         << ") is already in tree.\n");
4181       if (TryToFindDuplicates(S))
4182         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4183                      ReuseShuffleIndicies);
4184       return;
4185     }
4186   }
4187 
4188   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4189   for (Value *V : VL) {
4190     if (is_contained(UserIgnoreList, V)) {
4191       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4192       if (TryToFindDuplicates(S))
4193         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4194                      ReuseShuffleIndicies);
4195       return;
4196     }
4197   }
4198 
4199   // Check that all of the users of the scalars that we want to vectorize are
4200   // schedulable.
4201   auto *VL0 = cast<Instruction>(S.OpValue);
4202   BasicBlock *BB = VL0->getParent();
4203 
4204   if (!DT->isReachableFromEntry(BB)) {
4205     // Don't go into unreachable blocks. They may contain instructions with
4206     // dependency cycles which confuse the final scheduling.
4207     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4208     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4209     return;
4210   }
4211 
4212   // Check that every instruction appears once in this bundle.
4213   if (!TryToFindDuplicates(S))
4214     return;
4215 
4216   auto &BSRef = BlocksSchedules[BB];
4217   if (!BSRef)
4218     BSRef = std::make_unique<BlockScheduling>(BB);
4219 
4220   BlockScheduling &BS = *BSRef;
4221 
4222   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4223 #ifdef EXPENSIVE_CHECKS
4224   // Make sure we didn't break any internal invariants
4225   BS.verify();
4226 #endif
4227   if (!Bundle) {
4228     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4229     assert((!BS.getScheduleData(VL0) ||
4230             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4231            "tryScheduleBundle should cancelScheduling on failure");
4232     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4233                  ReuseShuffleIndicies);
4234     return;
4235   }
4236   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4237 
4238   unsigned ShuffleOrOp = S.isAltShuffle() ?
4239                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4240   switch (ShuffleOrOp) {
4241     case Instruction::PHI: {
4242       auto *PH = cast<PHINode>(VL0);
4243 
4244       // Check for terminator values (e.g. invoke).
4245       for (Value *V : VL)
4246         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4247           Instruction *Term = dyn_cast<Instruction>(Incoming);
4248           if (Term && Term->isTerminator()) {
4249             LLVM_DEBUG(dbgs()
4250                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4251             BS.cancelScheduling(VL, VL0);
4252             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4253                          ReuseShuffleIndicies);
4254             return;
4255           }
4256         }
4257 
4258       TreeEntry *TE =
4259           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4260       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4261 
4262       // Keeps the reordered operands to avoid code duplication.
4263       SmallVector<ValueList, 2> OperandsVec;
4264       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4265         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4266           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4267           TE->setOperand(I, Operands);
4268           OperandsVec.push_back(Operands);
4269           continue;
4270         }
4271         ValueList Operands;
4272         // Prepare the operand vector.
4273         for (Value *V : VL)
4274           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4275               PH->getIncomingBlock(I)));
4276         TE->setOperand(I, Operands);
4277         OperandsVec.push_back(Operands);
4278       }
4279       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4280         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4281       return;
4282     }
4283     case Instruction::ExtractValue:
4284     case Instruction::ExtractElement: {
4285       OrdersType CurrentOrder;
4286       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4287       if (Reuse) {
4288         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4289         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4290                      ReuseShuffleIndicies);
4291         // This is a special case, as it does not gather, but at the same time
4292         // we are not extending buildTree_rec() towards the operands.
4293         ValueList Op0;
4294         Op0.assign(VL.size(), VL0->getOperand(0));
4295         VectorizableTree.back()->setOperand(0, Op0);
4296         return;
4297       }
4298       if (!CurrentOrder.empty()) {
4299         LLVM_DEBUG({
4300           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4301                     "with order";
4302           for (unsigned Idx : CurrentOrder)
4303             dbgs() << " " << Idx;
4304           dbgs() << "\n";
4305         });
4306         fixupOrderingIndices(CurrentOrder);
4307         // Insert new order with initial value 0, if it does not exist,
4308         // otherwise return the iterator to the existing one.
4309         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4310                      ReuseShuffleIndicies, CurrentOrder);
4311         // This is a special case, as it does not gather, but at the same time
4312         // we are not extending buildTree_rec() towards the operands.
4313         ValueList Op0;
4314         Op0.assign(VL.size(), VL0->getOperand(0));
4315         VectorizableTree.back()->setOperand(0, Op0);
4316         return;
4317       }
4318       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4319       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4320                    ReuseShuffleIndicies);
4321       BS.cancelScheduling(VL, VL0);
4322       return;
4323     }
4324     case Instruction::InsertElement: {
4325       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4326 
4327       // Check that we have a buildvector and not a shuffle of 2 or more
4328       // different vectors.
4329       ValueSet SourceVectors;
4330       for (Value *V : VL) {
4331         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4332         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4333       }
4334 
4335       if (count_if(VL, [&SourceVectors](Value *V) {
4336             return !SourceVectors.contains(V);
4337           }) >= 2) {
4338         // Found 2nd source vector - cancel.
4339         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4340                              "different source vectors.\n");
4341         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4342         BS.cancelScheduling(VL, VL0);
4343         return;
4344       }
4345 
4346       auto OrdCompare = [](const std::pair<int, int> &P1,
4347                            const std::pair<int, int> &P2) {
4348         return P1.first > P2.first;
4349       };
4350       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4351                     decltype(OrdCompare)>
4352           Indices(OrdCompare);
4353       for (int I = 0, E = VL.size(); I < E; ++I) {
4354         unsigned Idx = *getInsertIndex(VL[I]);
4355         Indices.emplace(Idx, I);
4356       }
4357       OrdersType CurrentOrder(VL.size(), VL.size());
4358       bool IsIdentity = true;
4359       for (int I = 0, E = VL.size(); I < E; ++I) {
4360         CurrentOrder[Indices.top().second] = I;
4361         IsIdentity &= Indices.top().second == I;
4362         Indices.pop();
4363       }
4364       if (IsIdentity)
4365         CurrentOrder.clear();
4366       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4367                                    None, CurrentOrder);
4368       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4369 
4370       constexpr int NumOps = 2;
4371       ValueList VectorOperands[NumOps];
4372       for (int I = 0; I < NumOps; ++I) {
4373         for (Value *V : VL)
4374           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4375 
4376         TE->setOperand(I, VectorOperands[I]);
4377       }
4378       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4379       return;
4380     }
4381     case Instruction::Load: {
4382       // Check that a vectorized load would load the same memory as a scalar
4383       // load. For example, we don't want to vectorize loads that are smaller
4384       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4385       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4386       // from such a struct, we read/write packed bits disagreeing with the
4387       // unvectorized version.
4388       SmallVector<Value *> PointerOps;
4389       OrdersType CurrentOrder;
4390       TreeEntry *TE = nullptr;
4391       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4392                                 PointerOps)) {
4393       case LoadsState::Vectorize:
4394         if (CurrentOrder.empty()) {
4395           // Original loads are consecutive and does not require reordering.
4396           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4397                             ReuseShuffleIndicies);
4398           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4399         } else {
4400           fixupOrderingIndices(CurrentOrder);
4401           // Need to reorder.
4402           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4403                             ReuseShuffleIndicies, CurrentOrder);
4404           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4405         }
4406         TE->setOperandsInOrder();
4407         break;
4408       case LoadsState::ScatterVectorize:
4409         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4410         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4411                           UserTreeIdx, ReuseShuffleIndicies);
4412         TE->setOperandsInOrder();
4413         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4414         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4415         break;
4416       case LoadsState::Gather:
4417         BS.cancelScheduling(VL, VL0);
4418         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4419                      ReuseShuffleIndicies);
4420 #ifndef NDEBUG
4421         Type *ScalarTy = VL0->getType();
4422         if (DL->getTypeSizeInBits(ScalarTy) !=
4423             DL->getTypeAllocSizeInBits(ScalarTy))
4424           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4425         else if (any_of(VL, [](Value *V) {
4426                    return !cast<LoadInst>(V)->isSimple();
4427                  }))
4428           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4429         else
4430           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4431 #endif // NDEBUG
4432         break;
4433       }
4434       return;
4435     }
4436     case Instruction::ZExt:
4437     case Instruction::SExt:
4438     case Instruction::FPToUI:
4439     case Instruction::FPToSI:
4440     case Instruction::FPExt:
4441     case Instruction::PtrToInt:
4442     case Instruction::IntToPtr:
4443     case Instruction::SIToFP:
4444     case Instruction::UIToFP:
4445     case Instruction::Trunc:
4446     case Instruction::FPTrunc:
4447     case Instruction::BitCast: {
4448       Type *SrcTy = VL0->getOperand(0)->getType();
4449       for (Value *V : VL) {
4450         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4451         if (Ty != SrcTy || !isValidElementType(Ty)) {
4452           BS.cancelScheduling(VL, VL0);
4453           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4454                        ReuseShuffleIndicies);
4455           LLVM_DEBUG(dbgs()
4456                      << "SLP: Gathering casts with different src types.\n");
4457           return;
4458         }
4459       }
4460       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4461                                    ReuseShuffleIndicies);
4462       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4463 
4464       TE->setOperandsInOrder();
4465       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4466         ValueList Operands;
4467         // Prepare the operand vector.
4468         for (Value *V : VL)
4469           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4470 
4471         buildTree_rec(Operands, Depth + 1, {TE, i});
4472       }
4473       return;
4474     }
4475     case Instruction::ICmp:
4476     case Instruction::FCmp: {
4477       // Check that all of the compares have the same predicate.
4478       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4479       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4480       Type *ComparedTy = VL0->getOperand(0)->getType();
4481       for (Value *V : VL) {
4482         CmpInst *Cmp = cast<CmpInst>(V);
4483         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4484             Cmp->getOperand(0)->getType() != ComparedTy) {
4485           BS.cancelScheduling(VL, VL0);
4486           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4487                        ReuseShuffleIndicies);
4488           LLVM_DEBUG(dbgs()
4489                      << "SLP: Gathering cmp with different predicate.\n");
4490           return;
4491         }
4492       }
4493 
4494       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4495                                    ReuseShuffleIndicies);
4496       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4497 
4498       ValueList Left, Right;
4499       if (cast<CmpInst>(VL0)->isCommutative()) {
4500         // Commutative predicate - collect + sort operands of the instructions
4501         // so that each side is more likely to have the same opcode.
4502         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4503         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4504       } else {
4505         // Collect operands - commute if it uses the swapped predicate.
4506         for (Value *V : VL) {
4507           auto *Cmp = cast<CmpInst>(V);
4508           Value *LHS = Cmp->getOperand(0);
4509           Value *RHS = Cmp->getOperand(1);
4510           if (Cmp->getPredicate() != P0)
4511             std::swap(LHS, RHS);
4512           Left.push_back(LHS);
4513           Right.push_back(RHS);
4514         }
4515       }
4516       TE->setOperand(0, Left);
4517       TE->setOperand(1, Right);
4518       buildTree_rec(Left, Depth + 1, {TE, 0});
4519       buildTree_rec(Right, Depth + 1, {TE, 1});
4520       return;
4521     }
4522     case Instruction::Select:
4523     case Instruction::FNeg:
4524     case Instruction::Add:
4525     case Instruction::FAdd:
4526     case Instruction::Sub:
4527     case Instruction::FSub:
4528     case Instruction::Mul:
4529     case Instruction::FMul:
4530     case Instruction::UDiv:
4531     case Instruction::SDiv:
4532     case Instruction::FDiv:
4533     case Instruction::URem:
4534     case Instruction::SRem:
4535     case Instruction::FRem:
4536     case Instruction::Shl:
4537     case Instruction::LShr:
4538     case Instruction::AShr:
4539     case Instruction::And:
4540     case Instruction::Or:
4541     case Instruction::Xor: {
4542       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4543                                    ReuseShuffleIndicies);
4544       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4545 
4546       // Sort operands of the instructions so that each side is more likely to
4547       // have the same opcode.
4548       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4549         ValueList Left, Right;
4550         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4551         TE->setOperand(0, Left);
4552         TE->setOperand(1, Right);
4553         buildTree_rec(Left, Depth + 1, {TE, 0});
4554         buildTree_rec(Right, Depth + 1, {TE, 1});
4555         return;
4556       }
4557 
4558       TE->setOperandsInOrder();
4559       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4560         ValueList Operands;
4561         // Prepare the operand vector.
4562         for (Value *V : VL)
4563           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4564 
4565         buildTree_rec(Operands, Depth + 1, {TE, i});
4566       }
4567       return;
4568     }
4569     case Instruction::GetElementPtr: {
4570       // We don't combine GEPs with complicated (nested) indexing.
4571       for (Value *V : VL) {
4572         if (cast<Instruction>(V)->getNumOperands() != 2) {
4573           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4574           BS.cancelScheduling(VL, VL0);
4575           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4576                        ReuseShuffleIndicies);
4577           return;
4578         }
4579       }
4580 
4581       // We can't combine several GEPs into one vector if they operate on
4582       // different types.
4583       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4584       for (Value *V : VL) {
4585         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4586         if (Ty0 != CurTy) {
4587           LLVM_DEBUG(dbgs()
4588                      << "SLP: not-vectorizable GEP (different types).\n");
4589           BS.cancelScheduling(VL, VL0);
4590           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4591                        ReuseShuffleIndicies);
4592           return;
4593         }
4594       }
4595 
4596       // We don't combine GEPs with non-constant indexes.
4597       Type *Ty1 = VL0->getOperand(1)->getType();
4598       for (Value *V : VL) {
4599         auto Op = cast<Instruction>(V)->getOperand(1);
4600         if (!isa<ConstantInt>(Op) ||
4601             (Op->getType() != Ty1 &&
4602              Op->getType()->getScalarSizeInBits() >
4603                  DL->getIndexSizeInBits(
4604                      V->getType()->getPointerAddressSpace()))) {
4605           LLVM_DEBUG(dbgs()
4606                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4607           BS.cancelScheduling(VL, VL0);
4608           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4609                        ReuseShuffleIndicies);
4610           return;
4611         }
4612       }
4613 
4614       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4615                                    ReuseShuffleIndicies);
4616       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4617       SmallVector<ValueList, 2> Operands(2);
4618       // Prepare the operand vector for pointer operands.
4619       for (Value *V : VL)
4620         Operands.front().push_back(
4621             cast<GetElementPtrInst>(V)->getPointerOperand());
4622       TE->setOperand(0, Operands.front());
4623       // Need to cast all indices to the same type before vectorization to
4624       // avoid crash.
4625       // Required to be able to find correct matches between different gather
4626       // nodes and reuse the vectorized values rather than trying to gather them
4627       // again.
4628       int IndexIdx = 1;
4629       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4630       Type *Ty = all_of(VL,
4631                         [VL0Ty, IndexIdx](Value *V) {
4632                           return VL0Ty == cast<GetElementPtrInst>(V)
4633                                               ->getOperand(IndexIdx)
4634                                               ->getType();
4635                         })
4636                      ? VL0Ty
4637                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4638                                             ->getPointerOperandType()
4639                                             ->getScalarType());
4640       // Prepare the operand vector.
4641       for (Value *V : VL) {
4642         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4643         auto *CI = cast<ConstantInt>(Op);
4644         Operands.back().push_back(ConstantExpr::getIntegerCast(
4645             CI, Ty, CI->getValue().isSignBitSet()));
4646       }
4647       TE->setOperand(IndexIdx, Operands.back());
4648 
4649       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4650         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4651       return;
4652     }
4653     case Instruction::Store: {
4654       // Check if the stores are consecutive or if we need to swizzle them.
4655       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4656       // Avoid types that are padded when being allocated as scalars, while
4657       // being packed together in a vector (such as i1).
4658       if (DL->getTypeSizeInBits(ScalarTy) !=
4659           DL->getTypeAllocSizeInBits(ScalarTy)) {
4660         BS.cancelScheduling(VL, VL0);
4661         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4662                      ReuseShuffleIndicies);
4663         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4664         return;
4665       }
4666       // Make sure all stores in the bundle are simple - we can't vectorize
4667       // atomic or volatile stores.
4668       SmallVector<Value *, 4> PointerOps(VL.size());
4669       ValueList Operands(VL.size());
4670       auto POIter = PointerOps.begin();
4671       auto OIter = Operands.begin();
4672       for (Value *V : VL) {
4673         auto *SI = cast<StoreInst>(V);
4674         if (!SI->isSimple()) {
4675           BS.cancelScheduling(VL, VL0);
4676           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4677                        ReuseShuffleIndicies);
4678           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4679           return;
4680         }
4681         *POIter = SI->getPointerOperand();
4682         *OIter = SI->getValueOperand();
4683         ++POIter;
4684         ++OIter;
4685       }
4686 
4687       OrdersType CurrentOrder;
4688       // Check the order of pointer operands.
4689       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4690         Value *Ptr0;
4691         Value *PtrN;
4692         if (CurrentOrder.empty()) {
4693           Ptr0 = PointerOps.front();
4694           PtrN = PointerOps.back();
4695         } else {
4696           Ptr0 = PointerOps[CurrentOrder.front()];
4697           PtrN = PointerOps[CurrentOrder.back()];
4698         }
4699         Optional<int> Dist =
4700             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4701         // Check that the sorted pointer operands are consecutive.
4702         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4703           if (CurrentOrder.empty()) {
4704             // Original stores are consecutive and does not require reordering.
4705             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4706                                          UserTreeIdx, ReuseShuffleIndicies);
4707             TE->setOperandsInOrder();
4708             buildTree_rec(Operands, Depth + 1, {TE, 0});
4709             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4710           } else {
4711             fixupOrderingIndices(CurrentOrder);
4712             TreeEntry *TE =
4713                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4714                              ReuseShuffleIndicies, CurrentOrder);
4715             TE->setOperandsInOrder();
4716             buildTree_rec(Operands, Depth + 1, {TE, 0});
4717             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4718           }
4719           return;
4720         }
4721       }
4722 
4723       BS.cancelScheduling(VL, VL0);
4724       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4725                    ReuseShuffleIndicies);
4726       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4727       return;
4728     }
4729     case Instruction::Call: {
4730       // Check if the calls are all to the same vectorizable intrinsic or
4731       // library function.
4732       CallInst *CI = cast<CallInst>(VL0);
4733       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4734 
4735       VFShape Shape = VFShape::get(
4736           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4737           false /*HasGlobalPred*/);
4738       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4739 
4740       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4741         BS.cancelScheduling(VL, VL0);
4742         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4743                      ReuseShuffleIndicies);
4744         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4745         return;
4746       }
4747       Function *F = CI->getCalledFunction();
4748       unsigned NumArgs = CI->arg_size();
4749       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4750       for (unsigned j = 0; j != NumArgs; ++j)
4751         if (hasVectorInstrinsicScalarOpd(ID, j))
4752           ScalarArgs[j] = CI->getArgOperand(j);
4753       for (Value *V : VL) {
4754         CallInst *CI2 = dyn_cast<CallInst>(V);
4755         if (!CI2 || CI2->getCalledFunction() != F ||
4756             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4757             (VecFunc &&
4758              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4759             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4760           BS.cancelScheduling(VL, VL0);
4761           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4762                        ReuseShuffleIndicies);
4763           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4764                             << "\n");
4765           return;
4766         }
4767         // Some intrinsics have scalar arguments and should be same in order for
4768         // them to be vectorized.
4769         for (unsigned j = 0; j != NumArgs; ++j) {
4770           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4771             Value *A1J = CI2->getArgOperand(j);
4772             if (ScalarArgs[j] != A1J) {
4773               BS.cancelScheduling(VL, VL0);
4774               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4775                            ReuseShuffleIndicies);
4776               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4777                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4778                                 << "\n");
4779               return;
4780             }
4781           }
4782         }
4783         // Verify that the bundle operands are identical between the two calls.
4784         if (CI->hasOperandBundles() &&
4785             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4786                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4787                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4788           BS.cancelScheduling(VL, VL0);
4789           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4790                        ReuseShuffleIndicies);
4791           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4792                             << *CI << "!=" << *V << '\n');
4793           return;
4794         }
4795       }
4796 
4797       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4798                                    ReuseShuffleIndicies);
4799       TE->setOperandsInOrder();
4800       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4801         // For scalar operands no need to to create an entry since no need to
4802         // vectorize it.
4803         if (hasVectorInstrinsicScalarOpd(ID, i))
4804           continue;
4805         ValueList Operands;
4806         // Prepare the operand vector.
4807         for (Value *V : VL) {
4808           auto *CI2 = cast<CallInst>(V);
4809           Operands.push_back(CI2->getArgOperand(i));
4810         }
4811         buildTree_rec(Operands, Depth + 1, {TE, i});
4812       }
4813       return;
4814     }
4815     case Instruction::ShuffleVector: {
4816       // If this is not an alternate sequence of opcode like add-sub
4817       // then do not vectorize this instruction.
4818       if (!S.isAltShuffle()) {
4819         BS.cancelScheduling(VL, VL0);
4820         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4821                      ReuseShuffleIndicies);
4822         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4823         return;
4824       }
4825       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4826                                    ReuseShuffleIndicies);
4827       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4828 
4829       // Reorder operands if reordering would enable vectorization.
4830       auto *CI = dyn_cast<CmpInst>(VL0);
4831       if (isa<BinaryOperator>(VL0) || CI) {
4832         ValueList Left, Right;
4833         if (!CI || all_of(VL, [](Value *V) {
4834               return cast<CmpInst>(V)->isCommutative();
4835             })) {
4836           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4837         } else {
4838           CmpInst::Predicate P0 = CI->getPredicate();
4839           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4840           assert(P0 != AltP0 &&
4841                  "Expected different main/alternate predicates.");
4842           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4843           Value *BaseOp0 = VL0->getOperand(0);
4844           Value *BaseOp1 = VL0->getOperand(1);
4845           // Collect operands - commute if it uses the swapped predicate or
4846           // alternate operation.
4847           for (Value *V : VL) {
4848             auto *Cmp = cast<CmpInst>(V);
4849             Value *LHS = Cmp->getOperand(0);
4850             Value *RHS = Cmp->getOperand(1);
4851             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4852             if (P0 == AltP0Swapped) {
4853               if (CI != Cmp && S.AltOp != Cmp &&
4854                   ((P0 == CurrentPred &&
4855                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4856                    (AltP0 == CurrentPred &&
4857                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4858                 std::swap(LHS, RHS);
4859             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4860               std::swap(LHS, RHS);
4861             }
4862             Left.push_back(LHS);
4863             Right.push_back(RHS);
4864           }
4865         }
4866         TE->setOperand(0, Left);
4867         TE->setOperand(1, Right);
4868         buildTree_rec(Left, Depth + 1, {TE, 0});
4869         buildTree_rec(Right, Depth + 1, {TE, 1});
4870         return;
4871       }
4872 
4873       TE->setOperandsInOrder();
4874       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4875         ValueList Operands;
4876         // Prepare the operand vector.
4877         for (Value *V : VL)
4878           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4879 
4880         buildTree_rec(Operands, Depth + 1, {TE, i});
4881       }
4882       return;
4883     }
4884     default:
4885       BS.cancelScheduling(VL, VL0);
4886       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4887                    ReuseShuffleIndicies);
4888       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4889       return;
4890   }
4891 }
4892 
4893 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4894   unsigned N = 1;
4895   Type *EltTy = T;
4896 
4897   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4898          isa<VectorType>(EltTy)) {
4899     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4900       // Check that struct is homogeneous.
4901       for (const auto *Ty : ST->elements())
4902         if (Ty != *ST->element_begin())
4903           return 0;
4904       N *= ST->getNumElements();
4905       EltTy = *ST->element_begin();
4906     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4907       N *= AT->getNumElements();
4908       EltTy = AT->getElementType();
4909     } else {
4910       auto *VT = cast<FixedVectorType>(EltTy);
4911       N *= VT->getNumElements();
4912       EltTy = VT->getElementType();
4913     }
4914   }
4915 
4916   if (!isValidElementType(EltTy))
4917     return 0;
4918   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4919   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4920     return 0;
4921   return N;
4922 }
4923 
4924 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4925                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4926   const auto *It = find_if(VL, [](Value *V) {
4927     return isa<ExtractElementInst, ExtractValueInst>(V);
4928   });
4929   assert(It != VL.end() && "Expected at least one extract instruction.");
4930   auto *E0 = cast<Instruction>(*It);
4931   assert(all_of(VL,
4932                 [](Value *V) {
4933                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4934                       V);
4935                 }) &&
4936          "Invalid opcode");
4937   // Check if all of the extracts come from the same vector and from the
4938   // correct offset.
4939   Value *Vec = E0->getOperand(0);
4940 
4941   CurrentOrder.clear();
4942 
4943   // We have to extract from a vector/aggregate with the same number of elements.
4944   unsigned NElts;
4945   if (E0->getOpcode() == Instruction::ExtractValue) {
4946     const DataLayout &DL = E0->getModule()->getDataLayout();
4947     NElts = canMapToVector(Vec->getType(), DL);
4948     if (!NElts)
4949       return false;
4950     // Check if load can be rewritten as load of vector.
4951     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4952     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4953       return false;
4954   } else {
4955     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4956   }
4957 
4958   if (NElts != VL.size())
4959     return false;
4960 
4961   // Check that all of the indices extract from the correct offset.
4962   bool ShouldKeepOrder = true;
4963   unsigned E = VL.size();
4964   // Assign to all items the initial value E + 1 so we can check if the extract
4965   // instruction index was used already.
4966   // Also, later we can check that all the indices are used and we have a
4967   // consecutive access in the extract instructions, by checking that no
4968   // element of CurrentOrder still has value E + 1.
4969   CurrentOrder.assign(E, E);
4970   unsigned I = 0;
4971   for (; I < E; ++I) {
4972     auto *Inst = dyn_cast<Instruction>(VL[I]);
4973     if (!Inst)
4974       continue;
4975     if (Inst->getOperand(0) != Vec)
4976       break;
4977     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4978       if (isa<UndefValue>(EE->getIndexOperand()))
4979         continue;
4980     Optional<unsigned> Idx = getExtractIndex(Inst);
4981     if (!Idx)
4982       break;
4983     const unsigned ExtIdx = *Idx;
4984     if (ExtIdx != I) {
4985       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4986         break;
4987       ShouldKeepOrder = false;
4988       CurrentOrder[ExtIdx] = I;
4989     } else {
4990       if (CurrentOrder[I] != E)
4991         break;
4992       CurrentOrder[I] = I;
4993     }
4994   }
4995   if (I < E) {
4996     CurrentOrder.clear();
4997     return false;
4998   }
4999   if (ShouldKeepOrder)
5000     CurrentOrder.clear();
5001 
5002   return ShouldKeepOrder;
5003 }
5004 
5005 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5006                                     ArrayRef<Value *> VectorizedVals) const {
5007   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5008          all_of(I->users(), [this](User *U) {
5009            return ScalarToTreeEntry.count(U) > 0 ||
5010                   isVectorLikeInstWithConstOps(U) ||
5011                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5012          });
5013 }
5014 
5015 static std::pair<InstructionCost, InstructionCost>
5016 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5017                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5018   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5019 
5020   // Calculate the cost of the scalar and vector calls.
5021   SmallVector<Type *, 4> VecTys;
5022   for (Use &Arg : CI->args())
5023     VecTys.push_back(
5024         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5025   FastMathFlags FMF;
5026   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5027     FMF = FPCI->getFastMathFlags();
5028   SmallVector<const Value *> Arguments(CI->args());
5029   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5030                                     dyn_cast<IntrinsicInst>(CI));
5031   auto IntrinsicCost =
5032     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5033 
5034   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5035                                      VecTy->getNumElements())),
5036                             false /*HasGlobalPred*/);
5037   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5038   auto LibCost = IntrinsicCost;
5039   if (!CI->isNoBuiltin() && VecFunc) {
5040     // Calculate the cost of the vector library call.
5041     // If the corresponding vector call is cheaper, return its cost.
5042     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5043                                     TTI::TCK_RecipThroughput);
5044   }
5045   return {IntrinsicCost, LibCost};
5046 }
5047 
5048 /// Compute the cost of creating a vector of type \p VecTy containing the
5049 /// extracted values from \p VL.
5050 static InstructionCost
5051 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5052                    TargetTransformInfo::ShuffleKind ShuffleKind,
5053                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5054   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5055 
5056   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5057       VecTy->getNumElements() < NumOfParts)
5058     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5059 
5060   bool AllConsecutive = true;
5061   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5062   unsigned Idx = -1;
5063   InstructionCost Cost = 0;
5064 
5065   // Process extracts in blocks of EltsPerVector to check if the source vector
5066   // operand can be re-used directly. If not, add the cost of creating a shuffle
5067   // to extract the values into a vector register.
5068   for (auto *V : VL) {
5069     ++Idx;
5070 
5071     // Need to exclude undefs from analysis.
5072     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5073       continue;
5074 
5075     // Reached the start of a new vector registers.
5076     if (Idx % EltsPerVector == 0) {
5077       AllConsecutive = true;
5078       continue;
5079     }
5080 
5081     // Check all extracts for a vector register on the target directly
5082     // extract values in order.
5083     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5084     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5085       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5086       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5087                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5088     }
5089 
5090     if (AllConsecutive)
5091       continue;
5092 
5093     // Skip all indices, except for the last index per vector block.
5094     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5095       continue;
5096 
5097     // If we have a series of extracts which are not consecutive and hence
5098     // cannot re-use the source vector register directly, compute the shuffle
5099     // cost to extract the a vector with EltsPerVector elements.
5100     Cost += TTI.getShuffleCost(
5101         TargetTransformInfo::SK_PermuteSingleSrc,
5102         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5103   }
5104   return Cost;
5105 }
5106 
5107 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5108 /// operations operands.
5109 static void
5110 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5111                       ArrayRef<int> ReusesIndices,
5112                       const function_ref<bool(Instruction *)> IsAltOp,
5113                       SmallVectorImpl<int> &Mask,
5114                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5115                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5116   unsigned Sz = VL.size();
5117   Mask.assign(Sz, UndefMaskElem);
5118   SmallVector<int> OrderMask;
5119   if (!ReorderIndices.empty())
5120     inversePermutation(ReorderIndices, OrderMask);
5121   for (unsigned I = 0; I < Sz; ++I) {
5122     unsigned Idx = I;
5123     if (!ReorderIndices.empty())
5124       Idx = OrderMask[I];
5125     auto *OpInst = cast<Instruction>(VL[Idx]);
5126     if (IsAltOp(OpInst)) {
5127       Mask[I] = Sz + Idx;
5128       if (AltScalars)
5129         AltScalars->push_back(OpInst);
5130     } else {
5131       Mask[I] = Idx;
5132       if (OpScalars)
5133         OpScalars->push_back(OpInst);
5134     }
5135   }
5136   if (!ReusesIndices.empty()) {
5137     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5138     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5139       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5140     });
5141     Mask.swap(NewMask);
5142   }
5143 }
5144 
5145 /// Checks if the specified instruction \p I is an alternate operation for the
5146 /// given \p MainOp and \p AltOp instructions.
5147 static bool isAlternateInstruction(const Instruction *I,
5148                                    const Instruction *MainOp,
5149                                    const Instruction *AltOp) {
5150   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5151     auto *AltCI0 = cast<CmpInst>(AltOp);
5152     auto *CI = cast<CmpInst>(I);
5153     CmpInst::Predicate P0 = CI0->getPredicate();
5154     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5155     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5156     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5157     CmpInst::Predicate CurrentPred = CI->getPredicate();
5158     if (P0 == AltP0Swapped)
5159       return I == AltCI0 ||
5160              (I != MainOp &&
5161               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5162                                    CI->getOperand(0), CI->getOperand(1)));
5163     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5164   }
5165   return I->getOpcode() == AltOp->getOpcode();
5166 }
5167 
5168 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5169                                       ArrayRef<Value *> VectorizedVals) {
5170   ArrayRef<Value*> VL = E->Scalars;
5171 
5172   Type *ScalarTy = VL[0]->getType();
5173   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5174     ScalarTy = SI->getValueOperand()->getType();
5175   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5176     ScalarTy = CI->getOperand(0)->getType();
5177   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5178     ScalarTy = IE->getOperand(1)->getType();
5179   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5180   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5181 
5182   // If we have computed a smaller type for the expression, update VecTy so
5183   // that the costs will be accurate.
5184   if (MinBWs.count(VL[0]))
5185     VecTy = FixedVectorType::get(
5186         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5187   unsigned EntryVF = E->getVectorFactor();
5188   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5189 
5190   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5191   // FIXME: it tries to fix a problem with MSVC buildbots.
5192   TargetTransformInfo &TTIRef = *TTI;
5193   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5194                                VectorizedVals, E](InstructionCost &Cost) {
5195     DenseMap<Value *, int> ExtractVectorsTys;
5196     SmallPtrSet<Value *, 4> CheckedExtracts;
5197     for (auto *V : VL) {
5198       if (isa<UndefValue>(V))
5199         continue;
5200       // If all users of instruction are going to be vectorized and this
5201       // instruction itself is not going to be vectorized, consider this
5202       // instruction as dead and remove its cost from the final cost of the
5203       // vectorized tree.
5204       // Also, avoid adjusting the cost for extractelements with multiple uses
5205       // in different graph entries.
5206       const TreeEntry *VE = getTreeEntry(V);
5207       if (!CheckedExtracts.insert(V).second ||
5208           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5209           (VE && VE != E))
5210         continue;
5211       auto *EE = cast<ExtractElementInst>(V);
5212       Optional<unsigned> EEIdx = getExtractIndex(EE);
5213       if (!EEIdx)
5214         continue;
5215       unsigned Idx = *EEIdx;
5216       if (TTIRef.getNumberOfParts(VecTy) !=
5217           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5218         auto It =
5219             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5220         It->getSecond() = std::min<int>(It->second, Idx);
5221       }
5222       // Take credit for instruction that will become dead.
5223       if (EE->hasOneUse()) {
5224         Instruction *Ext = EE->user_back();
5225         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5226             all_of(Ext->users(),
5227                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5228           // Use getExtractWithExtendCost() to calculate the cost of
5229           // extractelement/ext pair.
5230           Cost -=
5231               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5232                                               EE->getVectorOperandType(), Idx);
5233           // Add back the cost of s|zext which is subtracted separately.
5234           Cost += TTIRef.getCastInstrCost(
5235               Ext->getOpcode(), Ext->getType(), EE->getType(),
5236               TTI::getCastContextHint(Ext), CostKind, Ext);
5237           continue;
5238         }
5239       }
5240       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5241                                         EE->getVectorOperandType(), Idx);
5242     }
5243     // Add a cost for subvector extracts/inserts if required.
5244     for (const auto &Data : ExtractVectorsTys) {
5245       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5246       unsigned NumElts = VecTy->getNumElements();
5247       if (Data.second % NumElts == 0)
5248         continue;
5249       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5250         unsigned Idx = (Data.second / NumElts) * NumElts;
5251         unsigned EENumElts = EEVTy->getNumElements();
5252         if (Idx + NumElts <= EENumElts) {
5253           Cost +=
5254               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5255                                     EEVTy, None, Idx, VecTy);
5256         } else {
5257           // Need to round up the subvector type vectorization factor to avoid a
5258           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5259           // <= EENumElts.
5260           auto *SubVT =
5261               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5262           Cost +=
5263               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5264                                     EEVTy, None, Idx, SubVT);
5265         }
5266       } else {
5267         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5268                                       VecTy, None, 0, EEVTy);
5269       }
5270     }
5271   };
5272   if (E->State == TreeEntry::NeedToGather) {
5273     if (allConstant(VL))
5274       return 0;
5275     if (isa<InsertElementInst>(VL[0]))
5276       return InstructionCost::getInvalid();
5277     SmallVector<int> Mask;
5278     SmallVector<const TreeEntry *> Entries;
5279     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5280         isGatherShuffledEntry(E, Mask, Entries);
5281     if (Shuffle.hasValue()) {
5282       InstructionCost GatherCost = 0;
5283       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5284         // Perfect match in the graph, will reuse the previously vectorized
5285         // node. Cost is 0.
5286         LLVM_DEBUG(
5287             dbgs()
5288             << "SLP: perfect diamond match for gather bundle that starts with "
5289             << *VL.front() << ".\n");
5290         if (NeedToShuffleReuses)
5291           GatherCost =
5292               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5293                                   FinalVecTy, E->ReuseShuffleIndices);
5294       } else {
5295         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5296                           << " entries for bundle that starts with "
5297                           << *VL.front() << ".\n");
5298         // Detected that instead of gather we can emit a shuffle of single/two
5299         // previously vectorized nodes. Add the cost of the permutation rather
5300         // than gather.
5301         ::addMask(Mask, E->ReuseShuffleIndices);
5302         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5303       }
5304       return GatherCost;
5305     }
5306     if ((E->getOpcode() == Instruction::ExtractElement ||
5307          all_of(E->Scalars,
5308                 [](Value *V) {
5309                   return isa<ExtractElementInst, UndefValue>(V);
5310                 })) &&
5311         allSameType(VL)) {
5312       // Check that gather of extractelements can be represented as just a
5313       // shuffle of a single/two vectors the scalars are extracted from.
5314       SmallVector<int> Mask;
5315       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5316           isFixedVectorShuffle(VL, Mask);
5317       if (ShuffleKind.hasValue()) {
5318         // Found the bunch of extractelement instructions that must be gathered
5319         // into a vector and can be represented as a permutation elements in a
5320         // single input vector or of 2 input vectors.
5321         InstructionCost Cost =
5322             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5323         AdjustExtractsCost(Cost);
5324         if (NeedToShuffleReuses)
5325           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5326                                       FinalVecTy, E->ReuseShuffleIndices);
5327         return Cost;
5328       }
5329     }
5330     if (isSplat(VL)) {
5331       // Found the broadcasting of the single scalar, calculate the cost as the
5332       // broadcast.
5333       assert(VecTy == FinalVecTy &&
5334              "No reused scalars expected for broadcast.");
5335       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5336                                  /*Mask=*/None, /*Index=*/0,
5337                                  /*SubTp=*/nullptr, /*Args=*/VL);
5338     }
5339     InstructionCost ReuseShuffleCost = 0;
5340     if (NeedToShuffleReuses)
5341       ReuseShuffleCost = TTI->getShuffleCost(
5342           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5343     // Improve gather cost for gather of loads, if we can group some of the
5344     // loads into vector loads.
5345     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5346         !E->isAltShuffle()) {
5347       BoUpSLP::ValueSet VectorizedLoads;
5348       unsigned StartIdx = 0;
5349       unsigned VF = VL.size() / 2;
5350       unsigned VectorizedCnt = 0;
5351       unsigned ScatterVectorizeCnt = 0;
5352       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5353       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5354         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5355              Cnt += VF) {
5356           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5357           if (!VectorizedLoads.count(Slice.front()) &&
5358               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5359             SmallVector<Value *> PointerOps;
5360             OrdersType CurrentOrder;
5361             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5362                                               *SE, CurrentOrder, PointerOps);
5363             switch (LS) {
5364             case LoadsState::Vectorize:
5365             case LoadsState::ScatterVectorize:
5366               // Mark the vectorized loads so that we don't vectorize them
5367               // again.
5368               if (LS == LoadsState::Vectorize)
5369                 ++VectorizedCnt;
5370               else
5371                 ++ScatterVectorizeCnt;
5372               VectorizedLoads.insert(Slice.begin(), Slice.end());
5373               // If we vectorized initial block, no need to try to vectorize it
5374               // again.
5375               if (Cnt == StartIdx)
5376                 StartIdx += VF;
5377               break;
5378             case LoadsState::Gather:
5379               break;
5380             }
5381           }
5382         }
5383         // Check if the whole array was vectorized already - exit.
5384         if (StartIdx >= VL.size())
5385           break;
5386         // Found vectorizable parts - exit.
5387         if (!VectorizedLoads.empty())
5388           break;
5389       }
5390       if (!VectorizedLoads.empty()) {
5391         InstructionCost GatherCost = 0;
5392         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5393         bool NeedInsertSubvectorAnalysis =
5394             !NumParts || (VL.size() / VF) > NumParts;
5395         // Get the cost for gathered loads.
5396         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5397           if (VectorizedLoads.contains(VL[I]))
5398             continue;
5399           GatherCost += getGatherCost(VL.slice(I, VF));
5400         }
5401         // The cost for vectorized loads.
5402         InstructionCost ScalarsCost = 0;
5403         for (Value *V : VectorizedLoads) {
5404           auto *LI = cast<LoadInst>(V);
5405           ScalarsCost += TTI->getMemoryOpCost(
5406               Instruction::Load, LI->getType(), LI->getAlign(),
5407               LI->getPointerAddressSpace(), CostKind, LI);
5408         }
5409         auto *LI = cast<LoadInst>(E->getMainOp());
5410         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5411         Align Alignment = LI->getAlign();
5412         GatherCost +=
5413             VectorizedCnt *
5414             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5415                                  LI->getPointerAddressSpace(), CostKind, LI);
5416         GatherCost += ScatterVectorizeCnt *
5417                       TTI->getGatherScatterOpCost(
5418                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5419                           /*VariableMask=*/false, Alignment, CostKind, LI);
5420         if (NeedInsertSubvectorAnalysis) {
5421           // Add the cost for the subvectors insert.
5422           for (int I = VF, E = VL.size(); I < E; I += VF)
5423             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5424                                               None, I, LoadTy);
5425         }
5426         return ReuseShuffleCost + GatherCost - ScalarsCost;
5427       }
5428     }
5429     return ReuseShuffleCost + getGatherCost(VL);
5430   }
5431   InstructionCost CommonCost = 0;
5432   SmallVector<int> Mask;
5433   if (!E->ReorderIndices.empty()) {
5434     SmallVector<int> NewMask;
5435     if (E->getOpcode() == Instruction::Store) {
5436       // For stores the order is actually a mask.
5437       NewMask.resize(E->ReorderIndices.size());
5438       copy(E->ReorderIndices, NewMask.begin());
5439     } else {
5440       inversePermutation(E->ReorderIndices, NewMask);
5441     }
5442     ::addMask(Mask, NewMask);
5443   }
5444   if (NeedToShuffleReuses)
5445     ::addMask(Mask, E->ReuseShuffleIndices);
5446   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5447     CommonCost =
5448         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5449   assert((E->State == TreeEntry::Vectorize ||
5450           E->State == TreeEntry::ScatterVectorize) &&
5451          "Unhandled state");
5452   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5453   Instruction *VL0 = E->getMainOp();
5454   unsigned ShuffleOrOp =
5455       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5456   switch (ShuffleOrOp) {
5457     case Instruction::PHI:
5458       return 0;
5459 
5460     case Instruction::ExtractValue:
5461     case Instruction::ExtractElement: {
5462       // The common cost of removal ExtractElement/ExtractValue instructions +
5463       // the cost of shuffles, if required to resuffle the original vector.
5464       if (NeedToShuffleReuses) {
5465         unsigned Idx = 0;
5466         for (unsigned I : E->ReuseShuffleIndices) {
5467           if (ShuffleOrOp == Instruction::ExtractElement) {
5468             auto *EE = cast<ExtractElementInst>(VL[I]);
5469             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5470                                                   EE->getVectorOperandType(),
5471                                                   *getExtractIndex(EE));
5472           } else {
5473             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5474                                                   VecTy, Idx);
5475             ++Idx;
5476           }
5477         }
5478         Idx = EntryVF;
5479         for (Value *V : VL) {
5480           if (ShuffleOrOp == Instruction::ExtractElement) {
5481             auto *EE = cast<ExtractElementInst>(V);
5482             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5483                                                   EE->getVectorOperandType(),
5484                                                   *getExtractIndex(EE));
5485           } else {
5486             --Idx;
5487             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5488                                                   VecTy, Idx);
5489           }
5490         }
5491       }
5492       if (ShuffleOrOp == Instruction::ExtractValue) {
5493         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5494           auto *EI = cast<Instruction>(VL[I]);
5495           // Take credit for instruction that will become dead.
5496           if (EI->hasOneUse()) {
5497             Instruction *Ext = EI->user_back();
5498             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5499                 all_of(Ext->users(),
5500                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5501               // Use getExtractWithExtendCost() to calculate the cost of
5502               // extractelement/ext pair.
5503               CommonCost -= TTI->getExtractWithExtendCost(
5504                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5505               // Add back the cost of s|zext which is subtracted separately.
5506               CommonCost += TTI->getCastInstrCost(
5507                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5508                   TTI::getCastContextHint(Ext), CostKind, Ext);
5509               continue;
5510             }
5511           }
5512           CommonCost -=
5513               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5514         }
5515       } else {
5516         AdjustExtractsCost(CommonCost);
5517       }
5518       return CommonCost;
5519     }
5520     case Instruction::InsertElement: {
5521       assert(E->ReuseShuffleIndices.empty() &&
5522              "Unique insertelements only are expected.");
5523       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5524 
5525       unsigned const NumElts = SrcVecTy->getNumElements();
5526       unsigned const NumScalars = VL.size();
5527       APInt DemandedElts = APInt::getZero(NumElts);
5528       // TODO: Add support for Instruction::InsertValue.
5529       SmallVector<int> Mask;
5530       if (!E->ReorderIndices.empty()) {
5531         inversePermutation(E->ReorderIndices, Mask);
5532         Mask.append(NumElts - NumScalars, UndefMaskElem);
5533       } else {
5534         Mask.assign(NumElts, UndefMaskElem);
5535         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5536       }
5537       unsigned Offset = *getInsertIndex(VL0);
5538       bool IsIdentity = true;
5539       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5540       Mask.swap(PrevMask);
5541       for (unsigned I = 0; I < NumScalars; ++I) {
5542         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5543         DemandedElts.setBit(InsertIdx);
5544         IsIdentity &= InsertIdx - Offset == I;
5545         Mask[InsertIdx - Offset] = I;
5546       }
5547       assert(Offset < NumElts && "Failed to find vector index offset");
5548 
5549       InstructionCost Cost = 0;
5550       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5551                                             /*Insert*/ true, /*Extract*/ false);
5552 
5553       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5554         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5555         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5556         Cost += TTI->getShuffleCost(
5557             TargetTransformInfo::SK_PermuteSingleSrc,
5558             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5559       } else if (!IsIdentity) {
5560         auto *FirstInsert =
5561             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5562               return !is_contained(E->Scalars,
5563                                    cast<Instruction>(V)->getOperand(0));
5564             }));
5565         if (isUndefVector(FirstInsert->getOperand(0))) {
5566           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5567         } else {
5568           SmallVector<int> InsertMask(NumElts);
5569           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5570           for (unsigned I = 0; I < NumElts; I++) {
5571             if (Mask[I] != UndefMaskElem)
5572               InsertMask[Offset + I] = NumElts + I;
5573           }
5574           Cost +=
5575               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5576         }
5577       }
5578 
5579       return Cost;
5580     }
5581     case Instruction::ZExt:
5582     case Instruction::SExt:
5583     case Instruction::FPToUI:
5584     case Instruction::FPToSI:
5585     case Instruction::FPExt:
5586     case Instruction::PtrToInt:
5587     case Instruction::IntToPtr:
5588     case Instruction::SIToFP:
5589     case Instruction::UIToFP:
5590     case Instruction::Trunc:
5591     case Instruction::FPTrunc:
5592     case Instruction::BitCast: {
5593       Type *SrcTy = VL0->getOperand(0)->getType();
5594       InstructionCost ScalarEltCost =
5595           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5596                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5597       if (NeedToShuffleReuses) {
5598         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5599       }
5600 
5601       // Calculate the cost of this instruction.
5602       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5603 
5604       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5605       InstructionCost VecCost = 0;
5606       // Check if the values are candidates to demote.
5607       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5608         VecCost = CommonCost + TTI->getCastInstrCost(
5609                                    E->getOpcode(), VecTy, SrcVecTy,
5610                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5611       }
5612       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5613       return VecCost - ScalarCost;
5614     }
5615     case Instruction::FCmp:
5616     case Instruction::ICmp:
5617     case Instruction::Select: {
5618       // Calculate the cost of this instruction.
5619       InstructionCost ScalarEltCost =
5620           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5621                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5622       if (NeedToShuffleReuses) {
5623         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5624       }
5625       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5626       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5627 
5628       // Check if all entries in VL are either compares or selects with compares
5629       // as condition that have the same predicates.
5630       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5631       bool First = true;
5632       for (auto *V : VL) {
5633         CmpInst::Predicate CurrentPred;
5634         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5635         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5636              !match(V, MatchCmp)) ||
5637             (!First && VecPred != CurrentPred)) {
5638           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5639           break;
5640         }
5641         First = false;
5642         VecPred = CurrentPred;
5643       }
5644 
5645       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5646           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5647       // Check if it is possible and profitable to use min/max for selects in
5648       // VL.
5649       //
5650       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5651       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5652         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5653                                           {VecTy, VecTy});
5654         InstructionCost IntrinsicCost =
5655             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5656         // If the selects are the only uses of the compares, they will be dead
5657         // and we can adjust the cost by removing their cost.
5658         if (IntrinsicAndUse.second)
5659           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5660                                                    MaskTy, VecPred, CostKind);
5661         VecCost = std::min(VecCost, IntrinsicCost);
5662       }
5663       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5664       return CommonCost + VecCost - ScalarCost;
5665     }
5666     case Instruction::FNeg:
5667     case Instruction::Add:
5668     case Instruction::FAdd:
5669     case Instruction::Sub:
5670     case Instruction::FSub:
5671     case Instruction::Mul:
5672     case Instruction::FMul:
5673     case Instruction::UDiv:
5674     case Instruction::SDiv:
5675     case Instruction::FDiv:
5676     case Instruction::URem:
5677     case Instruction::SRem:
5678     case Instruction::FRem:
5679     case Instruction::Shl:
5680     case Instruction::LShr:
5681     case Instruction::AShr:
5682     case Instruction::And:
5683     case Instruction::Or:
5684     case Instruction::Xor: {
5685       // Certain instructions can be cheaper to vectorize if they have a
5686       // constant second vector operand.
5687       TargetTransformInfo::OperandValueKind Op1VK =
5688           TargetTransformInfo::OK_AnyValue;
5689       TargetTransformInfo::OperandValueKind Op2VK =
5690           TargetTransformInfo::OK_UniformConstantValue;
5691       TargetTransformInfo::OperandValueProperties Op1VP =
5692           TargetTransformInfo::OP_None;
5693       TargetTransformInfo::OperandValueProperties Op2VP =
5694           TargetTransformInfo::OP_PowerOf2;
5695 
5696       // If all operands are exactly the same ConstantInt then set the
5697       // operand kind to OK_UniformConstantValue.
5698       // If instead not all operands are constants, then set the operand kind
5699       // to OK_AnyValue. If all operands are constants but not the same,
5700       // then set the operand kind to OK_NonUniformConstantValue.
5701       ConstantInt *CInt0 = nullptr;
5702       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5703         const Instruction *I = cast<Instruction>(VL[i]);
5704         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5705         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5706         if (!CInt) {
5707           Op2VK = TargetTransformInfo::OK_AnyValue;
5708           Op2VP = TargetTransformInfo::OP_None;
5709           break;
5710         }
5711         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5712             !CInt->getValue().isPowerOf2())
5713           Op2VP = TargetTransformInfo::OP_None;
5714         if (i == 0) {
5715           CInt0 = CInt;
5716           continue;
5717         }
5718         if (CInt0 != CInt)
5719           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5720       }
5721 
5722       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5723       InstructionCost ScalarEltCost =
5724           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5725                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5726       if (NeedToShuffleReuses) {
5727         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5728       }
5729       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5730       InstructionCost VecCost =
5731           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5732                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5733       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5734       return CommonCost + VecCost - ScalarCost;
5735     }
5736     case Instruction::GetElementPtr: {
5737       TargetTransformInfo::OperandValueKind Op1VK =
5738           TargetTransformInfo::OK_AnyValue;
5739       TargetTransformInfo::OperandValueKind Op2VK =
5740           TargetTransformInfo::OK_UniformConstantValue;
5741 
5742       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5743           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5744       if (NeedToShuffleReuses) {
5745         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5746       }
5747       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5748       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5749           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5750       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5751       return CommonCost + VecCost - ScalarCost;
5752     }
5753     case Instruction::Load: {
5754       // Cost of wide load - cost of scalar loads.
5755       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5756       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5757           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5758       if (NeedToShuffleReuses) {
5759         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5760       }
5761       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5762       InstructionCost VecLdCost;
5763       if (E->State == TreeEntry::Vectorize) {
5764         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5765                                          CostKind, VL0);
5766       } else {
5767         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5768         Align CommonAlignment = Alignment;
5769         for (Value *V : VL)
5770           CommonAlignment =
5771               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5772         VecLdCost = TTI->getGatherScatterOpCost(
5773             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5774             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5775       }
5776       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5777       return CommonCost + VecLdCost - ScalarLdCost;
5778     }
5779     case Instruction::Store: {
5780       // We know that we can merge the stores. Calculate the cost.
5781       bool IsReorder = !E->ReorderIndices.empty();
5782       auto *SI =
5783           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5784       Align Alignment = SI->getAlign();
5785       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5786           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5787       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5788       InstructionCost VecStCost = TTI->getMemoryOpCost(
5789           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5790       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5791       return CommonCost + VecStCost - ScalarStCost;
5792     }
5793     case Instruction::Call: {
5794       CallInst *CI = cast<CallInst>(VL0);
5795       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5796 
5797       // Calculate the cost of the scalar and vector calls.
5798       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5799       InstructionCost ScalarEltCost =
5800           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5801       if (NeedToShuffleReuses) {
5802         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5803       }
5804       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5805 
5806       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5807       InstructionCost VecCallCost =
5808           std::min(VecCallCosts.first, VecCallCosts.second);
5809 
5810       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5811                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5812                         << " for " << *CI << "\n");
5813 
5814       return CommonCost + VecCallCost - ScalarCallCost;
5815     }
5816     case Instruction::ShuffleVector: {
5817       assert(E->isAltShuffle() &&
5818              ((Instruction::isBinaryOp(E->getOpcode()) &&
5819                Instruction::isBinaryOp(E->getAltOpcode())) ||
5820               (Instruction::isCast(E->getOpcode()) &&
5821                Instruction::isCast(E->getAltOpcode())) ||
5822               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5823              "Invalid Shuffle Vector Operand");
5824       InstructionCost ScalarCost = 0;
5825       if (NeedToShuffleReuses) {
5826         for (unsigned Idx : E->ReuseShuffleIndices) {
5827           Instruction *I = cast<Instruction>(VL[Idx]);
5828           CommonCost -= TTI->getInstructionCost(I, CostKind);
5829         }
5830         for (Value *V : VL) {
5831           Instruction *I = cast<Instruction>(V);
5832           CommonCost += TTI->getInstructionCost(I, CostKind);
5833         }
5834       }
5835       for (Value *V : VL) {
5836         Instruction *I = cast<Instruction>(V);
5837         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5838         ScalarCost += TTI->getInstructionCost(I, CostKind);
5839       }
5840       // VecCost is equal to sum of the cost of creating 2 vectors
5841       // and the cost of creating shuffle.
5842       InstructionCost VecCost = 0;
5843       // Try to find the previous shuffle node with the same operands and same
5844       // main/alternate ops.
5845       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5846         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5847           if (TE.get() == E)
5848             break;
5849           if (TE->isAltShuffle() &&
5850               ((TE->getOpcode() == E->getOpcode() &&
5851                 TE->getAltOpcode() == E->getAltOpcode()) ||
5852                (TE->getOpcode() == E->getAltOpcode() &&
5853                 TE->getAltOpcode() == E->getOpcode())) &&
5854               TE->hasEqualOperands(*E))
5855             return true;
5856         }
5857         return false;
5858       };
5859       if (TryFindNodeWithEqualOperands()) {
5860         LLVM_DEBUG({
5861           dbgs() << "SLP: diamond match for alternate node found.\n";
5862           E->dump();
5863         });
5864         // No need to add new vector costs here since we're going to reuse
5865         // same main/alternate vector ops, just do different shuffling.
5866       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5867         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5868         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5869                                                CostKind);
5870       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5871         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5872                                           Builder.getInt1Ty(),
5873                                           CI0->getPredicate(), CostKind, VL0);
5874         VecCost += TTI->getCmpSelInstrCost(
5875             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5876             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5877             E->getAltOp());
5878       } else {
5879         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5880         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5881         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5882         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5883         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5884                                         TTI::CastContextHint::None, CostKind);
5885         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5886                                          TTI::CastContextHint::None, CostKind);
5887       }
5888 
5889       SmallVector<int> Mask;
5890       buildShuffleEntryMask(
5891           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5892           [E](Instruction *I) {
5893             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5894             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5895           },
5896           Mask);
5897       CommonCost =
5898           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5899       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5900       return CommonCost + VecCost - ScalarCost;
5901     }
5902     default:
5903       llvm_unreachable("Unknown instruction");
5904   }
5905 }
5906 
5907 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5908   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5909                     << VectorizableTree.size() << " is fully vectorizable .\n");
5910 
5911   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5912     SmallVector<int> Mask;
5913     return TE->State == TreeEntry::NeedToGather &&
5914            !any_of(TE->Scalars,
5915                    [this](Value *V) { return EphValues.contains(V); }) &&
5916            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5917             TE->Scalars.size() < Limit ||
5918             ((TE->getOpcode() == Instruction::ExtractElement ||
5919               all_of(TE->Scalars,
5920                      [](Value *V) {
5921                        return isa<ExtractElementInst, UndefValue>(V);
5922                      })) &&
5923              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5924             (TE->State == TreeEntry::NeedToGather &&
5925              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5926   };
5927 
5928   // We only handle trees of heights 1 and 2.
5929   if (VectorizableTree.size() == 1 &&
5930       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5931        (ForReduction &&
5932         AreVectorizableGathers(VectorizableTree[0].get(),
5933                                VectorizableTree[0]->Scalars.size()) &&
5934         VectorizableTree[0]->getVectorFactor() > 2)))
5935     return true;
5936 
5937   if (VectorizableTree.size() != 2)
5938     return false;
5939 
5940   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5941   // with the second gather nodes if they have less scalar operands rather than
5942   // the initial tree element (may be profitable to shuffle the second gather)
5943   // or they are extractelements, which form shuffle.
5944   SmallVector<int> Mask;
5945   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5946       AreVectorizableGathers(VectorizableTree[1].get(),
5947                              VectorizableTree[0]->Scalars.size()))
5948     return true;
5949 
5950   // Gathering cost would be too much for tiny trees.
5951   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5952       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5953        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5954     return false;
5955 
5956   return true;
5957 }
5958 
5959 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5960                                        TargetTransformInfo *TTI,
5961                                        bool MustMatchOrInst) {
5962   // Look past the root to find a source value. Arbitrarily follow the
5963   // path through operand 0 of any 'or'. Also, peek through optional
5964   // shift-left-by-multiple-of-8-bits.
5965   Value *ZextLoad = Root;
5966   const APInt *ShAmtC;
5967   bool FoundOr = false;
5968   while (!isa<ConstantExpr>(ZextLoad) &&
5969          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5970           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5971            ShAmtC->urem(8) == 0))) {
5972     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5973     ZextLoad = BinOp->getOperand(0);
5974     if (BinOp->getOpcode() == Instruction::Or)
5975       FoundOr = true;
5976   }
5977   // Check if the input is an extended load of the required or/shift expression.
5978   Value *Load;
5979   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5980       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5981     return false;
5982 
5983   // Require that the total load bit width is a legal integer type.
5984   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5985   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5986   Type *SrcTy = Load->getType();
5987   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5988   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5989     return false;
5990 
5991   // Everything matched - assume that we can fold the whole sequence using
5992   // load combining.
5993   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5994              << *(cast<Instruction>(Root)) << "\n");
5995 
5996   return true;
5997 }
5998 
5999 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6000   if (RdxKind != RecurKind::Or)
6001     return false;
6002 
6003   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6004   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6005   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6006                                     /* MatchOr */ false);
6007 }
6008 
6009 bool BoUpSLP::isLoadCombineCandidate() const {
6010   // Peek through a final sequence of stores and check if all operations are
6011   // likely to be load-combined.
6012   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6013   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6014     Value *X;
6015     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6016         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6017       return false;
6018   }
6019   return true;
6020 }
6021 
6022 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6023   // No need to vectorize inserts of gathered values.
6024   if (VectorizableTree.size() == 2 &&
6025       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6026       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6027     return true;
6028 
6029   // We can vectorize the tree if its size is greater than or equal to the
6030   // minimum size specified by the MinTreeSize command line option.
6031   if (VectorizableTree.size() >= MinTreeSize)
6032     return false;
6033 
6034   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6035   // can vectorize it if we can prove it fully vectorizable.
6036   if (isFullyVectorizableTinyTree(ForReduction))
6037     return false;
6038 
6039   assert(VectorizableTree.empty()
6040              ? ExternalUses.empty()
6041              : true && "We shouldn't have any external users");
6042 
6043   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6044   // vectorizable.
6045   return true;
6046 }
6047 
6048 InstructionCost BoUpSLP::getSpillCost() const {
6049   // Walk from the bottom of the tree to the top, tracking which values are
6050   // live. When we see a call instruction that is not part of our tree,
6051   // query TTI to see if there is a cost to keeping values live over it
6052   // (for example, if spills and fills are required).
6053   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6054   InstructionCost Cost = 0;
6055 
6056   SmallPtrSet<Instruction*, 4> LiveValues;
6057   Instruction *PrevInst = nullptr;
6058 
6059   // The entries in VectorizableTree are not necessarily ordered by their
6060   // position in basic blocks. Collect them and order them by dominance so later
6061   // instructions are guaranteed to be visited first. For instructions in
6062   // different basic blocks, we only scan to the beginning of the block, so
6063   // their order does not matter, as long as all instructions in a basic block
6064   // are grouped together. Using dominance ensures a deterministic order.
6065   SmallVector<Instruction *, 16> OrderedScalars;
6066   for (const auto &TEPtr : VectorizableTree) {
6067     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6068     if (!Inst)
6069       continue;
6070     OrderedScalars.push_back(Inst);
6071   }
6072   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6073     auto *NodeA = DT->getNode(A->getParent());
6074     auto *NodeB = DT->getNode(B->getParent());
6075     assert(NodeA && "Should only process reachable instructions");
6076     assert(NodeB && "Should only process reachable instructions");
6077     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6078            "Different nodes should have different DFS numbers");
6079     if (NodeA != NodeB)
6080       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6081     return B->comesBefore(A);
6082   });
6083 
6084   for (Instruction *Inst : OrderedScalars) {
6085     if (!PrevInst) {
6086       PrevInst = Inst;
6087       continue;
6088     }
6089 
6090     // Update LiveValues.
6091     LiveValues.erase(PrevInst);
6092     for (auto &J : PrevInst->operands()) {
6093       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6094         LiveValues.insert(cast<Instruction>(&*J));
6095     }
6096 
6097     LLVM_DEBUG({
6098       dbgs() << "SLP: #LV: " << LiveValues.size();
6099       for (auto *X : LiveValues)
6100         dbgs() << " " << X->getName();
6101       dbgs() << ", Looking at ";
6102       Inst->dump();
6103     });
6104 
6105     // Now find the sequence of instructions between PrevInst and Inst.
6106     unsigned NumCalls = 0;
6107     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6108                                  PrevInstIt =
6109                                      PrevInst->getIterator().getReverse();
6110     while (InstIt != PrevInstIt) {
6111       if (PrevInstIt == PrevInst->getParent()->rend()) {
6112         PrevInstIt = Inst->getParent()->rbegin();
6113         continue;
6114       }
6115 
6116       // Debug information does not impact spill cost.
6117       if ((isa<CallInst>(&*PrevInstIt) &&
6118            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6119           &*PrevInstIt != PrevInst)
6120         NumCalls++;
6121 
6122       ++PrevInstIt;
6123     }
6124 
6125     if (NumCalls) {
6126       SmallVector<Type*, 4> V;
6127       for (auto *II : LiveValues) {
6128         auto *ScalarTy = II->getType();
6129         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6130           ScalarTy = VectorTy->getElementType();
6131         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6132       }
6133       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6134     }
6135 
6136     PrevInst = Inst;
6137   }
6138 
6139   return Cost;
6140 }
6141 
6142 /// Check if two insertelement instructions are from the same buildvector.
6143 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6144                                             InsertElementInst *V) {
6145   // Instructions must be from the same basic blocks.
6146   if (VU->getParent() != V->getParent())
6147     return false;
6148   // Checks if 2 insertelements are from the same buildvector.
6149   if (VU->getType() != V->getType())
6150     return false;
6151   // Multiple used inserts are separate nodes.
6152   if (!VU->hasOneUse() && !V->hasOneUse())
6153     return false;
6154   auto *IE1 = VU;
6155   auto *IE2 = V;
6156   // Go through the vector operand of insertelement instructions trying to find
6157   // either VU as the original vector for IE2 or V as the original vector for
6158   // IE1.
6159   do {
6160     if (IE2 == VU || IE1 == V)
6161       return true;
6162     if (IE1) {
6163       if (IE1 != VU && !IE1->hasOneUse())
6164         IE1 = nullptr;
6165       else
6166         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6167     }
6168     if (IE2) {
6169       if (IE2 != V && !IE2->hasOneUse())
6170         IE2 = nullptr;
6171       else
6172         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6173     }
6174   } while (IE1 || IE2);
6175   return false;
6176 }
6177 
6178 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6179   InstructionCost Cost = 0;
6180   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6181                     << VectorizableTree.size() << ".\n");
6182 
6183   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6184 
6185   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6186     TreeEntry &TE = *VectorizableTree[I];
6187 
6188     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6189     Cost += C;
6190     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6191                       << " for bundle that starts with " << *TE.Scalars[0]
6192                       << ".\n"
6193                       << "SLP: Current total cost = " << Cost << "\n");
6194   }
6195 
6196   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6197   InstructionCost ExtractCost = 0;
6198   SmallVector<unsigned> VF;
6199   SmallVector<SmallVector<int>> ShuffleMask;
6200   SmallVector<Value *> FirstUsers;
6201   SmallVector<APInt> DemandedElts;
6202   for (ExternalUser &EU : ExternalUses) {
6203     // We only add extract cost once for the same scalar.
6204     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6205         !ExtractCostCalculated.insert(EU.Scalar).second)
6206       continue;
6207 
6208     // Uses by ephemeral values are free (because the ephemeral value will be
6209     // removed prior to code generation, and so the extraction will be
6210     // removed as well).
6211     if (EphValues.count(EU.User))
6212       continue;
6213 
6214     // No extract cost for vector "scalar"
6215     if (isa<FixedVectorType>(EU.Scalar->getType()))
6216       continue;
6217 
6218     // Already counted the cost for external uses when tried to adjust the cost
6219     // for extractelements, no need to add it again.
6220     if (isa<ExtractElementInst>(EU.Scalar))
6221       continue;
6222 
6223     // If found user is an insertelement, do not calculate extract cost but try
6224     // to detect it as a final shuffled/identity match.
6225     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6226       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6227         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6228         if (InsertIdx) {
6229           auto *It = find_if(FirstUsers, [VU](Value *V) {
6230             return areTwoInsertFromSameBuildVector(VU,
6231                                                    cast<InsertElementInst>(V));
6232           });
6233           int VecId = -1;
6234           if (It == FirstUsers.end()) {
6235             VF.push_back(FTy->getNumElements());
6236             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6237             // Find the insertvector, vectorized in tree, if any.
6238             Value *Base = VU;
6239             while (isa<InsertElementInst>(Base)) {
6240               // Build the mask for the vectorized insertelement instructions.
6241               if (const TreeEntry *E = getTreeEntry(Base)) {
6242                 VU = cast<InsertElementInst>(Base);
6243                 do {
6244                   int Idx = E->findLaneForValue(Base);
6245                   ShuffleMask.back()[Idx] = Idx;
6246                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6247                 } while (E == getTreeEntry(Base));
6248                 break;
6249               }
6250               Base = cast<InsertElementInst>(Base)->getOperand(0);
6251             }
6252             FirstUsers.push_back(VU);
6253             DemandedElts.push_back(APInt::getZero(VF.back()));
6254             VecId = FirstUsers.size() - 1;
6255           } else {
6256             VecId = std::distance(FirstUsers.begin(), It);
6257           }
6258           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6259           DemandedElts[VecId].setBit(*InsertIdx);
6260           continue;
6261         }
6262       }
6263     }
6264 
6265     // If we plan to rewrite the tree in a smaller type, we will need to sign
6266     // extend the extracted value back to the original type. Here, we account
6267     // for the extract and the added cost of the sign extend if needed.
6268     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6269     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6270     if (MinBWs.count(ScalarRoot)) {
6271       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6272       auto Extend =
6273           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6274       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6275       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6276                                                    VecTy, EU.Lane);
6277     } else {
6278       ExtractCost +=
6279           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6280     }
6281   }
6282 
6283   InstructionCost SpillCost = getSpillCost();
6284   Cost += SpillCost + ExtractCost;
6285   if (FirstUsers.size() == 1) {
6286     int Limit = ShuffleMask.front().size() * 2;
6287     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6288         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6289       InstructionCost C = TTI->getShuffleCost(
6290           TTI::SK_PermuteSingleSrc,
6291           cast<FixedVectorType>(FirstUsers.front()->getType()),
6292           ShuffleMask.front());
6293       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6294                         << " for final shuffle of insertelement external users "
6295                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6296                         << "SLP: Current total cost = " << Cost << "\n");
6297       Cost += C;
6298     }
6299     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6300         cast<FixedVectorType>(FirstUsers.front()->getType()),
6301         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6302     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6303                       << " for insertelements gather.\n"
6304                       << "SLP: Current total cost = " << Cost << "\n");
6305     Cost -= InsertCost;
6306   } else if (FirstUsers.size() >= 2) {
6307     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6308     // Combined masks of the first 2 vectors.
6309     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6310     copy(ShuffleMask.front(), CombinedMask.begin());
6311     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6312     auto *VecTy = FixedVectorType::get(
6313         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6314         MaxVF);
6315     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6316       if (ShuffleMask[1][I] != UndefMaskElem) {
6317         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6318         CombinedDemandedElts.setBit(I);
6319       }
6320     }
6321     InstructionCost C =
6322         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6323     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6324                       << " for final shuffle of vector node and external "
6325                          "insertelement users "
6326                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6327                       << "SLP: Current total cost = " << Cost << "\n");
6328     Cost += C;
6329     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6330         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6331     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6332                       << " for insertelements gather.\n"
6333                       << "SLP: Current total cost = " << Cost << "\n");
6334     Cost -= InsertCost;
6335     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6336       // Other elements - permutation of 2 vectors (the initial one and the
6337       // next Ith incoming vector).
6338       unsigned VF = ShuffleMask[I].size();
6339       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6340         int Mask = ShuffleMask[I][Idx];
6341         if (Mask != UndefMaskElem)
6342           CombinedMask[Idx] = MaxVF + Mask;
6343         else if (CombinedMask[Idx] != UndefMaskElem)
6344           CombinedMask[Idx] = Idx;
6345       }
6346       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6347         if (CombinedMask[Idx] != UndefMaskElem)
6348           CombinedMask[Idx] = Idx;
6349       InstructionCost C =
6350           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6351       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6352                         << " for final shuffle of vector node and external "
6353                            "insertelement users "
6354                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6355                         << "SLP: Current total cost = " << Cost << "\n");
6356       Cost += C;
6357       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6358           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6359           /*Insert*/ true, /*Extract*/ false);
6360       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6361                         << " for insertelements gather.\n"
6362                         << "SLP: Current total cost = " << Cost << "\n");
6363       Cost -= InsertCost;
6364     }
6365   }
6366 
6367 #ifndef NDEBUG
6368   SmallString<256> Str;
6369   {
6370     raw_svector_ostream OS(Str);
6371     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6372        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6373        << "SLP: Total Cost = " << Cost << ".\n";
6374   }
6375   LLVM_DEBUG(dbgs() << Str);
6376   if (ViewSLPTree)
6377     ViewGraph(this, "SLP" + F->getName(), false, Str);
6378 #endif
6379 
6380   return Cost;
6381 }
6382 
6383 Optional<TargetTransformInfo::ShuffleKind>
6384 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6385                                SmallVectorImpl<const TreeEntry *> &Entries) {
6386   // TODO: currently checking only for Scalars in the tree entry, need to count
6387   // reused elements too for better cost estimation.
6388   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6389   Entries.clear();
6390   // Build a lists of values to tree entries.
6391   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6392   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6393     if (EntryPtr.get() == TE)
6394       break;
6395     if (EntryPtr->State != TreeEntry::NeedToGather)
6396       continue;
6397     for (Value *V : EntryPtr->Scalars)
6398       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6399   }
6400   // Find all tree entries used by the gathered values. If no common entries
6401   // found - not a shuffle.
6402   // Here we build a set of tree nodes for each gathered value and trying to
6403   // find the intersection between these sets. If we have at least one common
6404   // tree node for each gathered value - we have just a permutation of the
6405   // single vector. If we have 2 different sets, we're in situation where we
6406   // have a permutation of 2 input vectors.
6407   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6408   DenseMap<Value *, int> UsedValuesEntry;
6409   for (Value *V : TE->Scalars) {
6410     if (isa<UndefValue>(V))
6411       continue;
6412     // Build a list of tree entries where V is used.
6413     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6414     auto It = ValueToTEs.find(V);
6415     if (It != ValueToTEs.end())
6416       VToTEs = It->second;
6417     if (const TreeEntry *VTE = getTreeEntry(V))
6418       VToTEs.insert(VTE);
6419     if (VToTEs.empty())
6420       return None;
6421     if (UsedTEs.empty()) {
6422       // The first iteration, just insert the list of nodes to vector.
6423       UsedTEs.push_back(VToTEs);
6424     } else {
6425       // Need to check if there are any previously used tree nodes which use V.
6426       // If there are no such nodes, consider that we have another one input
6427       // vector.
6428       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6429       unsigned Idx = 0;
6430       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6431         // Do we have a non-empty intersection of previously listed tree entries
6432         // and tree entries using current V?
6433         set_intersect(VToTEs, Set);
6434         if (!VToTEs.empty()) {
6435           // Yes, write the new subset and continue analysis for the next
6436           // scalar.
6437           Set.swap(VToTEs);
6438           break;
6439         }
6440         VToTEs = SavedVToTEs;
6441         ++Idx;
6442       }
6443       // No non-empty intersection found - need to add a second set of possible
6444       // source vectors.
6445       if (Idx == UsedTEs.size()) {
6446         // If the number of input vectors is greater than 2 - not a permutation,
6447         // fallback to the regular gather.
6448         if (UsedTEs.size() == 2)
6449           return None;
6450         UsedTEs.push_back(SavedVToTEs);
6451         Idx = UsedTEs.size() - 1;
6452       }
6453       UsedValuesEntry.try_emplace(V, Idx);
6454     }
6455   }
6456 
6457   if (UsedTEs.empty()) {
6458     assert(all_of(TE->Scalars, UndefValue::classof) &&
6459            "Expected vector of undefs only.");
6460     return None;
6461   }
6462 
6463   unsigned VF = 0;
6464   if (UsedTEs.size() == 1) {
6465     // Try to find the perfect match in another gather node at first.
6466     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6467       return EntryPtr->isSame(TE->Scalars);
6468     });
6469     if (It != UsedTEs.front().end()) {
6470       Entries.push_back(*It);
6471       std::iota(Mask.begin(), Mask.end(), 0);
6472       return TargetTransformInfo::SK_PermuteSingleSrc;
6473     }
6474     // No perfect match, just shuffle, so choose the first tree node.
6475     Entries.push_back(*UsedTEs.front().begin());
6476   } else {
6477     // Try to find nodes with the same vector factor.
6478     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6479     DenseMap<int, const TreeEntry *> VFToTE;
6480     for (const TreeEntry *TE : UsedTEs.front())
6481       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6482     for (const TreeEntry *TE : UsedTEs.back()) {
6483       auto It = VFToTE.find(TE->getVectorFactor());
6484       if (It != VFToTE.end()) {
6485         VF = It->first;
6486         Entries.push_back(It->second);
6487         Entries.push_back(TE);
6488         break;
6489       }
6490     }
6491     // No 2 source vectors with the same vector factor - give up and do regular
6492     // gather.
6493     if (Entries.empty())
6494       return None;
6495   }
6496 
6497   // Build a shuffle mask for better cost estimation and vector emission.
6498   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6499     Value *V = TE->Scalars[I];
6500     if (isa<UndefValue>(V))
6501       continue;
6502     unsigned Idx = UsedValuesEntry.lookup(V);
6503     const TreeEntry *VTE = Entries[Idx];
6504     int FoundLane = VTE->findLaneForValue(V);
6505     Mask[I] = Idx * VF + FoundLane;
6506     // Extra check required by isSingleSourceMaskImpl function (called by
6507     // ShuffleVectorInst::isSingleSourceMask).
6508     if (Mask[I] >= 2 * E)
6509       return None;
6510   }
6511   switch (Entries.size()) {
6512   case 1:
6513     return TargetTransformInfo::SK_PermuteSingleSrc;
6514   case 2:
6515     return TargetTransformInfo::SK_PermuteTwoSrc;
6516   default:
6517     break;
6518   }
6519   return None;
6520 }
6521 
6522 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6523                                        const APInt &ShuffledIndices,
6524                                        bool NeedToShuffle) const {
6525   InstructionCost Cost =
6526       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6527                                     /*Extract*/ false);
6528   if (NeedToShuffle)
6529     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6530   return Cost;
6531 }
6532 
6533 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6534   // Find the type of the operands in VL.
6535   Type *ScalarTy = VL[0]->getType();
6536   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6537     ScalarTy = SI->getValueOperand()->getType();
6538   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6539   bool DuplicateNonConst = false;
6540   // Find the cost of inserting/extracting values from the vector.
6541   // Check if the same elements are inserted several times and count them as
6542   // shuffle candidates.
6543   APInt ShuffledElements = APInt::getZero(VL.size());
6544   DenseSet<Value *> UniqueElements;
6545   // Iterate in reverse order to consider insert elements with the high cost.
6546   for (unsigned I = VL.size(); I > 0; --I) {
6547     unsigned Idx = I - 1;
6548     // No need to shuffle duplicates for constants.
6549     if (isConstant(VL[Idx])) {
6550       ShuffledElements.setBit(Idx);
6551       continue;
6552     }
6553     if (!UniqueElements.insert(VL[Idx]).second) {
6554       DuplicateNonConst = true;
6555       ShuffledElements.setBit(Idx);
6556     }
6557   }
6558   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6559 }
6560 
6561 // Perform operand reordering on the instructions in VL and return the reordered
6562 // operands in Left and Right.
6563 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6564                                              SmallVectorImpl<Value *> &Left,
6565                                              SmallVectorImpl<Value *> &Right,
6566                                              const DataLayout &DL,
6567                                              ScalarEvolution &SE,
6568                                              const BoUpSLP &R) {
6569   if (VL.empty())
6570     return;
6571   VLOperands Ops(VL, DL, SE, R);
6572   // Reorder the operands in place.
6573   Ops.reorder();
6574   Left = Ops.getVL(0);
6575   Right = Ops.getVL(1);
6576 }
6577 
6578 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6579   // Get the basic block this bundle is in. All instructions in the bundle
6580   // should be in this block.
6581   auto *Front = E->getMainOp();
6582   auto *BB = Front->getParent();
6583   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6584     auto *I = cast<Instruction>(V);
6585     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6586   }));
6587 
6588   auto &&FindLastInst = [E, Front]() {
6589     Instruction *LastInst = Front;
6590     for (Value *V : E->Scalars) {
6591       auto *I = dyn_cast<Instruction>(V);
6592       if (!I)
6593         continue;
6594       if (LastInst->comesBefore(I))
6595         LastInst = I;
6596     }
6597     return LastInst;
6598   };
6599 
6600   auto &&FindFirstInst = [E, Front]() {
6601     Instruction *FirstInst = Front;
6602     for (Value *V : E->Scalars) {
6603       auto *I = dyn_cast<Instruction>(V);
6604       if (!I)
6605         continue;
6606       if (I->comesBefore(FirstInst))
6607         FirstInst = I;
6608     }
6609     return FirstInst;
6610   };
6611 
6612   // Set the insert point to the beginning of the basic block if the entry
6613   // should not be scheduled.
6614   if (E->State != TreeEntry::NeedToGather &&
6615       doesNotNeedToSchedule(E->Scalars)) {
6616     BasicBlock::iterator InsertPt;
6617     if (all_of(E->Scalars, isUsedOutsideBlock))
6618       InsertPt = FindLastInst()->getIterator();
6619     else
6620       InsertPt = FindFirstInst()->getIterator();
6621     Builder.SetInsertPoint(BB, InsertPt);
6622     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6623     return;
6624   }
6625 
6626   // The last instruction in the bundle in program order.
6627   Instruction *LastInst = nullptr;
6628 
6629   // Find the last instruction. The common case should be that BB has been
6630   // scheduled, and the last instruction is VL.back(). So we start with
6631   // VL.back() and iterate over schedule data until we reach the end of the
6632   // bundle. The end of the bundle is marked by null ScheduleData.
6633   if (BlocksSchedules.count(BB)) {
6634     Value *V = E->isOneOf(E->Scalars.back());
6635     if (doesNotNeedToBeScheduled(V))
6636       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6637     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6638     if (Bundle && Bundle->isPartOfBundle())
6639       for (; Bundle; Bundle = Bundle->NextInBundle)
6640         if (Bundle->OpValue == Bundle->Inst)
6641           LastInst = Bundle->Inst;
6642   }
6643 
6644   // LastInst can still be null at this point if there's either not an entry
6645   // for BB in BlocksSchedules or there's no ScheduleData available for
6646   // VL.back(). This can be the case if buildTree_rec aborts for various
6647   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6648   // size is reached, etc.). ScheduleData is initialized in the scheduling
6649   // "dry-run".
6650   //
6651   // If this happens, we can still find the last instruction by brute force. We
6652   // iterate forwards from Front (inclusive) until we either see all
6653   // instructions in the bundle or reach the end of the block. If Front is the
6654   // last instruction in program order, LastInst will be set to Front, and we
6655   // will visit all the remaining instructions in the block.
6656   //
6657   // One of the reasons we exit early from buildTree_rec is to place an upper
6658   // bound on compile-time. Thus, taking an additional compile-time hit here is
6659   // not ideal. However, this should be exceedingly rare since it requires that
6660   // we both exit early from buildTree_rec and that the bundle be out-of-order
6661   // (causing us to iterate all the way to the end of the block).
6662   if (!LastInst)
6663     LastInst = FindLastInst();
6664   assert(LastInst && "Failed to find last instruction in bundle");
6665 
6666   // Set the insertion point after the last instruction in the bundle. Set the
6667   // debug location to Front.
6668   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6669   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6670 }
6671 
6672 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6673   // List of instructions/lanes from current block and/or the blocks which are
6674   // part of the current loop. These instructions will be inserted at the end to
6675   // make it possible to optimize loops and hoist invariant instructions out of
6676   // the loops body with better chances for success.
6677   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6678   SmallSet<int, 4> PostponedIndices;
6679   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6680   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6681     SmallPtrSet<BasicBlock *, 4> Visited;
6682     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6683       InsertBB = InsertBB->getSinglePredecessor();
6684     return InsertBB && InsertBB == InstBB;
6685   };
6686   for (int I = 0, E = VL.size(); I < E; ++I) {
6687     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6688       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6689            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6690           PostponedIndices.insert(I).second)
6691         PostponedInsts.emplace_back(Inst, I);
6692   }
6693 
6694   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6695     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6696     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6697     if (!InsElt)
6698       return Vec;
6699     GatherShuffleSeq.insert(InsElt);
6700     CSEBlocks.insert(InsElt->getParent());
6701     // Add to our 'need-to-extract' list.
6702     if (TreeEntry *Entry = getTreeEntry(V)) {
6703       // Find which lane we need to extract.
6704       unsigned FoundLane = Entry->findLaneForValue(V);
6705       ExternalUses.emplace_back(V, InsElt, FoundLane);
6706     }
6707     return Vec;
6708   };
6709   Value *Val0 =
6710       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6711   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6712   Value *Vec = PoisonValue::get(VecTy);
6713   SmallVector<int> NonConsts;
6714   // Insert constant values at first.
6715   for (int I = 0, E = VL.size(); I < E; ++I) {
6716     if (PostponedIndices.contains(I))
6717       continue;
6718     if (!isConstant(VL[I])) {
6719       NonConsts.push_back(I);
6720       continue;
6721     }
6722     Vec = CreateInsertElement(Vec, VL[I], I);
6723   }
6724   // Insert non-constant values.
6725   for (int I : NonConsts)
6726     Vec = CreateInsertElement(Vec, VL[I], I);
6727   // Append instructions, which are/may be part of the loop, in the end to make
6728   // it possible to hoist non-loop-based instructions.
6729   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6730     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6731 
6732   return Vec;
6733 }
6734 
6735 namespace {
6736 /// Merges shuffle masks and emits final shuffle instruction, if required.
6737 class ShuffleInstructionBuilder {
6738   IRBuilderBase &Builder;
6739   const unsigned VF = 0;
6740   bool IsFinalized = false;
6741   SmallVector<int, 4> Mask;
6742   /// Holds all of the instructions that we gathered.
6743   SetVector<Instruction *> &GatherShuffleSeq;
6744   /// A list of blocks that we are going to CSE.
6745   SetVector<BasicBlock *> &CSEBlocks;
6746 
6747 public:
6748   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6749                             SetVector<Instruction *> &GatherShuffleSeq,
6750                             SetVector<BasicBlock *> &CSEBlocks)
6751       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6752         CSEBlocks(CSEBlocks) {}
6753 
6754   /// Adds a mask, inverting it before applying.
6755   void addInversedMask(ArrayRef<unsigned> SubMask) {
6756     if (SubMask.empty())
6757       return;
6758     SmallVector<int, 4> NewMask;
6759     inversePermutation(SubMask, NewMask);
6760     addMask(NewMask);
6761   }
6762 
6763   /// Functions adds masks, merging them into  single one.
6764   void addMask(ArrayRef<unsigned> SubMask) {
6765     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6766     addMask(NewMask);
6767   }
6768 
6769   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6770 
6771   Value *finalize(Value *V) {
6772     IsFinalized = true;
6773     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6774     if (VF == ValueVF && Mask.empty())
6775       return V;
6776     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6777     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6778     addMask(NormalizedMask);
6779 
6780     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6781       return V;
6782     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6783     if (auto *I = dyn_cast<Instruction>(Vec)) {
6784       GatherShuffleSeq.insert(I);
6785       CSEBlocks.insert(I->getParent());
6786     }
6787     return Vec;
6788   }
6789 
6790   ~ShuffleInstructionBuilder() {
6791     assert((IsFinalized || Mask.empty()) &&
6792            "Shuffle construction must be finalized.");
6793   }
6794 };
6795 } // namespace
6796 
6797 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6798   const unsigned VF = VL.size();
6799   InstructionsState S = getSameOpcode(VL);
6800   if (S.getOpcode()) {
6801     if (TreeEntry *E = getTreeEntry(S.OpValue))
6802       if (E->isSame(VL)) {
6803         Value *V = vectorizeTree(E);
6804         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6805           if (!E->ReuseShuffleIndices.empty()) {
6806             // Reshuffle to get only unique values.
6807             // If some of the scalars are duplicated in the vectorization tree
6808             // entry, we do not vectorize them but instead generate a mask for
6809             // the reuses. But if there are several users of the same entry,
6810             // they may have different vectorization factors. This is especially
6811             // important for PHI nodes. In this case, we need to adapt the
6812             // resulting instruction for the user vectorization factor and have
6813             // to reshuffle it again to take only unique elements of the vector.
6814             // Without this code the function incorrectly returns reduced vector
6815             // instruction with the same elements, not with the unique ones.
6816 
6817             // block:
6818             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6819             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6820             // ... (use %2)
6821             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6822             // br %block
6823             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6824             SmallSet<int, 4> UsedIdxs;
6825             int Pos = 0;
6826             int Sz = VL.size();
6827             for (int Idx : E->ReuseShuffleIndices) {
6828               if (Idx != Sz && Idx != UndefMaskElem &&
6829                   UsedIdxs.insert(Idx).second)
6830                 UniqueIdxs[Idx] = Pos;
6831               ++Pos;
6832             }
6833             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6834                                             "less than original vector size.");
6835             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6836             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6837           } else {
6838             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6839                    "Expected vectorization factor less "
6840                    "than original vector size.");
6841             SmallVector<int> UniformMask(VF, 0);
6842             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6843             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6844           }
6845           if (auto *I = dyn_cast<Instruction>(V)) {
6846             GatherShuffleSeq.insert(I);
6847             CSEBlocks.insert(I->getParent());
6848           }
6849         }
6850         return V;
6851       }
6852   }
6853 
6854   // Can't vectorize this, so simply build a new vector with each lane
6855   // corresponding to the requested value.
6856   return createBuildVector(VL);
6857 }
6858 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6859   unsigned VF = VL.size();
6860   // Exploit possible reuse of values across lanes.
6861   SmallVector<int> ReuseShuffleIndicies;
6862   SmallVector<Value *> UniqueValues;
6863   if (VL.size() > 2) {
6864     DenseMap<Value *, unsigned> UniquePositions;
6865     unsigned NumValues =
6866         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6867                                     return !isa<UndefValue>(V);
6868                                   }).base());
6869     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6870     int UniqueVals = 0;
6871     for (Value *V : VL.drop_back(VL.size() - VF)) {
6872       if (isa<UndefValue>(V)) {
6873         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6874         continue;
6875       }
6876       if (isConstant(V)) {
6877         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6878         UniqueValues.emplace_back(V);
6879         continue;
6880       }
6881       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6882       ReuseShuffleIndicies.emplace_back(Res.first->second);
6883       if (Res.second) {
6884         UniqueValues.emplace_back(V);
6885         ++UniqueVals;
6886       }
6887     }
6888     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6889       // Emit pure splat vector.
6890       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6891                                   UndefMaskElem);
6892     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6893       ReuseShuffleIndicies.clear();
6894       UniqueValues.clear();
6895       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6896     }
6897     UniqueValues.append(VF - UniqueValues.size(),
6898                         PoisonValue::get(VL[0]->getType()));
6899     VL = UniqueValues;
6900   }
6901 
6902   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6903                                            CSEBlocks);
6904   Value *Vec = gather(VL);
6905   if (!ReuseShuffleIndicies.empty()) {
6906     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6907     Vec = ShuffleBuilder.finalize(Vec);
6908   }
6909   return Vec;
6910 }
6911 
6912 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6913   IRBuilder<>::InsertPointGuard Guard(Builder);
6914 
6915   if (E->VectorizedValue) {
6916     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6917     return E->VectorizedValue;
6918   }
6919 
6920   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6921   unsigned VF = E->getVectorFactor();
6922   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6923                                            CSEBlocks);
6924   if (E->State == TreeEntry::NeedToGather) {
6925     if (E->getMainOp())
6926       setInsertPointAfterBundle(E);
6927     Value *Vec;
6928     SmallVector<int> Mask;
6929     SmallVector<const TreeEntry *> Entries;
6930     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6931         isGatherShuffledEntry(E, Mask, Entries);
6932     if (Shuffle.hasValue()) {
6933       assert((Entries.size() == 1 || Entries.size() == 2) &&
6934              "Expected shuffle of 1 or 2 entries.");
6935       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6936                                         Entries.back()->VectorizedValue, Mask);
6937       if (auto *I = dyn_cast<Instruction>(Vec)) {
6938         GatherShuffleSeq.insert(I);
6939         CSEBlocks.insert(I->getParent());
6940       }
6941     } else {
6942       Vec = gather(E->Scalars);
6943     }
6944     if (NeedToShuffleReuses) {
6945       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6946       Vec = ShuffleBuilder.finalize(Vec);
6947     }
6948     E->VectorizedValue = Vec;
6949     return Vec;
6950   }
6951 
6952   assert((E->State == TreeEntry::Vectorize ||
6953           E->State == TreeEntry::ScatterVectorize) &&
6954          "Unhandled state");
6955   unsigned ShuffleOrOp =
6956       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6957   Instruction *VL0 = E->getMainOp();
6958   Type *ScalarTy = VL0->getType();
6959   if (auto *Store = dyn_cast<StoreInst>(VL0))
6960     ScalarTy = Store->getValueOperand()->getType();
6961   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6962     ScalarTy = IE->getOperand(1)->getType();
6963   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6964   switch (ShuffleOrOp) {
6965     case Instruction::PHI: {
6966       assert(
6967           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6968           "PHI reordering is free.");
6969       auto *PH = cast<PHINode>(VL0);
6970       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6971       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6972       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6973       Value *V = NewPhi;
6974 
6975       // Adjust insertion point once all PHI's have been generated.
6976       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6977       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6978 
6979       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6980       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6981       V = ShuffleBuilder.finalize(V);
6982 
6983       E->VectorizedValue = V;
6984 
6985       // PHINodes may have multiple entries from the same block. We want to
6986       // visit every block once.
6987       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6988 
6989       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6990         ValueList Operands;
6991         BasicBlock *IBB = PH->getIncomingBlock(i);
6992 
6993         if (!VisitedBBs.insert(IBB).second) {
6994           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6995           continue;
6996         }
6997 
6998         Builder.SetInsertPoint(IBB->getTerminator());
6999         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7000         Value *Vec = vectorizeTree(E->getOperand(i));
7001         NewPhi->addIncoming(Vec, IBB);
7002       }
7003 
7004       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7005              "Invalid number of incoming values");
7006       return V;
7007     }
7008 
7009     case Instruction::ExtractElement: {
7010       Value *V = E->getSingleOperand(0);
7011       Builder.SetInsertPoint(VL0);
7012       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7013       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7014       V = ShuffleBuilder.finalize(V);
7015       E->VectorizedValue = V;
7016       return V;
7017     }
7018     case Instruction::ExtractValue: {
7019       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7020       Builder.SetInsertPoint(LI);
7021       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7022       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7023       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7024       Value *NewV = propagateMetadata(V, E->Scalars);
7025       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7026       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7027       NewV = ShuffleBuilder.finalize(NewV);
7028       E->VectorizedValue = NewV;
7029       return NewV;
7030     }
7031     case Instruction::InsertElement: {
7032       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7033       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7034       Value *V = vectorizeTree(E->getOperand(1));
7035 
7036       // Create InsertVector shuffle if necessary
7037       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7038         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7039       }));
7040       const unsigned NumElts =
7041           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7042       const unsigned NumScalars = E->Scalars.size();
7043 
7044       unsigned Offset = *getInsertIndex(VL0);
7045       assert(Offset < NumElts && "Failed to find vector index offset");
7046 
7047       // Create shuffle to resize vector
7048       SmallVector<int> Mask;
7049       if (!E->ReorderIndices.empty()) {
7050         inversePermutation(E->ReorderIndices, Mask);
7051         Mask.append(NumElts - NumScalars, UndefMaskElem);
7052       } else {
7053         Mask.assign(NumElts, UndefMaskElem);
7054         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7055       }
7056       // Create InsertVector shuffle if necessary
7057       bool IsIdentity = true;
7058       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7059       Mask.swap(PrevMask);
7060       for (unsigned I = 0; I < NumScalars; ++I) {
7061         Value *Scalar = E->Scalars[PrevMask[I]];
7062         unsigned InsertIdx = *getInsertIndex(Scalar);
7063         IsIdentity &= InsertIdx - Offset == I;
7064         Mask[InsertIdx - Offset] = I;
7065       }
7066       if (!IsIdentity || NumElts != NumScalars) {
7067         V = Builder.CreateShuffleVector(V, Mask);
7068         if (auto *I = dyn_cast<Instruction>(V)) {
7069           GatherShuffleSeq.insert(I);
7070           CSEBlocks.insert(I->getParent());
7071         }
7072       }
7073 
7074       if ((!IsIdentity || Offset != 0 ||
7075            !isUndefVector(FirstInsert->getOperand(0))) &&
7076           NumElts != NumScalars) {
7077         SmallVector<int> InsertMask(NumElts);
7078         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7079         for (unsigned I = 0; I < NumElts; I++) {
7080           if (Mask[I] != UndefMaskElem)
7081             InsertMask[Offset + I] = NumElts + I;
7082         }
7083 
7084         V = Builder.CreateShuffleVector(
7085             FirstInsert->getOperand(0), V, InsertMask,
7086             cast<Instruction>(E->Scalars.back())->getName());
7087         if (auto *I = dyn_cast<Instruction>(V)) {
7088           GatherShuffleSeq.insert(I);
7089           CSEBlocks.insert(I->getParent());
7090         }
7091       }
7092 
7093       ++NumVectorInstructions;
7094       E->VectorizedValue = V;
7095       return V;
7096     }
7097     case Instruction::ZExt:
7098     case Instruction::SExt:
7099     case Instruction::FPToUI:
7100     case Instruction::FPToSI:
7101     case Instruction::FPExt:
7102     case Instruction::PtrToInt:
7103     case Instruction::IntToPtr:
7104     case Instruction::SIToFP:
7105     case Instruction::UIToFP:
7106     case Instruction::Trunc:
7107     case Instruction::FPTrunc:
7108     case Instruction::BitCast: {
7109       setInsertPointAfterBundle(E);
7110 
7111       Value *InVec = vectorizeTree(E->getOperand(0));
7112 
7113       if (E->VectorizedValue) {
7114         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7115         return E->VectorizedValue;
7116       }
7117 
7118       auto *CI = cast<CastInst>(VL0);
7119       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7120       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7121       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7122       V = ShuffleBuilder.finalize(V);
7123 
7124       E->VectorizedValue = V;
7125       ++NumVectorInstructions;
7126       return V;
7127     }
7128     case Instruction::FCmp:
7129     case Instruction::ICmp: {
7130       setInsertPointAfterBundle(E);
7131 
7132       Value *L = vectorizeTree(E->getOperand(0));
7133       Value *R = vectorizeTree(E->getOperand(1));
7134 
7135       if (E->VectorizedValue) {
7136         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7137         return E->VectorizedValue;
7138       }
7139 
7140       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7141       Value *V = Builder.CreateCmp(P0, L, R);
7142       propagateIRFlags(V, E->Scalars, VL0);
7143       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7144       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7145       V = ShuffleBuilder.finalize(V);
7146 
7147       E->VectorizedValue = V;
7148       ++NumVectorInstructions;
7149       return V;
7150     }
7151     case Instruction::Select: {
7152       setInsertPointAfterBundle(E);
7153 
7154       Value *Cond = vectorizeTree(E->getOperand(0));
7155       Value *True = vectorizeTree(E->getOperand(1));
7156       Value *False = vectorizeTree(E->getOperand(2));
7157 
7158       if (E->VectorizedValue) {
7159         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7160         return E->VectorizedValue;
7161       }
7162 
7163       Value *V = Builder.CreateSelect(Cond, True, False);
7164       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7165       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7166       V = ShuffleBuilder.finalize(V);
7167 
7168       E->VectorizedValue = V;
7169       ++NumVectorInstructions;
7170       return V;
7171     }
7172     case Instruction::FNeg: {
7173       setInsertPointAfterBundle(E);
7174 
7175       Value *Op = vectorizeTree(E->getOperand(0));
7176 
7177       if (E->VectorizedValue) {
7178         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7179         return E->VectorizedValue;
7180       }
7181 
7182       Value *V = Builder.CreateUnOp(
7183           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7184       propagateIRFlags(V, E->Scalars, VL0);
7185       if (auto *I = dyn_cast<Instruction>(V))
7186         V = propagateMetadata(I, E->Scalars);
7187 
7188       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7189       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7190       V = ShuffleBuilder.finalize(V);
7191 
7192       E->VectorizedValue = V;
7193       ++NumVectorInstructions;
7194 
7195       return V;
7196     }
7197     case Instruction::Add:
7198     case Instruction::FAdd:
7199     case Instruction::Sub:
7200     case Instruction::FSub:
7201     case Instruction::Mul:
7202     case Instruction::FMul:
7203     case Instruction::UDiv:
7204     case Instruction::SDiv:
7205     case Instruction::FDiv:
7206     case Instruction::URem:
7207     case Instruction::SRem:
7208     case Instruction::FRem:
7209     case Instruction::Shl:
7210     case Instruction::LShr:
7211     case Instruction::AShr:
7212     case Instruction::And:
7213     case Instruction::Or:
7214     case Instruction::Xor: {
7215       setInsertPointAfterBundle(E);
7216 
7217       Value *LHS = vectorizeTree(E->getOperand(0));
7218       Value *RHS = vectorizeTree(E->getOperand(1));
7219 
7220       if (E->VectorizedValue) {
7221         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7222         return E->VectorizedValue;
7223       }
7224 
7225       Value *V = Builder.CreateBinOp(
7226           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7227           RHS);
7228       propagateIRFlags(V, E->Scalars, VL0);
7229       if (auto *I = dyn_cast<Instruction>(V))
7230         V = propagateMetadata(I, E->Scalars);
7231 
7232       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7233       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7234       V = ShuffleBuilder.finalize(V);
7235 
7236       E->VectorizedValue = V;
7237       ++NumVectorInstructions;
7238 
7239       return V;
7240     }
7241     case Instruction::Load: {
7242       // Loads are inserted at the head of the tree because we don't want to
7243       // sink them all the way down past store instructions.
7244       setInsertPointAfterBundle(E);
7245 
7246       LoadInst *LI = cast<LoadInst>(VL0);
7247       Instruction *NewLI;
7248       unsigned AS = LI->getPointerAddressSpace();
7249       Value *PO = LI->getPointerOperand();
7250       if (E->State == TreeEntry::Vectorize) {
7251         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7252         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7253 
7254         // The pointer operand uses an in-tree scalar so we add the new BitCast
7255         // or LoadInst to ExternalUses list to make sure that an extract will
7256         // be generated in the future.
7257         if (TreeEntry *Entry = getTreeEntry(PO)) {
7258           // Find which lane we need to extract.
7259           unsigned FoundLane = Entry->findLaneForValue(PO);
7260           ExternalUses.emplace_back(
7261               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7262         }
7263       } else {
7264         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7265         Value *VecPtr = vectorizeTree(E->getOperand(0));
7266         // Use the minimum alignment of the gathered loads.
7267         Align CommonAlignment = LI->getAlign();
7268         for (Value *V : E->Scalars)
7269           CommonAlignment =
7270               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7271         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7272       }
7273       Value *V = propagateMetadata(NewLI, E->Scalars);
7274 
7275       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7276       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7277       V = ShuffleBuilder.finalize(V);
7278       E->VectorizedValue = V;
7279       ++NumVectorInstructions;
7280       return V;
7281     }
7282     case Instruction::Store: {
7283       auto *SI = cast<StoreInst>(VL0);
7284       unsigned AS = SI->getPointerAddressSpace();
7285 
7286       setInsertPointAfterBundle(E);
7287 
7288       Value *VecValue = vectorizeTree(E->getOperand(0));
7289       ShuffleBuilder.addMask(E->ReorderIndices);
7290       VecValue = ShuffleBuilder.finalize(VecValue);
7291 
7292       Value *ScalarPtr = SI->getPointerOperand();
7293       Value *VecPtr = Builder.CreateBitCast(
7294           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7295       StoreInst *ST =
7296           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7297 
7298       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7299       // StoreInst to ExternalUses to make sure that an extract will be
7300       // generated in the future.
7301       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7302         // Find which lane we need to extract.
7303         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7304         ExternalUses.push_back(ExternalUser(
7305             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7306             FoundLane));
7307       }
7308 
7309       Value *V = propagateMetadata(ST, E->Scalars);
7310 
7311       E->VectorizedValue = V;
7312       ++NumVectorInstructions;
7313       return V;
7314     }
7315     case Instruction::GetElementPtr: {
7316       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7317       setInsertPointAfterBundle(E);
7318 
7319       Value *Op0 = vectorizeTree(E->getOperand(0));
7320 
7321       SmallVector<Value *> OpVecs;
7322       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7323         Value *OpVec = vectorizeTree(E->getOperand(J));
7324         OpVecs.push_back(OpVec);
7325       }
7326 
7327       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7328       if (Instruction *I = dyn_cast<Instruction>(V))
7329         V = propagateMetadata(I, E->Scalars);
7330 
7331       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7332       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7333       V = ShuffleBuilder.finalize(V);
7334 
7335       E->VectorizedValue = V;
7336       ++NumVectorInstructions;
7337 
7338       return V;
7339     }
7340     case Instruction::Call: {
7341       CallInst *CI = cast<CallInst>(VL0);
7342       setInsertPointAfterBundle(E);
7343 
7344       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7345       if (Function *FI = CI->getCalledFunction())
7346         IID = FI->getIntrinsicID();
7347 
7348       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7349 
7350       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7351       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7352                           VecCallCosts.first <= VecCallCosts.second;
7353 
7354       Value *ScalarArg = nullptr;
7355       std::vector<Value *> OpVecs;
7356       SmallVector<Type *, 2> TysForDecl =
7357           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7358       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7359         ValueList OpVL;
7360         // Some intrinsics have scalar arguments. This argument should not be
7361         // vectorized.
7362         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7363           CallInst *CEI = cast<CallInst>(VL0);
7364           ScalarArg = CEI->getArgOperand(j);
7365           OpVecs.push_back(CEI->getArgOperand(j));
7366           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7367             TysForDecl.push_back(ScalarArg->getType());
7368           continue;
7369         }
7370 
7371         Value *OpVec = vectorizeTree(E->getOperand(j));
7372         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7373         OpVecs.push_back(OpVec);
7374       }
7375 
7376       Function *CF;
7377       if (!UseIntrinsic) {
7378         VFShape Shape =
7379             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7380                                   VecTy->getNumElements())),
7381                          false /*HasGlobalPred*/);
7382         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7383       } else {
7384         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7385       }
7386 
7387       SmallVector<OperandBundleDef, 1> OpBundles;
7388       CI->getOperandBundlesAsDefs(OpBundles);
7389       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7390 
7391       // The scalar argument uses an in-tree scalar so we add the new vectorized
7392       // call to ExternalUses list to make sure that an extract will be
7393       // generated in the future.
7394       if (ScalarArg) {
7395         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7396           // Find which lane we need to extract.
7397           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7398           ExternalUses.push_back(
7399               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7400         }
7401       }
7402 
7403       propagateIRFlags(V, E->Scalars, VL0);
7404       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7405       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7406       V = ShuffleBuilder.finalize(V);
7407 
7408       E->VectorizedValue = V;
7409       ++NumVectorInstructions;
7410       return V;
7411     }
7412     case Instruction::ShuffleVector: {
7413       assert(E->isAltShuffle() &&
7414              ((Instruction::isBinaryOp(E->getOpcode()) &&
7415                Instruction::isBinaryOp(E->getAltOpcode())) ||
7416               (Instruction::isCast(E->getOpcode()) &&
7417                Instruction::isCast(E->getAltOpcode())) ||
7418               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7419              "Invalid Shuffle Vector Operand");
7420 
7421       Value *LHS = nullptr, *RHS = nullptr;
7422       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7423         setInsertPointAfterBundle(E);
7424         LHS = vectorizeTree(E->getOperand(0));
7425         RHS = vectorizeTree(E->getOperand(1));
7426       } else {
7427         setInsertPointAfterBundle(E);
7428         LHS = vectorizeTree(E->getOperand(0));
7429       }
7430 
7431       if (E->VectorizedValue) {
7432         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7433         return E->VectorizedValue;
7434       }
7435 
7436       Value *V0, *V1;
7437       if (Instruction::isBinaryOp(E->getOpcode())) {
7438         V0 = Builder.CreateBinOp(
7439             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7440         V1 = Builder.CreateBinOp(
7441             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7442       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7443         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7444         auto *AltCI = cast<CmpInst>(E->getAltOp());
7445         CmpInst::Predicate AltPred = AltCI->getPredicate();
7446         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7447       } else {
7448         V0 = Builder.CreateCast(
7449             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7450         V1 = Builder.CreateCast(
7451             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7452       }
7453       // Add V0 and V1 to later analysis to try to find and remove matching
7454       // instruction, if any.
7455       for (Value *V : {V0, V1}) {
7456         if (auto *I = dyn_cast<Instruction>(V)) {
7457           GatherShuffleSeq.insert(I);
7458           CSEBlocks.insert(I->getParent());
7459         }
7460       }
7461 
7462       // Create shuffle to take alternate operations from the vector.
7463       // Also, gather up main and alt scalar ops to propagate IR flags to
7464       // each vector operation.
7465       ValueList OpScalars, AltScalars;
7466       SmallVector<int> Mask;
7467       buildShuffleEntryMask(
7468           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7469           [E](Instruction *I) {
7470             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7471             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7472           },
7473           Mask, &OpScalars, &AltScalars);
7474 
7475       propagateIRFlags(V0, OpScalars);
7476       propagateIRFlags(V1, AltScalars);
7477 
7478       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7479       if (auto *I = dyn_cast<Instruction>(V)) {
7480         V = propagateMetadata(I, E->Scalars);
7481         GatherShuffleSeq.insert(I);
7482         CSEBlocks.insert(I->getParent());
7483       }
7484       V = ShuffleBuilder.finalize(V);
7485 
7486       E->VectorizedValue = V;
7487       ++NumVectorInstructions;
7488 
7489       return V;
7490     }
7491     default:
7492     llvm_unreachable("unknown inst");
7493   }
7494   return nullptr;
7495 }
7496 
7497 Value *BoUpSLP::vectorizeTree() {
7498   ExtraValueToDebugLocsMap ExternallyUsedValues;
7499   return vectorizeTree(ExternallyUsedValues);
7500 }
7501 
7502 Value *
7503 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7504   // All blocks must be scheduled before any instructions are inserted.
7505   for (auto &BSIter : BlocksSchedules) {
7506     scheduleBlock(BSIter.second.get());
7507   }
7508 
7509   Builder.SetInsertPoint(&F->getEntryBlock().front());
7510   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7511 
7512   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7513   // vectorized root. InstCombine will then rewrite the entire expression. We
7514   // sign extend the extracted values below.
7515   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7516   if (MinBWs.count(ScalarRoot)) {
7517     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7518       // If current instr is a phi and not the last phi, insert it after the
7519       // last phi node.
7520       if (isa<PHINode>(I))
7521         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7522       else
7523         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7524     }
7525     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7526     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7527     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7528     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7529     VectorizableTree[0]->VectorizedValue = Trunc;
7530   }
7531 
7532   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7533                     << " values .\n");
7534 
7535   // Extract all of the elements with the external uses.
7536   for (const auto &ExternalUse : ExternalUses) {
7537     Value *Scalar = ExternalUse.Scalar;
7538     llvm::User *User = ExternalUse.User;
7539 
7540     // Skip users that we already RAUW. This happens when one instruction
7541     // has multiple uses of the same value.
7542     if (User && !is_contained(Scalar->users(), User))
7543       continue;
7544     TreeEntry *E = getTreeEntry(Scalar);
7545     assert(E && "Invalid scalar");
7546     assert(E->State != TreeEntry::NeedToGather &&
7547            "Extracting from a gather list");
7548 
7549     Value *Vec = E->VectorizedValue;
7550     assert(Vec && "Can't find vectorizable value");
7551 
7552     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7553     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7554       if (Scalar->getType() != Vec->getType()) {
7555         Value *Ex;
7556         // "Reuse" the existing extract to improve final codegen.
7557         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7558           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7559                                             ES->getOperand(1));
7560         } else {
7561           Ex = Builder.CreateExtractElement(Vec, Lane);
7562         }
7563         // If necessary, sign-extend or zero-extend ScalarRoot
7564         // to the larger type.
7565         if (!MinBWs.count(ScalarRoot))
7566           return Ex;
7567         if (MinBWs[ScalarRoot].second)
7568           return Builder.CreateSExt(Ex, Scalar->getType());
7569         return Builder.CreateZExt(Ex, Scalar->getType());
7570       }
7571       assert(isa<FixedVectorType>(Scalar->getType()) &&
7572              isa<InsertElementInst>(Scalar) &&
7573              "In-tree scalar of vector type is not insertelement?");
7574       return Vec;
7575     };
7576     // If User == nullptr, the Scalar is used as extra arg. Generate
7577     // ExtractElement instruction and update the record for this scalar in
7578     // ExternallyUsedValues.
7579     if (!User) {
7580       assert(ExternallyUsedValues.count(Scalar) &&
7581              "Scalar with nullptr as an external user must be registered in "
7582              "ExternallyUsedValues map");
7583       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7584         Builder.SetInsertPoint(VecI->getParent(),
7585                                std::next(VecI->getIterator()));
7586       } else {
7587         Builder.SetInsertPoint(&F->getEntryBlock().front());
7588       }
7589       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7590       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7591       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7592       auto It = ExternallyUsedValues.find(Scalar);
7593       assert(It != ExternallyUsedValues.end() &&
7594              "Externally used scalar is not found in ExternallyUsedValues");
7595       NewInstLocs.append(It->second);
7596       ExternallyUsedValues.erase(Scalar);
7597       // Required to update internally referenced instructions.
7598       Scalar->replaceAllUsesWith(NewInst);
7599       continue;
7600     }
7601 
7602     // Generate extracts for out-of-tree users.
7603     // Find the insertion point for the extractelement lane.
7604     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7605       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7606         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7607           if (PH->getIncomingValue(i) == Scalar) {
7608             Instruction *IncomingTerminator =
7609                 PH->getIncomingBlock(i)->getTerminator();
7610             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7611               Builder.SetInsertPoint(VecI->getParent(),
7612                                      std::next(VecI->getIterator()));
7613             } else {
7614               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7615             }
7616             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7617             CSEBlocks.insert(PH->getIncomingBlock(i));
7618             PH->setOperand(i, NewInst);
7619           }
7620         }
7621       } else {
7622         Builder.SetInsertPoint(cast<Instruction>(User));
7623         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7624         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7625         User->replaceUsesOfWith(Scalar, NewInst);
7626       }
7627     } else {
7628       Builder.SetInsertPoint(&F->getEntryBlock().front());
7629       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7630       CSEBlocks.insert(&F->getEntryBlock());
7631       User->replaceUsesOfWith(Scalar, NewInst);
7632     }
7633 
7634     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7635   }
7636 
7637   // For each vectorized value:
7638   for (auto &TEPtr : VectorizableTree) {
7639     TreeEntry *Entry = TEPtr.get();
7640 
7641     // No need to handle users of gathered values.
7642     if (Entry->State == TreeEntry::NeedToGather)
7643       continue;
7644 
7645     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7646 
7647     // For each lane:
7648     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7649       Value *Scalar = Entry->Scalars[Lane];
7650 
7651 #ifndef NDEBUG
7652       Type *Ty = Scalar->getType();
7653       if (!Ty->isVoidTy()) {
7654         for (User *U : Scalar->users()) {
7655           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7656 
7657           // It is legal to delete users in the ignorelist.
7658           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7659                   (isa_and_nonnull<Instruction>(U) &&
7660                    isDeleted(cast<Instruction>(U)))) &&
7661                  "Deleting out-of-tree value");
7662         }
7663       }
7664 #endif
7665       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7666       eraseInstruction(cast<Instruction>(Scalar));
7667     }
7668   }
7669 
7670   Builder.ClearInsertionPoint();
7671   InstrElementSize.clear();
7672 
7673   return VectorizableTree[0]->VectorizedValue;
7674 }
7675 
7676 void BoUpSLP::optimizeGatherSequence() {
7677   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7678                     << " gather sequences instructions.\n");
7679   // LICM InsertElementInst sequences.
7680   for (Instruction *I : GatherShuffleSeq) {
7681     if (isDeleted(I))
7682       continue;
7683 
7684     // Check if this block is inside a loop.
7685     Loop *L = LI->getLoopFor(I->getParent());
7686     if (!L)
7687       continue;
7688 
7689     // Check if it has a preheader.
7690     BasicBlock *PreHeader = L->getLoopPreheader();
7691     if (!PreHeader)
7692       continue;
7693 
7694     // If the vector or the element that we insert into it are
7695     // instructions that are defined in this basic block then we can't
7696     // hoist this instruction.
7697     if (any_of(I->operands(), [L](Value *V) {
7698           auto *OpI = dyn_cast<Instruction>(V);
7699           return OpI && L->contains(OpI);
7700         }))
7701       continue;
7702 
7703     // We can hoist this instruction. Move it to the pre-header.
7704     I->moveBefore(PreHeader->getTerminator());
7705   }
7706 
7707   // Make a list of all reachable blocks in our CSE queue.
7708   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7709   CSEWorkList.reserve(CSEBlocks.size());
7710   for (BasicBlock *BB : CSEBlocks)
7711     if (DomTreeNode *N = DT->getNode(BB)) {
7712       assert(DT->isReachableFromEntry(N));
7713       CSEWorkList.push_back(N);
7714     }
7715 
7716   // Sort blocks by domination. This ensures we visit a block after all blocks
7717   // dominating it are visited.
7718   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7719     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7720            "Different nodes should have different DFS numbers");
7721     return A->getDFSNumIn() < B->getDFSNumIn();
7722   });
7723 
7724   // Less defined shuffles can be replaced by the more defined copies.
7725   // Between two shuffles one is less defined if it has the same vector operands
7726   // and its mask indeces are the same as in the first one or undefs. E.g.
7727   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7728   // poison, <0, 0, 0, 0>.
7729   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7730                                            SmallVectorImpl<int> &NewMask) {
7731     if (I1->getType() != I2->getType())
7732       return false;
7733     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7734     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7735     if (!SI1 || !SI2)
7736       return I1->isIdenticalTo(I2);
7737     if (SI1->isIdenticalTo(SI2))
7738       return true;
7739     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7740       if (SI1->getOperand(I) != SI2->getOperand(I))
7741         return false;
7742     // Check if the second instruction is more defined than the first one.
7743     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7744     ArrayRef<int> SM1 = SI1->getShuffleMask();
7745     // Count trailing undefs in the mask to check the final number of used
7746     // registers.
7747     unsigned LastUndefsCnt = 0;
7748     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7749       if (SM1[I] == UndefMaskElem)
7750         ++LastUndefsCnt;
7751       else
7752         LastUndefsCnt = 0;
7753       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7754           NewMask[I] != SM1[I])
7755         return false;
7756       if (NewMask[I] == UndefMaskElem)
7757         NewMask[I] = SM1[I];
7758     }
7759     // Check if the last undefs actually change the final number of used vector
7760     // registers.
7761     return SM1.size() - LastUndefsCnt > 1 &&
7762            TTI->getNumberOfParts(SI1->getType()) ==
7763                TTI->getNumberOfParts(
7764                    FixedVectorType::get(SI1->getType()->getElementType(),
7765                                         SM1.size() - LastUndefsCnt));
7766   };
7767   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7768   // instructions. TODO: We can further optimize this scan if we split the
7769   // instructions into different buckets based on the insert lane.
7770   SmallVector<Instruction *, 16> Visited;
7771   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7772     assert(*I &&
7773            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7774            "Worklist not sorted properly!");
7775     BasicBlock *BB = (*I)->getBlock();
7776     // For all instructions in blocks containing gather sequences:
7777     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7778       if (isDeleted(&In))
7779         continue;
7780       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7781           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7782         continue;
7783 
7784       // Check if we can replace this instruction with any of the
7785       // visited instructions.
7786       bool Replaced = false;
7787       for (Instruction *&V : Visited) {
7788         SmallVector<int> NewMask;
7789         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7790             DT->dominates(V->getParent(), In.getParent())) {
7791           In.replaceAllUsesWith(V);
7792           eraseInstruction(&In);
7793           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7794             if (!NewMask.empty())
7795               SI->setShuffleMask(NewMask);
7796           Replaced = true;
7797           break;
7798         }
7799         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7800             GatherShuffleSeq.contains(V) &&
7801             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7802             DT->dominates(In.getParent(), V->getParent())) {
7803           In.moveAfter(V);
7804           V->replaceAllUsesWith(&In);
7805           eraseInstruction(V);
7806           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7807             if (!NewMask.empty())
7808               SI->setShuffleMask(NewMask);
7809           V = &In;
7810           Replaced = true;
7811           break;
7812         }
7813       }
7814       if (!Replaced) {
7815         assert(!is_contained(Visited, &In));
7816         Visited.push_back(&In);
7817       }
7818     }
7819   }
7820   CSEBlocks.clear();
7821   GatherShuffleSeq.clear();
7822 }
7823 
7824 BoUpSLP::ScheduleData *
7825 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7826   ScheduleData *Bundle = nullptr;
7827   ScheduleData *PrevInBundle = nullptr;
7828   for (Value *V : VL) {
7829     if (doesNotNeedToBeScheduled(V))
7830       continue;
7831     ScheduleData *BundleMember = getScheduleData(V);
7832     assert(BundleMember &&
7833            "no ScheduleData for bundle member "
7834            "(maybe not in same basic block)");
7835     assert(BundleMember->isSchedulingEntity() &&
7836            "bundle member already part of other bundle");
7837     if (PrevInBundle) {
7838       PrevInBundle->NextInBundle = BundleMember;
7839     } else {
7840       Bundle = BundleMember;
7841     }
7842 
7843     // Group the instructions to a bundle.
7844     BundleMember->FirstInBundle = Bundle;
7845     PrevInBundle = BundleMember;
7846   }
7847   assert(Bundle && "Failed to find schedule bundle");
7848   return Bundle;
7849 }
7850 
7851 // Groups the instructions to a bundle (which is then a single scheduling entity)
7852 // and schedules instructions until the bundle gets ready.
7853 Optional<BoUpSLP::ScheduleData *>
7854 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7855                                             const InstructionsState &S) {
7856   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7857   // instructions.
7858   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7859       doesNotNeedToSchedule(VL))
7860     return nullptr;
7861 
7862   // Initialize the instruction bundle.
7863   Instruction *OldScheduleEnd = ScheduleEnd;
7864   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7865 
7866   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7867                                                          ScheduleData *Bundle) {
7868     // The scheduling region got new instructions at the lower end (or it is a
7869     // new region for the first bundle). This makes it necessary to
7870     // recalculate all dependencies.
7871     // It is seldom that this needs to be done a second time after adding the
7872     // initial bundle to the region.
7873     if (ScheduleEnd != OldScheduleEnd) {
7874       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7875         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7876       ReSchedule = true;
7877     }
7878     if (Bundle) {
7879       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7880                         << " in block " << BB->getName() << "\n");
7881       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7882     }
7883 
7884     if (ReSchedule) {
7885       resetSchedule();
7886       initialFillReadyList(ReadyInsts);
7887     }
7888 
7889     // Now try to schedule the new bundle or (if no bundle) just calculate
7890     // dependencies. As soon as the bundle is "ready" it means that there are no
7891     // cyclic dependencies and we can schedule it. Note that's important that we
7892     // don't "schedule" the bundle yet (see cancelScheduling).
7893     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7894            !ReadyInsts.empty()) {
7895       ScheduleData *Picked = ReadyInsts.pop_back_val();
7896       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7897              "must be ready to schedule");
7898       schedule(Picked, ReadyInsts);
7899     }
7900   };
7901 
7902   // Make sure that the scheduling region contains all
7903   // instructions of the bundle.
7904   for (Value *V : VL) {
7905     if (doesNotNeedToBeScheduled(V))
7906       continue;
7907     if (!extendSchedulingRegion(V, S)) {
7908       // If the scheduling region got new instructions at the lower end (or it
7909       // is a new region for the first bundle). This makes it necessary to
7910       // recalculate all dependencies.
7911       // Otherwise the compiler may crash trying to incorrectly calculate
7912       // dependencies and emit instruction in the wrong order at the actual
7913       // scheduling.
7914       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7915       return None;
7916     }
7917   }
7918 
7919   bool ReSchedule = false;
7920   for (Value *V : VL) {
7921     if (doesNotNeedToBeScheduled(V))
7922       continue;
7923     ScheduleData *BundleMember = getScheduleData(V);
7924     assert(BundleMember &&
7925            "no ScheduleData for bundle member (maybe not in same basic block)");
7926 
7927     // Make sure we don't leave the pieces of the bundle in the ready list when
7928     // whole bundle might not be ready.
7929     ReadyInsts.remove(BundleMember);
7930 
7931     if (!BundleMember->IsScheduled)
7932       continue;
7933     // A bundle member was scheduled as single instruction before and now
7934     // needs to be scheduled as part of the bundle. We just get rid of the
7935     // existing schedule.
7936     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7937                       << " was already scheduled\n");
7938     ReSchedule = true;
7939   }
7940 
7941   auto *Bundle = buildBundle(VL);
7942   TryScheduleBundleImpl(ReSchedule, Bundle);
7943   if (!Bundle->isReady()) {
7944     cancelScheduling(VL, S.OpValue);
7945     return None;
7946   }
7947   return Bundle;
7948 }
7949 
7950 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7951                                                 Value *OpValue) {
7952   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7953       doesNotNeedToSchedule(VL))
7954     return;
7955 
7956   if (doesNotNeedToBeScheduled(OpValue))
7957     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7958   ScheduleData *Bundle = getScheduleData(OpValue);
7959   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7960   assert(!Bundle->IsScheduled &&
7961          "Can't cancel bundle which is already scheduled");
7962   assert(Bundle->isSchedulingEntity() &&
7963          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7964          "tried to unbundle something which is not a bundle");
7965 
7966   // Remove the bundle from the ready list.
7967   if (Bundle->isReady())
7968     ReadyInsts.remove(Bundle);
7969 
7970   // Un-bundle: make single instructions out of the bundle.
7971   ScheduleData *BundleMember = Bundle;
7972   while (BundleMember) {
7973     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7974     BundleMember->FirstInBundle = BundleMember;
7975     ScheduleData *Next = BundleMember->NextInBundle;
7976     BundleMember->NextInBundle = nullptr;
7977     BundleMember->TE = nullptr;
7978     if (BundleMember->unscheduledDepsInBundle() == 0) {
7979       ReadyInsts.insert(BundleMember);
7980     }
7981     BundleMember = Next;
7982   }
7983 }
7984 
7985 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7986   // Allocate a new ScheduleData for the instruction.
7987   if (ChunkPos >= ChunkSize) {
7988     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7989     ChunkPos = 0;
7990   }
7991   return &(ScheduleDataChunks.back()[ChunkPos++]);
7992 }
7993 
7994 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7995                                                       const InstructionsState &S) {
7996   if (getScheduleData(V, isOneOf(S, V)))
7997     return true;
7998   Instruction *I = dyn_cast<Instruction>(V);
7999   assert(I && "bundle member must be an instruction");
8000   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8001          !doesNotNeedToBeScheduled(I) &&
8002          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8003          "be scheduled");
8004   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8005     ScheduleData *ISD = getScheduleData(I);
8006     if (!ISD)
8007       return false;
8008     assert(isInSchedulingRegion(ISD) &&
8009            "ScheduleData not in scheduling region");
8010     ScheduleData *SD = allocateScheduleDataChunks();
8011     SD->Inst = I;
8012     SD->init(SchedulingRegionID, S.OpValue);
8013     ExtraScheduleDataMap[I][S.OpValue] = SD;
8014     return true;
8015   };
8016   if (CheckScheduleForI(I))
8017     return true;
8018   if (!ScheduleStart) {
8019     // It's the first instruction in the new region.
8020     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8021     ScheduleStart = I;
8022     ScheduleEnd = I->getNextNode();
8023     if (isOneOf(S, I) != I)
8024       CheckScheduleForI(I);
8025     assert(ScheduleEnd && "tried to vectorize a terminator?");
8026     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8027     return true;
8028   }
8029   // Search up and down at the same time, because we don't know if the new
8030   // instruction is above or below the existing scheduling region.
8031   BasicBlock::reverse_iterator UpIter =
8032       ++ScheduleStart->getIterator().getReverse();
8033   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8034   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8035   BasicBlock::iterator LowerEnd = BB->end();
8036   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8037          &*DownIter != I) {
8038     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8039       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8040       return false;
8041     }
8042 
8043     ++UpIter;
8044     ++DownIter;
8045   }
8046   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8047     assert(I->getParent() == ScheduleStart->getParent() &&
8048            "Instruction is in wrong basic block.");
8049     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8050     ScheduleStart = I;
8051     if (isOneOf(S, I) != I)
8052       CheckScheduleForI(I);
8053     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8054                       << "\n");
8055     return true;
8056   }
8057   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8058          "Expected to reach top of the basic block or instruction down the "
8059          "lower end.");
8060   assert(I->getParent() == ScheduleEnd->getParent() &&
8061          "Instruction is in wrong basic block.");
8062   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8063                    nullptr);
8064   ScheduleEnd = I->getNextNode();
8065   if (isOneOf(S, I) != I)
8066     CheckScheduleForI(I);
8067   assert(ScheduleEnd && "tried to vectorize a terminator?");
8068   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8069   return true;
8070 }
8071 
8072 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8073                                                 Instruction *ToI,
8074                                                 ScheduleData *PrevLoadStore,
8075                                                 ScheduleData *NextLoadStore) {
8076   ScheduleData *CurrentLoadStore = PrevLoadStore;
8077   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8078     // No need to allocate data for non-schedulable instructions.
8079     if (doesNotNeedToBeScheduled(I))
8080       continue;
8081     ScheduleData *SD = ScheduleDataMap.lookup(I);
8082     if (!SD) {
8083       SD = allocateScheduleDataChunks();
8084       ScheduleDataMap[I] = SD;
8085       SD->Inst = I;
8086     }
8087     assert(!isInSchedulingRegion(SD) &&
8088            "new ScheduleData already in scheduling region");
8089     SD->init(SchedulingRegionID, I);
8090 
8091     if (I->mayReadOrWriteMemory() &&
8092         (!isa<IntrinsicInst>(I) ||
8093          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8094           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8095               Intrinsic::pseudoprobe))) {
8096       // Update the linked list of memory accessing instructions.
8097       if (CurrentLoadStore) {
8098         CurrentLoadStore->NextLoadStore = SD;
8099       } else {
8100         FirstLoadStoreInRegion = SD;
8101       }
8102       CurrentLoadStore = SD;
8103     }
8104 
8105     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8106         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8107       RegionHasStackSave = true;
8108   }
8109   if (NextLoadStore) {
8110     if (CurrentLoadStore)
8111       CurrentLoadStore->NextLoadStore = NextLoadStore;
8112   } else {
8113     LastLoadStoreInRegion = CurrentLoadStore;
8114   }
8115 }
8116 
8117 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8118                                                      bool InsertInReadyList,
8119                                                      BoUpSLP *SLP) {
8120   assert(SD->isSchedulingEntity());
8121 
8122   SmallVector<ScheduleData *, 10> WorkList;
8123   WorkList.push_back(SD);
8124 
8125   while (!WorkList.empty()) {
8126     ScheduleData *SD = WorkList.pop_back_val();
8127     for (ScheduleData *BundleMember = SD; BundleMember;
8128          BundleMember = BundleMember->NextInBundle) {
8129       assert(isInSchedulingRegion(BundleMember));
8130       if (BundleMember->hasValidDependencies())
8131         continue;
8132 
8133       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8134                  << "\n");
8135       BundleMember->Dependencies = 0;
8136       BundleMember->resetUnscheduledDeps();
8137 
8138       // Handle def-use chain dependencies.
8139       if (BundleMember->OpValue != BundleMember->Inst) {
8140         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8141           BundleMember->Dependencies++;
8142           ScheduleData *DestBundle = UseSD->FirstInBundle;
8143           if (!DestBundle->IsScheduled)
8144             BundleMember->incrementUnscheduledDeps(1);
8145           if (!DestBundle->hasValidDependencies())
8146             WorkList.push_back(DestBundle);
8147         }
8148       } else {
8149         for (User *U : BundleMember->Inst->users()) {
8150           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8151             BundleMember->Dependencies++;
8152             ScheduleData *DestBundle = UseSD->FirstInBundle;
8153             if (!DestBundle->IsScheduled)
8154               BundleMember->incrementUnscheduledDeps(1);
8155             if (!DestBundle->hasValidDependencies())
8156               WorkList.push_back(DestBundle);
8157           }
8158         }
8159       }
8160 
8161       auto makeControlDependent = [&](Instruction *I) {
8162         auto *DepDest = getScheduleData(I);
8163         assert(DepDest && "must be in schedule window");
8164         DepDest->ControlDependencies.push_back(BundleMember);
8165         BundleMember->Dependencies++;
8166         ScheduleData *DestBundle = DepDest->FirstInBundle;
8167         if (!DestBundle->IsScheduled)
8168           BundleMember->incrementUnscheduledDeps(1);
8169         if (!DestBundle->hasValidDependencies())
8170           WorkList.push_back(DestBundle);
8171       };
8172 
8173       // Any instruction which isn't safe to speculate at the begining of the
8174       // block is control dependend on any early exit or non-willreturn call
8175       // which proceeds it.
8176       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8177         for (Instruction *I = BundleMember->Inst->getNextNode();
8178              I != ScheduleEnd; I = I->getNextNode()) {
8179           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8180             continue;
8181 
8182           // Add the dependency
8183           makeControlDependent(I);
8184 
8185           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8186             // Everything past here must be control dependent on I.
8187             break;
8188         }
8189       }
8190 
8191       if (RegionHasStackSave) {
8192         // If we have an inalloc alloca instruction, it needs to be scheduled
8193         // after any preceeding stacksave.  We also need to prevent any alloca
8194         // from reordering above a preceeding stackrestore.
8195         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8196             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8197           for (Instruction *I = BundleMember->Inst->getNextNode();
8198                I != ScheduleEnd; I = I->getNextNode()) {
8199             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8200                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8201               // Any allocas past here must be control dependent on I, and I
8202               // must be memory dependend on BundleMember->Inst.
8203               break;
8204 
8205             if (!isa<AllocaInst>(I))
8206               continue;
8207 
8208             // Add the dependency
8209             makeControlDependent(I);
8210           }
8211         }
8212 
8213         // In addition to the cases handle just above, we need to prevent
8214         // allocas from moving below a stacksave.  The stackrestore case
8215         // is currently thought to be conservatism.
8216         if (isa<AllocaInst>(BundleMember->Inst)) {
8217           for (Instruction *I = BundleMember->Inst->getNextNode();
8218                I != ScheduleEnd; I = I->getNextNode()) {
8219             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8220                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8221               continue;
8222 
8223             // Add the dependency
8224             makeControlDependent(I);
8225             break;
8226           }
8227         }
8228       }
8229 
8230       // Handle the memory dependencies (if any).
8231       ScheduleData *DepDest = BundleMember->NextLoadStore;
8232       if (!DepDest)
8233         continue;
8234       Instruction *SrcInst = BundleMember->Inst;
8235       assert(SrcInst->mayReadOrWriteMemory() &&
8236              "NextLoadStore list for non memory effecting bundle?");
8237       MemoryLocation SrcLoc = getLocation(SrcInst);
8238       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8239       unsigned numAliased = 0;
8240       unsigned DistToSrc = 1;
8241 
8242       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8243         assert(isInSchedulingRegion(DepDest));
8244 
8245         // We have two limits to reduce the complexity:
8246         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8247         //    SLP->isAliased (which is the expensive part in this loop).
8248         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8249         //    the whole loop (even if the loop is fast, it's quadratic).
8250         //    It's important for the loop break condition (see below) to
8251         //    check this limit even between two read-only instructions.
8252         if (DistToSrc >= MaxMemDepDistance ||
8253             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8254              (numAliased >= AliasedCheckLimit ||
8255               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8256 
8257           // We increment the counter only if the locations are aliased
8258           // (instead of counting all alias checks). This gives a better
8259           // balance between reduced runtime and accurate dependencies.
8260           numAliased++;
8261 
8262           DepDest->MemoryDependencies.push_back(BundleMember);
8263           BundleMember->Dependencies++;
8264           ScheduleData *DestBundle = DepDest->FirstInBundle;
8265           if (!DestBundle->IsScheduled) {
8266             BundleMember->incrementUnscheduledDeps(1);
8267           }
8268           if (!DestBundle->hasValidDependencies()) {
8269             WorkList.push_back(DestBundle);
8270           }
8271         }
8272 
8273         // Example, explaining the loop break condition: Let's assume our
8274         // starting instruction is i0 and MaxMemDepDistance = 3.
8275         //
8276         //                      +--------v--v--v
8277         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8278         //             +--------^--^--^
8279         //
8280         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8281         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8282         // Previously we already added dependencies from i3 to i6,i7,i8
8283         // (because of MaxMemDepDistance). As we added a dependency from
8284         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8285         // and we can abort this loop at i6.
8286         if (DistToSrc >= 2 * MaxMemDepDistance)
8287           break;
8288         DistToSrc++;
8289       }
8290     }
8291     if (InsertInReadyList && SD->isReady()) {
8292       ReadyInsts.insert(SD);
8293       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8294                         << "\n");
8295     }
8296   }
8297 }
8298 
8299 void BoUpSLP::BlockScheduling::resetSchedule() {
8300   assert(ScheduleStart &&
8301          "tried to reset schedule on block which has not been scheduled");
8302   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8303     doForAllOpcodes(I, [&](ScheduleData *SD) {
8304       assert(isInSchedulingRegion(SD) &&
8305              "ScheduleData not in scheduling region");
8306       SD->IsScheduled = false;
8307       SD->resetUnscheduledDeps();
8308     });
8309   }
8310   ReadyInsts.clear();
8311 }
8312 
8313 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8314   if (!BS->ScheduleStart)
8315     return;
8316 
8317   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8318 
8319   // A key point - if we got here, pre-scheduling was able to find a valid
8320   // scheduling of the sub-graph of the scheduling window which consists
8321   // of all vector bundles and their transitive users.  As such, we do not
8322   // need to reschedule anything *outside of* that subgraph.
8323 
8324   BS->resetSchedule();
8325 
8326   // For the real scheduling we use a more sophisticated ready-list: it is
8327   // sorted by the original instruction location. This lets the final schedule
8328   // be as  close as possible to the original instruction order.
8329   // WARNING: If changing this order causes a correctness issue, that means
8330   // there is some missing dependence edge in the schedule data graph.
8331   struct ScheduleDataCompare {
8332     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8333       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8334     }
8335   };
8336   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8337 
8338   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8339   // and fill the ready-list with initial instructions.
8340   int Idx = 0;
8341   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8342        I = I->getNextNode()) {
8343     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8344       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8345       (void)SDTE;
8346       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8347               SD->isPartOfBundle() ==
8348                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8349              "scheduler and vectorizer bundle mismatch");
8350       SD->FirstInBundle->SchedulingPriority = Idx++;
8351 
8352       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8353         BS->calculateDependencies(SD, false, this);
8354     });
8355   }
8356   BS->initialFillReadyList(ReadyInsts);
8357 
8358   Instruction *LastScheduledInst = BS->ScheduleEnd;
8359 
8360   // Do the "real" scheduling.
8361   while (!ReadyInsts.empty()) {
8362     ScheduleData *picked = *ReadyInsts.begin();
8363     ReadyInsts.erase(ReadyInsts.begin());
8364 
8365     // Move the scheduled instruction(s) to their dedicated places, if not
8366     // there yet.
8367     for (ScheduleData *BundleMember = picked; BundleMember;
8368          BundleMember = BundleMember->NextInBundle) {
8369       Instruction *pickedInst = BundleMember->Inst;
8370       if (pickedInst->getNextNode() != LastScheduledInst)
8371         pickedInst->moveBefore(LastScheduledInst);
8372       LastScheduledInst = pickedInst;
8373     }
8374 
8375     BS->schedule(picked, ReadyInsts);
8376   }
8377 
8378   // Check that we didn't break any of our invariants.
8379 #ifdef EXPENSIVE_CHECKS
8380   BS->verify();
8381 #endif
8382 
8383 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8384   // Check that all schedulable entities got scheduled
8385   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8386     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8387       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8388         assert(SD->IsScheduled && "must be scheduled at this point");
8389       }
8390     });
8391   }
8392 #endif
8393 
8394   // Avoid duplicate scheduling of the block.
8395   BS->ScheduleStart = nullptr;
8396 }
8397 
8398 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8399   // If V is a store, just return the width of the stored value (or value
8400   // truncated just before storing) without traversing the expression tree.
8401   // This is the common case.
8402   if (auto *Store = dyn_cast<StoreInst>(V)) {
8403     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8404       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8405     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8406   }
8407 
8408   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8409     return getVectorElementSize(IEI->getOperand(1));
8410 
8411   auto E = InstrElementSize.find(V);
8412   if (E != InstrElementSize.end())
8413     return E->second;
8414 
8415   // If V is not a store, we can traverse the expression tree to find loads
8416   // that feed it. The type of the loaded value may indicate a more suitable
8417   // width than V's type. We want to base the vector element size on the width
8418   // of memory operations where possible.
8419   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8420   SmallPtrSet<Instruction *, 16> Visited;
8421   if (auto *I = dyn_cast<Instruction>(V)) {
8422     Worklist.emplace_back(I, I->getParent());
8423     Visited.insert(I);
8424   }
8425 
8426   // Traverse the expression tree in bottom-up order looking for loads. If we
8427   // encounter an instruction we don't yet handle, we give up.
8428   auto Width = 0u;
8429   while (!Worklist.empty()) {
8430     Instruction *I;
8431     BasicBlock *Parent;
8432     std::tie(I, Parent) = Worklist.pop_back_val();
8433 
8434     // We should only be looking at scalar instructions here. If the current
8435     // instruction has a vector type, skip.
8436     auto *Ty = I->getType();
8437     if (isa<VectorType>(Ty))
8438       continue;
8439 
8440     // If the current instruction is a load, update MaxWidth to reflect the
8441     // width of the loaded value.
8442     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8443         isa<ExtractValueInst>(I))
8444       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8445 
8446     // Otherwise, we need to visit the operands of the instruction. We only
8447     // handle the interesting cases from buildTree here. If an operand is an
8448     // instruction we haven't yet visited and from the same basic block as the
8449     // user or the use is a PHI node, we add it to the worklist.
8450     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8451              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8452              isa<UnaryOperator>(I)) {
8453       for (Use &U : I->operands())
8454         if (auto *J = dyn_cast<Instruction>(U.get()))
8455           if (Visited.insert(J).second &&
8456               (isa<PHINode>(I) || J->getParent() == Parent))
8457             Worklist.emplace_back(J, J->getParent());
8458     } else {
8459       break;
8460     }
8461   }
8462 
8463   // If we didn't encounter a memory access in the expression tree, or if we
8464   // gave up for some reason, just return the width of V. Otherwise, return the
8465   // maximum width we found.
8466   if (!Width) {
8467     if (auto *CI = dyn_cast<CmpInst>(V))
8468       V = CI->getOperand(0);
8469     Width = DL->getTypeSizeInBits(V->getType());
8470   }
8471 
8472   for (Instruction *I : Visited)
8473     InstrElementSize[I] = Width;
8474 
8475   return Width;
8476 }
8477 
8478 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8479 // smaller type with a truncation. We collect the values that will be demoted
8480 // in ToDemote and additional roots that require investigating in Roots.
8481 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8482                                   SmallVectorImpl<Value *> &ToDemote,
8483                                   SmallVectorImpl<Value *> &Roots) {
8484   // We can always demote constants.
8485   if (isa<Constant>(V)) {
8486     ToDemote.push_back(V);
8487     return true;
8488   }
8489 
8490   // If the value is not an instruction in the expression with only one use, it
8491   // cannot be demoted.
8492   auto *I = dyn_cast<Instruction>(V);
8493   if (!I || !I->hasOneUse() || !Expr.count(I))
8494     return false;
8495 
8496   switch (I->getOpcode()) {
8497 
8498   // We can always demote truncations and extensions. Since truncations can
8499   // seed additional demotion, we save the truncated value.
8500   case Instruction::Trunc:
8501     Roots.push_back(I->getOperand(0));
8502     break;
8503   case Instruction::ZExt:
8504   case Instruction::SExt:
8505     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8506         isa<InsertElementInst>(I->getOperand(0)))
8507       return false;
8508     break;
8509 
8510   // We can demote certain binary operations if we can demote both of their
8511   // operands.
8512   case Instruction::Add:
8513   case Instruction::Sub:
8514   case Instruction::Mul:
8515   case Instruction::And:
8516   case Instruction::Or:
8517   case Instruction::Xor:
8518     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8519         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8520       return false;
8521     break;
8522 
8523   // We can demote selects if we can demote their true and false values.
8524   case Instruction::Select: {
8525     SelectInst *SI = cast<SelectInst>(I);
8526     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8527         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8528       return false;
8529     break;
8530   }
8531 
8532   // We can demote phis if we can demote all their incoming operands. Note that
8533   // we don't need to worry about cycles since we ensure single use above.
8534   case Instruction::PHI: {
8535     PHINode *PN = cast<PHINode>(I);
8536     for (Value *IncValue : PN->incoming_values())
8537       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8538         return false;
8539     break;
8540   }
8541 
8542   // Otherwise, conservatively give up.
8543   default:
8544     return false;
8545   }
8546 
8547   // Record the value that we can demote.
8548   ToDemote.push_back(V);
8549   return true;
8550 }
8551 
8552 void BoUpSLP::computeMinimumValueSizes() {
8553   // If there are no external uses, the expression tree must be rooted by a
8554   // store. We can't demote in-memory values, so there is nothing to do here.
8555   if (ExternalUses.empty())
8556     return;
8557 
8558   // We only attempt to truncate integer expressions.
8559   auto &TreeRoot = VectorizableTree[0]->Scalars;
8560   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8561   if (!TreeRootIT)
8562     return;
8563 
8564   // If the expression is not rooted by a store, these roots should have
8565   // external uses. We will rely on InstCombine to rewrite the expression in
8566   // the narrower type. However, InstCombine only rewrites single-use values.
8567   // This means that if a tree entry other than a root is used externally, it
8568   // must have multiple uses and InstCombine will not rewrite it. The code
8569   // below ensures that only the roots are used externally.
8570   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8571   for (auto &EU : ExternalUses)
8572     if (!Expr.erase(EU.Scalar))
8573       return;
8574   if (!Expr.empty())
8575     return;
8576 
8577   // Collect the scalar values of the vectorizable expression. We will use this
8578   // context to determine which values can be demoted. If we see a truncation,
8579   // we mark it as seeding another demotion.
8580   for (auto &EntryPtr : VectorizableTree)
8581     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8582 
8583   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8584   // have a single external user that is not in the vectorizable tree.
8585   for (auto *Root : TreeRoot)
8586     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8587       return;
8588 
8589   // Conservatively determine if we can actually truncate the roots of the
8590   // expression. Collect the values that can be demoted in ToDemote and
8591   // additional roots that require investigating in Roots.
8592   SmallVector<Value *, 32> ToDemote;
8593   SmallVector<Value *, 4> Roots;
8594   for (auto *Root : TreeRoot)
8595     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8596       return;
8597 
8598   // The maximum bit width required to represent all the values that can be
8599   // demoted without loss of precision. It would be safe to truncate the roots
8600   // of the expression to this width.
8601   auto MaxBitWidth = 8u;
8602 
8603   // We first check if all the bits of the roots are demanded. If they're not,
8604   // we can truncate the roots to this narrower type.
8605   for (auto *Root : TreeRoot) {
8606     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8607     MaxBitWidth = std::max<unsigned>(
8608         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8609   }
8610 
8611   // True if the roots can be zero-extended back to their original type, rather
8612   // than sign-extended. We know that if the leading bits are not demanded, we
8613   // can safely zero-extend. So we initialize IsKnownPositive to True.
8614   bool IsKnownPositive = true;
8615 
8616   // If all the bits of the roots are demanded, we can try a little harder to
8617   // compute a narrower type. This can happen, for example, if the roots are
8618   // getelementptr indices. InstCombine promotes these indices to the pointer
8619   // width. Thus, all their bits are technically demanded even though the
8620   // address computation might be vectorized in a smaller type.
8621   //
8622   // We start by looking at each entry that can be demoted. We compute the
8623   // maximum bit width required to store the scalar by using ValueTracking to
8624   // compute the number of high-order bits we can truncate.
8625   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8626       llvm::all_of(TreeRoot, [](Value *R) {
8627         assert(R->hasOneUse() && "Root should have only one use!");
8628         return isa<GetElementPtrInst>(R->user_back());
8629       })) {
8630     MaxBitWidth = 8u;
8631 
8632     // Determine if the sign bit of all the roots is known to be zero. If not,
8633     // IsKnownPositive is set to False.
8634     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8635       KnownBits Known = computeKnownBits(R, *DL);
8636       return Known.isNonNegative();
8637     });
8638 
8639     // Determine the maximum number of bits required to store the scalar
8640     // values.
8641     for (auto *Scalar : ToDemote) {
8642       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8643       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8644       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8645     }
8646 
8647     // If we can't prove that the sign bit is zero, we must add one to the
8648     // maximum bit width to account for the unknown sign bit. This preserves
8649     // the existing sign bit so we can safely sign-extend the root back to the
8650     // original type. Otherwise, if we know the sign bit is zero, we will
8651     // zero-extend the root instead.
8652     //
8653     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8654     //        one to the maximum bit width will yield a larger-than-necessary
8655     //        type. In general, we need to add an extra bit only if we can't
8656     //        prove that the upper bit of the original type is equal to the
8657     //        upper bit of the proposed smaller type. If these two bits are the
8658     //        same (either zero or one) we know that sign-extending from the
8659     //        smaller type will result in the same value. Here, since we can't
8660     //        yet prove this, we are just making the proposed smaller type
8661     //        larger to ensure correctness.
8662     if (!IsKnownPositive)
8663       ++MaxBitWidth;
8664   }
8665 
8666   // Round MaxBitWidth up to the next power-of-two.
8667   if (!isPowerOf2_64(MaxBitWidth))
8668     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8669 
8670   // If the maximum bit width we compute is less than the with of the roots'
8671   // type, we can proceed with the narrowing. Otherwise, do nothing.
8672   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8673     return;
8674 
8675   // If we can truncate the root, we must collect additional values that might
8676   // be demoted as a result. That is, those seeded by truncations we will
8677   // modify.
8678   while (!Roots.empty())
8679     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8680 
8681   // Finally, map the values we can demote to the maximum bit with we computed.
8682   for (auto *Scalar : ToDemote)
8683     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8684 }
8685 
8686 namespace {
8687 
8688 /// The SLPVectorizer Pass.
8689 struct SLPVectorizer : public FunctionPass {
8690   SLPVectorizerPass Impl;
8691 
8692   /// Pass identification, replacement for typeid
8693   static char ID;
8694 
8695   explicit SLPVectorizer() : FunctionPass(ID) {
8696     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8697   }
8698 
8699   bool doInitialization(Module &M) override { return false; }
8700 
8701   bool runOnFunction(Function &F) override {
8702     if (skipFunction(F))
8703       return false;
8704 
8705     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8706     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8707     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8708     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8709     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8710     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8711     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8712     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8713     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8714     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8715 
8716     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8717   }
8718 
8719   void getAnalysisUsage(AnalysisUsage &AU) const override {
8720     FunctionPass::getAnalysisUsage(AU);
8721     AU.addRequired<AssumptionCacheTracker>();
8722     AU.addRequired<ScalarEvolutionWrapperPass>();
8723     AU.addRequired<AAResultsWrapperPass>();
8724     AU.addRequired<TargetTransformInfoWrapperPass>();
8725     AU.addRequired<LoopInfoWrapperPass>();
8726     AU.addRequired<DominatorTreeWrapperPass>();
8727     AU.addRequired<DemandedBitsWrapperPass>();
8728     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8729     AU.addRequired<InjectTLIMappingsLegacy>();
8730     AU.addPreserved<LoopInfoWrapperPass>();
8731     AU.addPreserved<DominatorTreeWrapperPass>();
8732     AU.addPreserved<AAResultsWrapperPass>();
8733     AU.addPreserved<GlobalsAAWrapperPass>();
8734     AU.setPreservesCFG();
8735   }
8736 };
8737 
8738 } // end anonymous namespace
8739 
8740 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8741   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8742   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8743   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8744   auto *AA = &AM.getResult<AAManager>(F);
8745   auto *LI = &AM.getResult<LoopAnalysis>(F);
8746   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8747   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8748   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8749   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8750 
8751   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8752   if (!Changed)
8753     return PreservedAnalyses::all();
8754 
8755   PreservedAnalyses PA;
8756   PA.preserveSet<CFGAnalyses>();
8757   return PA;
8758 }
8759 
8760 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8761                                 TargetTransformInfo *TTI_,
8762                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8763                                 LoopInfo *LI_, DominatorTree *DT_,
8764                                 AssumptionCache *AC_, DemandedBits *DB_,
8765                                 OptimizationRemarkEmitter *ORE_) {
8766   if (!RunSLPVectorization)
8767     return false;
8768   SE = SE_;
8769   TTI = TTI_;
8770   TLI = TLI_;
8771   AA = AA_;
8772   LI = LI_;
8773   DT = DT_;
8774   AC = AC_;
8775   DB = DB_;
8776   DL = &F.getParent()->getDataLayout();
8777 
8778   Stores.clear();
8779   GEPs.clear();
8780   bool Changed = false;
8781 
8782   // If the target claims to have no vector registers don't attempt
8783   // vectorization.
8784   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8785     LLVM_DEBUG(
8786         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8787     return false;
8788   }
8789 
8790   // Don't vectorize when the attribute NoImplicitFloat is used.
8791   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8792     return false;
8793 
8794   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8795 
8796   // Use the bottom up slp vectorizer to construct chains that start with
8797   // store instructions.
8798   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8799 
8800   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8801   // delete instructions.
8802 
8803   // Update DFS numbers now so that we can use them for ordering.
8804   DT->updateDFSNumbers();
8805 
8806   // Scan the blocks in the function in post order.
8807   for (auto BB : post_order(&F.getEntryBlock())) {
8808     collectSeedInstructions(BB);
8809 
8810     // Vectorize trees that end at stores.
8811     if (!Stores.empty()) {
8812       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8813                         << " underlying objects.\n");
8814       Changed |= vectorizeStoreChains(R);
8815     }
8816 
8817     // Vectorize trees that end at reductions.
8818     Changed |= vectorizeChainsInBlock(BB, R);
8819 
8820     // Vectorize the index computations of getelementptr instructions. This
8821     // is primarily intended to catch gather-like idioms ending at
8822     // non-consecutive loads.
8823     if (!GEPs.empty()) {
8824       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8825                         << " underlying objects.\n");
8826       Changed |= vectorizeGEPIndices(BB, R);
8827     }
8828   }
8829 
8830   if (Changed) {
8831     R.optimizeGatherSequence();
8832     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8833   }
8834   return Changed;
8835 }
8836 
8837 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8838                                             unsigned Idx) {
8839   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8840                     << "\n");
8841   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8842   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8843   unsigned VF = Chain.size();
8844 
8845   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8846     return false;
8847 
8848   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8849                     << "\n");
8850 
8851   R.buildTree(Chain);
8852   if (R.isTreeTinyAndNotFullyVectorizable())
8853     return false;
8854   if (R.isLoadCombineCandidate())
8855     return false;
8856   R.reorderTopToBottom();
8857   R.reorderBottomToTop();
8858   R.buildExternalUses();
8859 
8860   R.computeMinimumValueSizes();
8861 
8862   InstructionCost Cost = R.getTreeCost();
8863 
8864   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8865   if (Cost < -SLPCostThreshold) {
8866     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8867 
8868     using namespace ore;
8869 
8870     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8871                                         cast<StoreInst>(Chain[0]))
8872                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8873                      << " and with tree size "
8874                      << NV("TreeSize", R.getTreeSize()));
8875 
8876     R.vectorizeTree();
8877     return true;
8878   }
8879 
8880   return false;
8881 }
8882 
8883 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8884                                         BoUpSLP &R) {
8885   // We may run into multiple chains that merge into a single chain. We mark the
8886   // stores that we vectorized so that we don't visit the same store twice.
8887   BoUpSLP::ValueSet VectorizedStores;
8888   bool Changed = false;
8889 
8890   int E = Stores.size();
8891   SmallBitVector Tails(E, false);
8892   int MaxIter = MaxStoreLookup.getValue();
8893   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8894       E, std::make_pair(E, INT_MAX));
8895   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8896   int IterCnt;
8897   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8898                                   &CheckedPairs,
8899                                   &ConsecutiveChain](int K, int Idx) {
8900     if (IterCnt >= MaxIter)
8901       return true;
8902     if (CheckedPairs[Idx].test(K))
8903       return ConsecutiveChain[K].second == 1 &&
8904              ConsecutiveChain[K].first == Idx;
8905     ++IterCnt;
8906     CheckedPairs[Idx].set(K);
8907     CheckedPairs[K].set(Idx);
8908     Optional<int> Diff = getPointersDiff(
8909         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8910         Stores[Idx]->getValueOperand()->getType(),
8911         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8912     if (!Diff || *Diff == 0)
8913       return false;
8914     int Val = *Diff;
8915     if (Val < 0) {
8916       if (ConsecutiveChain[Idx].second > -Val) {
8917         Tails.set(K);
8918         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8919       }
8920       return false;
8921     }
8922     if (ConsecutiveChain[K].second <= Val)
8923       return false;
8924 
8925     Tails.set(Idx);
8926     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8927     return Val == 1;
8928   };
8929   // Do a quadratic search on all of the given stores in reverse order and find
8930   // all of the pairs of stores that follow each other.
8931   for (int Idx = E - 1; Idx >= 0; --Idx) {
8932     // If a store has multiple consecutive store candidates, search according
8933     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8934     // This is because usually pairing with immediate succeeding or preceding
8935     // candidate create the best chance to find slp vectorization opportunity.
8936     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8937     IterCnt = 0;
8938     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8939       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8940           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8941         break;
8942   }
8943 
8944   // Tracks if we tried to vectorize stores starting from the given tail
8945   // already.
8946   SmallBitVector TriedTails(E, false);
8947   // For stores that start but don't end a link in the chain:
8948   for (int Cnt = E; Cnt > 0; --Cnt) {
8949     int I = Cnt - 1;
8950     if (ConsecutiveChain[I].first == E || Tails.test(I))
8951       continue;
8952     // We found a store instr that starts a chain. Now follow the chain and try
8953     // to vectorize it.
8954     BoUpSLP::ValueList Operands;
8955     // Collect the chain into a list.
8956     while (I != E && !VectorizedStores.count(Stores[I])) {
8957       Operands.push_back(Stores[I]);
8958       Tails.set(I);
8959       if (ConsecutiveChain[I].second != 1) {
8960         // Mark the new end in the chain and go back, if required. It might be
8961         // required if the original stores come in reversed order, for example.
8962         if (ConsecutiveChain[I].first != E &&
8963             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8964             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8965           TriedTails.set(I);
8966           Tails.reset(ConsecutiveChain[I].first);
8967           if (Cnt < ConsecutiveChain[I].first + 2)
8968             Cnt = ConsecutiveChain[I].first + 2;
8969         }
8970         break;
8971       }
8972       // Move to the next value in the chain.
8973       I = ConsecutiveChain[I].first;
8974     }
8975     assert(!Operands.empty() && "Expected non-empty list of stores.");
8976 
8977     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8978     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8979     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8980 
8981     unsigned MinVF = R.getMinVF(EltSize);
8982     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8983                               MaxElts);
8984 
8985     // FIXME: Is division-by-2 the correct step? Should we assert that the
8986     // register size is a power-of-2?
8987     unsigned StartIdx = 0;
8988     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8989       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8990         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8991         if (!VectorizedStores.count(Slice.front()) &&
8992             !VectorizedStores.count(Slice.back()) &&
8993             vectorizeStoreChain(Slice, R, Cnt)) {
8994           // Mark the vectorized stores so that we don't vectorize them again.
8995           VectorizedStores.insert(Slice.begin(), Slice.end());
8996           Changed = true;
8997           // If we vectorized initial block, no need to try to vectorize it
8998           // again.
8999           if (Cnt == StartIdx)
9000             StartIdx += Size;
9001           Cnt += Size;
9002           continue;
9003         }
9004         ++Cnt;
9005       }
9006       // Check if the whole array was vectorized already - exit.
9007       if (StartIdx >= Operands.size())
9008         break;
9009     }
9010   }
9011 
9012   return Changed;
9013 }
9014 
9015 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9016   // Initialize the collections. We will make a single pass over the block.
9017   Stores.clear();
9018   GEPs.clear();
9019 
9020   // Visit the store and getelementptr instructions in BB and organize them in
9021   // Stores and GEPs according to the underlying objects of their pointer
9022   // operands.
9023   for (Instruction &I : *BB) {
9024     // Ignore store instructions that are volatile or have a pointer operand
9025     // that doesn't point to a scalar type.
9026     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9027       if (!SI->isSimple())
9028         continue;
9029       if (!isValidElementType(SI->getValueOperand()->getType()))
9030         continue;
9031       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9032     }
9033 
9034     // Ignore getelementptr instructions that have more than one index, a
9035     // constant index, or a pointer operand that doesn't point to a scalar
9036     // type.
9037     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9038       auto Idx = GEP->idx_begin()->get();
9039       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9040         continue;
9041       if (!isValidElementType(Idx->getType()))
9042         continue;
9043       if (GEP->getType()->isVectorTy())
9044         continue;
9045       GEPs[GEP->getPointerOperand()].push_back(GEP);
9046     }
9047   }
9048 }
9049 
9050 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9051   if (!A || !B)
9052     return false;
9053   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9054     return false;
9055   Value *VL[] = {A, B};
9056   return tryToVectorizeList(VL, R);
9057 }
9058 
9059 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9060                                            bool LimitForRegisterSize) {
9061   if (VL.size() < 2)
9062     return false;
9063 
9064   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9065                     << VL.size() << ".\n");
9066 
9067   // Check that all of the parts are instructions of the same type,
9068   // we permit an alternate opcode via InstructionsState.
9069   InstructionsState S = getSameOpcode(VL);
9070   if (!S.getOpcode())
9071     return false;
9072 
9073   Instruction *I0 = cast<Instruction>(S.OpValue);
9074   // Make sure invalid types (including vector type) are rejected before
9075   // determining vectorization factor for scalar instructions.
9076   for (Value *V : VL) {
9077     Type *Ty = V->getType();
9078     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9079       // NOTE: the following will give user internal llvm type name, which may
9080       // not be useful.
9081       R.getORE()->emit([&]() {
9082         std::string type_str;
9083         llvm::raw_string_ostream rso(type_str);
9084         Ty->print(rso);
9085         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9086                << "Cannot SLP vectorize list: type "
9087                << rso.str() + " is unsupported by vectorizer";
9088       });
9089       return false;
9090     }
9091   }
9092 
9093   unsigned Sz = R.getVectorElementSize(I0);
9094   unsigned MinVF = R.getMinVF(Sz);
9095   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9096   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9097   if (MaxVF < 2) {
9098     R.getORE()->emit([&]() {
9099       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9100              << "Cannot SLP vectorize list: vectorization factor "
9101              << "less than 2 is not supported";
9102     });
9103     return false;
9104   }
9105 
9106   bool Changed = false;
9107   bool CandidateFound = false;
9108   InstructionCost MinCost = SLPCostThreshold.getValue();
9109   Type *ScalarTy = VL[0]->getType();
9110   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9111     ScalarTy = IE->getOperand(1)->getType();
9112 
9113   unsigned NextInst = 0, MaxInst = VL.size();
9114   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9115     // No actual vectorization should happen, if number of parts is the same as
9116     // provided vectorization factor (i.e. the scalar type is used for vector
9117     // code during codegen).
9118     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9119     if (TTI->getNumberOfParts(VecTy) == VF)
9120       continue;
9121     for (unsigned I = NextInst; I < MaxInst; ++I) {
9122       unsigned OpsWidth = 0;
9123 
9124       if (I + VF > MaxInst)
9125         OpsWidth = MaxInst - I;
9126       else
9127         OpsWidth = VF;
9128 
9129       if (!isPowerOf2_32(OpsWidth))
9130         continue;
9131 
9132       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9133           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9134         break;
9135 
9136       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9137       // Check that a previous iteration of this loop did not delete the Value.
9138       if (llvm::any_of(Ops, [&R](Value *V) {
9139             auto *I = dyn_cast<Instruction>(V);
9140             return I && R.isDeleted(I);
9141           }))
9142         continue;
9143 
9144       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9145                         << "\n");
9146 
9147       R.buildTree(Ops);
9148       if (R.isTreeTinyAndNotFullyVectorizable())
9149         continue;
9150       R.reorderTopToBottom();
9151       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9152       R.buildExternalUses();
9153 
9154       R.computeMinimumValueSizes();
9155       InstructionCost Cost = R.getTreeCost();
9156       CandidateFound = true;
9157       MinCost = std::min(MinCost, Cost);
9158 
9159       if (Cost < -SLPCostThreshold) {
9160         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9161         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9162                                                     cast<Instruction>(Ops[0]))
9163                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9164                                  << " and with tree size "
9165                                  << ore::NV("TreeSize", R.getTreeSize()));
9166 
9167         R.vectorizeTree();
9168         // Move to the next bundle.
9169         I += VF - 1;
9170         NextInst = I + 1;
9171         Changed = true;
9172       }
9173     }
9174   }
9175 
9176   if (!Changed && CandidateFound) {
9177     R.getORE()->emit([&]() {
9178       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9179              << "List vectorization was possible but not beneficial with cost "
9180              << ore::NV("Cost", MinCost) << " >= "
9181              << ore::NV("Treshold", -SLPCostThreshold);
9182     });
9183   } else if (!Changed) {
9184     R.getORE()->emit([&]() {
9185       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9186              << "Cannot SLP vectorize list: vectorization was impossible"
9187              << " with available vectorization factors";
9188     });
9189   }
9190   return Changed;
9191 }
9192 
9193 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9194   if (!I)
9195     return false;
9196 
9197   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9198     return false;
9199 
9200   Value *P = I->getParent();
9201 
9202   // Vectorize in current basic block only.
9203   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9204   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9205   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9206     return false;
9207 
9208   // Try to vectorize V.
9209   if (tryToVectorizePair(Op0, Op1, R))
9210     return true;
9211 
9212   auto *A = dyn_cast<BinaryOperator>(Op0);
9213   auto *B = dyn_cast<BinaryOperator>(Op1);
9214   // Try to skip B.
9215   if (B && B->hasOneUse()) {
9216     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9217     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9218     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9219       return true;
9220     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9221       return true;
9222   }
9223 
9224   // Try to skip A.
9225   if (A && A->hasOneUse()) {
9226     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9227     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9228     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9229       return true;
9230     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9231       return true;
9232   }
9233   return false;
9234 }
9235 
9236 namespace {
9237 
9238 /// Model horizontal reductions.
9239 ///
9240 /// A horizontal reduction is a tree of reduction instructions that has values
9241 /// that can be put into a vector as its leaves. For example:
9242 ///
9243 /// mul mul mul mul
9244 ///  \  /    \  /
9245 ///   +       +
9246 ///    \     /
9247 ///       +
9248 /// This tree has "mul" as its leaf values and "+" as its reduction
9249 /// instructions. A reduction can feed into a store or a binary operation
9250 /// feeding a phi.
9251 ///    ...
9252 ///    \  /
9253 ///     +
9254 ///     |
9255 ///  phi +=
9256 ///
9257 ///  Or:
9258 ///    ...
9259 ///    \  /
9260 ///     +
9261 ///     |
9262 ///   *p =
9263 ///
9264 class HorizontalReduction {
9265   using ReductionOpsType = SmallVector<Value *, 16>;
9266   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9267   ReductionOpsListType ReductionOps;
9268   /// List of possibly reduced values.
9269   SmallVector<SmallVector<Value *>> ReducedVals;
9270   /// Maps reduced value to the corresponding reduction operation.
9271   DenseMap<Value *, Instruction *> ReducedValsToOps;
9272   // Use map vector to make stable output.
9273   MapVector<Instruction *, Value *> ExtraArgs;
9274   WeakTrackingVH ReductionRoot;
9275   /// The type of reduction operation.
9276   RecurKind RdxKind;
9277 
9278   static bool isCmpSelMinMax(Instruction *I) {
9279     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9280            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9281   }
9282 
9283   // And/or are potentially poison-safe logical patterns like:
9284   // select x, y, false
9285   // select x, true, y
9286   static bool isBoolLogicOp(Instruction *I) {
9287     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9288            match(I, m_LogicalOr(m_Value(), m_Value()));
9289   }
9290 
9291   /// Checks if instruction is associative and can be vectorized.
9292   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9293     if (Kind == RecurKind::None)
9294       return false;
9295 
9296     // Integer ops that map to select instructions or intrinsics are fine.
9297     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9298         isBoolLogicOp(I))
9299       return true;
9300 
9301     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9302       // FP min/max are associative except for NaN and -0.0. We do not
9303       // have to rule out -0.0 here because the intrinsic semantics do not
9304       // specify a fixed result for it.
9305       return I->getFastMathFlags().noNaNs();
9306     }
9307 
9308     return I->isAssociative();
9309   }
9310 
9311   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9312     // Poison-safe 'or' takes the form: select X, true, Y
9313     // To make that work with the normal operand processing, we skip the
9314     // true value operand.
9315     // TODO: Change the code and data structures to handle this without a hack.
9316     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9317       return I->getOperand(2);
9318     return I->getOperand(Index);
9319   }
9320 
9321   /// Creates reduction operation with the current opcode.
9322   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9323                          Value *RHS, const Twine &Name, bool UseSelect) {
9324     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9325     switch (Kind) {
9326     case RecurKind::Or:
9327       if (UseSelect &&
9328           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9329         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9330       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9331                                  Name);
9332     case RecurKind::And:
9333       if (UseSelect &&
9334           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9335         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9336       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9337                                  Name);
9338     case RecurKind::Add:
9339     case RecurKind::Mul:
9340     case RecurKind::Xor:
9341     case RecurKind::FAdd:
9342     case RecurKind::FMul:
9343       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9344                                  Name);
9345     case RecurKind::FMax:
9346       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9347     case RecurKind::FMin:
9348       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9349     case RecurKind::SMax:
9350       if (UseSelect) {
9351         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9352         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9353       }
9354       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9355     case RecurKind::SMin:
9356       if (UseSelect) {
9357         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9358         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9359       }
9360       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9361     case RecurKind::UMax:
9362       if (UseSelect) {
9363         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9364         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9365       }
9366       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9367     case RecurKind::UMin:
9368       if (UseSelect) {
9369         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9370         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9371       }
9372       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9373     default:
9374       llvm_unreachable("Unknown reduction operation.");
9375     }
9376   }
9377 
9378   /// Creates reduction operation with the current opcode with the IR flags
9379   /// from \p ReductionOps.
9380   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9381                          Value *RHS, const Twine &Name,
9382                          const ReductionOpsListType &ReductionOps) {
9383     bool UseSelect = ReductionOps.size() == 2 ||
9384                      // Logical or/and.
9385                      (ReductionOps.size() == 1 &&
9386                       isa<SelectInst>(ReductionOps.front().front()));
9387     assert((!UseSelect || ReductionOps.size() != 2 ||
9388             isa<SelectInst>(ReductionOps[1][0])) &&
9389            "Expected cmp + select pairs for reduction");
9390     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9391     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9392       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9393         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9394         propagateIRFlags(Op, ReductionOps[1]);
9395         return Op;
9396       }
9397     }
9398     propagateIRFlags(Op, ReductionOps[0]);
9399     return Op;
9400   }
9401 
9402   /// Creates reduction operation with the current opcode with the IR flags
9403   /// from \p I.
9404   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9405                          Value *RHS, const Twine &Name, Value *I) {
9406     auto *SelI = dyn_cast<SelectInst>(I);
9407     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9408     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9409       if (auto *Sel = dyn_cast<SelectInst>(Op))
9410         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9411     }
9412     propagateIRFlags(Op, I);
9413     return Op;
9414   }
9415 
9416   static RecurKind getRdxKind(Value *V) {
9417     auto *I = dyn_cast<Instruction>(V);
9418     if (!I)
9419       return RecurKind::None;
9420     if (match(I, m_Add(m_Value(), m_Value())))
9421       return RecurKind::Add;
9422     if (match(I, m_Mul(m_Value(), m_Value())))
9423       return RecurKind::Mul;
9424     if (match(I, m_And(m_Value(), m_Value())) ||
9425         match(I, m_LogicalAnd(m_Value(), m_Value())))
9426       return RecurKind::And;
9427     if (match(I, m_Or(m_Value(), m_Value())) ||
9428         match(I, m_LogicalOr(m_Value(), m_Value())))
9429       return RecurKind::Or;
9430     if (match(I, m_Xor(m_Value(), m_Value())))
9431       return RecurKind::Xor;
9432     if (match(I, m_FAdd(m_Value(), m_Value())))
9433       return RecurKind::FAdd;
9434     if (match(I, m_FMul(m_Value(), m_Value())))
9435       return RecurKind::FMul;
9436 
9437     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9438       return RecurKind::FMax;
9439     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9440       return RecurKind::FMin;
9441 
9442     // This matches either cmp+select or intrinsics. SLP is expected to handle
9443     // either form.
9444     // TODO: If we are canonicalizing to intrinsics, we can remove several
9445     //       special-case paths that deal with selects.
9446     if (match(I, m_SMax(m_Value(), m_Value())))
9447       return RecurKind::SMax;
9448     if (match(I, m_SMin(m_Value(), m_Value())))
9449       return RecurKind::SMin;
9450     if (match(I, m_UMax(m_Value(), m_Value())))
9451       return RecurKind::UMax;
9452     if (match(I, m_UMin(m_Value(), m_Value())))
9453       return RecurKind::UMin;
9454 
9455     if (auto *Select = dyn_cast<SelectInst>(I)) {
9456       // Try harder: look for min/max pattern based on instructions producing
9457       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9458       // During the intermediate stages of SLP, it's very common to have
9459       // pattern like this (since optimizeGatherSequence is run only once
9460       // at the end):
9461       // %1 = extractelement <2 x i32> %a, i32 0
9462       // %2 = extractelement <2 x i32> %a, i32 1
9463       // %cond = icmp sgt i32 %1, %2
9464       // %3 = extractelement <2 x i32> %a, i32 0
9465       // %4 = extractelement <2 x i32> %a, i32 1
9466       // %select = select i1 %cond, i32 %3, i32 %4
9467       CmpInst::Predicate Pred;
9468       Instruction *L1;
9469       Instruction *L2;
9470 
9471       Value *LHS = Select->getTrueValue();
9472       Value *RHS = Select->getFalseValue();
9473       Value *Cond = Select->getCondition();
9474 
9475       // TODO: Support inverse predicates.
9476       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9477         if (!isa<ExtractElementInst>(RHS) ||
9478             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9479           return RecurKind::None;
9480       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9481         if (!isa<ExtractElementInst>(LHS) ||
9482             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9483           return RecurKind::None;
9484       } else {
9485         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9486           return RecurKind::None;
9487         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9488             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9489             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9490           return RecurKind::None;
9491       }
9492 
9493       switch (Pred) {
9494       default:
9495         return RecurKind::None;
9496       case CmpInst::ICMP_SGT:
9497       case CmpInst::ICMP_SGE:
9498         return RecurKind::SMax;
9499       case CmpInst::ICMP_SLT:
9500       case CmpInst::ICMP_SLE:
9501         return RecurKind::SMin;
9502       case CmpInst::ICMP_UGT:
9503       case CmpInst::ICMP_UGE:
9504         return RecurKind::UMax;
9505       case CmpInst::ICMP_ULT:
9506       case CmpInst::ICMP_ULE:
9507         return RecurKind::UMin;
9508       }
9509     }
9510     return RecurKind::None;
9511   }
9512 
9513   /// Get the index of the first operand.
9514   static unsigned getFirstOperandIndex(Instruction *I) {
9515     return isCmpSelMinMax(I) ? 1 : 0;
9516   }
9517 
9518   /// Total number of operands in the reduction operation.
9519   static unsigned getNumberOfOperands(Instruction *I) {
9520     return isCmpSelMinMax(I) ? 3 : 2;
9521   }
9522 
9523   /// Checks if the instruction is in basic block \p BB.
9524   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9525   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9526     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9527       auto *Sel = cast<SelectInst>(I);
9528       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9529       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9530     }
9531     return I->getParent() == BB;
9532   }
9533 
9534   /// Expected number of uses for reduction operations/reduced values.
9535   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9536     if (IsCmpSelMinMax) {
9537       // SelectInst must be used twice while the condition op must have single
9538       // use only.
9539       if (auto *Sel = dyn_cast<SelectInst>(I))
9540         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9541       return I->hasNUses(2);
9542     }
9543 
9544     // Arithmetic reduction operation must be used once only.
9545     return I->hasOneUse();
9546   }
9547 
9548   /// Initializes the list of reduction operations.
9549   void initReductionOps(Instruction *I) {
9550     if (isCmpSelMinMax(I))
9551       ReductionOps.assign(2, ReductionOpsType());
9552     else
9553       ReductionOps.assign(1, ReductionOpsType());
9554   }
9555 
9556   /// Add all reduction operations for the reduction instruction \p I.
9557   void addReductionOps(Instruction *I) {
9558     if (isCmpSelMinMax(I)) {
9559       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9560       ReductionOps[1].emplace_back(I);
9561     } else {
9562       ReductionOps[0].emplace_back(I);
9563     }
9564   }
9565 
9566   static Value *getLHS(RecurKind Kind, Instruction *I) {
9567     if (Kind == RecurKind::None)
9568       return nullptr;
9569     return I->getOperand(getFirstOperandIndex(I));
9570   }
9571   static Value *getRHS(RecurKind Kind, Instruction *I) {
9572     if (Kind == RecurKind::None)
9573       return nullptr;
9574     return I->getOperand(getFirstOperandIndex(I) + 1);
9575   }
9576 
9577 public:
9578   HorizontalReduction() = default;
9579 
9580   /// Try to find a reduction tree.
9581   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9582                                  ScalarEvolution &SE, const DataLayout &DL,
9583                                  const TargetLibraryInfo &TLI) {
9584     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9585            "Phi needs to use the binary operator");
9586     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9587             isa<IntrinsicInst>(Inst)) &&
9588            "Expected binop, select, or intrinsic for reduction matching");
9589     RdxKind = getRdxKind(Inst);
9590 
9591     // We could have a initial reductions that is not an add.
9592     //  r *= v1 + v2 + v3 + v4
9593     // In such a case start looking for a tree rooted in the first '+'.
9594     if (Phi) {
9595       if (getLHS(RdxKind, Inst) == Phi) {
9596         Phi = nullptr;
9597         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9598         if (!Inst)
9599           return false;
9600         RdxKind = getRdxKind(Inst);
9601       } else if (getRHS(RdxKind, Inst) == Phi) {
9602         Phi = nullptr;
9603         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9604         if (!Inst)
9605           return false;
9606         RdxKind = getRdxKind(Inst);
9607       }
9608     }
9609 
9610     if (!isVectorizable(RdxKind, Inst))
9611       return false;
9612 
9613     // Analyze "regular" integer/FP types for reductions - no target-specific
9614     // types or pointers.
9615     Type *Ty = Inst->getType();
9616     if (!isValidElementType(Ty) || Ty->isPointerTy())
9617       return false;
9618 
9619     // Though the ultimate reduction may have multiple uses, its condition must
9620     // have only single use.
9621     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9622       if (!Sel->getCondition()->hasOneUse())
9623         return false;
9624 
9625     ReductionRoot = Inst;
9626 
9627     // Iterate through all the operands of the possible reduction tree and
9628     // gather all the reduced values, sorting them by their value id.
9629     BasicBlock *BB = Inst->getParent();
9630     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9631     SmallVector<Instruction *> Worklist(1, Inst);
9632     // Checks if the operands of the \p TreeN instruction are also reduction
9633     // operations or should be treated as reduced values or an extra argument,
9634     // which is not part of the reduction.
9635     auto &&CheckOperands = [this, IsCmpSelMinMax,
9636                             BB](Instruction *TreeN,
9637                                 SmallVectorImpl<Value *> &ExtraArgs,
9638                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9639                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9640       for (int I = getFirstOperandIndex(TreeN),
9641                End = getNumberOfOperands(TreeN);
9642            I < End; ++I) {
9643         Value *EdgeVal = getRdxOperand(TreeN, I);
9644         ReducedValsToOps.try_emplace(EdgeVal, TreeN);
9645         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9646         // Edge has wrong parent - mark as an extra argument.
9647         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9648             !hasSameParent(EdgeInst, BB)) {
9649           ExtraArgs.push_back(EdgeVal);
9650           continue;
9651         }
9652         // If the edge is not an instruction, or it is different from the main
9653         // reduction opcode or has too many uses - possible reduced value.
9654         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9655             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9656             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9657           PossibleReducedVals.push_back(EdgeVal);
9658           continue;
9659         }
9660         ReductionOps.push_back(EdgeInst);
9661       }
9662     };
9663     // Try to regroup reduced values so that it gets more profitable to try to
9664     // reduce them. Values are grouped by their value ids, instructions - by
9665     // instruction op id and/or alternate op id, plus do extra analysis for
9666     // loads (grouping them by the distabce between pointers) and cmp
9667     // instructions (grouping them by the predicate).
9668     MapVector<size_t, MapVector<size_t, SmallVector<Value *>>>
9669         PossibleReducedVals;
9670     initReductionOps(Inst);
9671     while (!Worklist.empty()) {
9672       Instruction *TreeN = Worklist.pop_back_val();
9673       SmallVector<Value *> Args;
9674       SmallVector<Value *> PossibleRedVals;
9675       SmallVector<Instruction *> PossibleReductionOps;
9676       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9677       // If too many extra args - mark the instruction itself as a reduction
9678       // value, not a reduction operation.
9679       if (Args.size() < 2) {
9680         addReductionOps(TreeN);
9681         // Add extra args.
9682         if (!Args.empty()) {
9683           assert(Args.size() == 1 && "Expected only single argument.");
9684           ExtraArgs[TreeN] = Args.front();
9685         }
9686         // Add reduction values. The values are sorted for better vectorization
9687         // results.
9688         for (Value *V : PossibleRedVals) {
9689           size_t Key, Idx;
9690           std::tie(Key, Idx) = generateKeySubkey(
9691               V, &TLI,
9692               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9693                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9694                   auto *RLI = cast<LoadInst>(LoadData.second.front());
9695                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9696                                       LI->getType(), LI->getPointerOperand(),
9697                                       DL, SE, /*StrictCheck=*/true))
9698                     return hash_value(RLI->getPointerOperand());
9699                 }
9700                 return hash_value(LI->getPointerOperand());
9701               },
9702               /*AllowAlternate=*/false);
9703           PossibleReducedVals[Key][Idx].push_back(V);
9704         }
9705         Worklist.append(PossibleReductionOps.begin(),
9706                         PossibleReductionOps.end());
9707       } else {
9708         size_t Key, Idx;
9709         std::tie(Key, Idx) = generateKeySubkey(
9710             TreeN, &TLI,
9711             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9712               for (const auto &LoadData : PossibleReducedVals[Key]) {
9713                 auto *RLI = cast<LoadInst>(LoadData.second.front());
9714                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9715                                     LI->getType(), LI->getPointerOperand(), DL,
9716                                     SE, /*StrictCheck=*/true))
9717                   return hash_value(RLI->getPointerOperand());
9718               }
9719               return hash_value(LI->getPointerOperand());
9720             },
9721             /*AllowAlternate=*/false);
9722         PossibleReducedVals[Key][Idx].push_back(TreeN);
9723       }
9724     }
9725     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9726     // Sort values by the total number of values kinds to start the reduction
9727     // from the longest possible reduced values sequences.
9728     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9729       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9730       stable_sort(PossibleRedVals, [](const auto &P1, const auto &P2) {
9731         return P1.second.size() > P2.second.size();
9732       });
9733       ReducedVals.emplace_back();
9734       for (auto &Data : PossibleRedVals)
9735         ReducedVals.back().append(Data.second.rbegin(), Data.second.rend());
9736     }
9737     // Sort the reduced values by number of same/alternate opcode and/or pointer
9738     // operand.
9739     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
9740       return P1.size() > P2.size();
9741     });
9742     return true;
9743   }
9744 
9745   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9746   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9747     // If there are a sufficient number of reduction values, reduce
9748     // to a nearby power-of-2. We can safely generate oversized
9749     // vectors and rely on the backend to split them to legal sizes.
9750     unsigned NumReducedVals = std::accumulate(
9751         ReducedVals.begin(), ReducedVals.end(), 0,
9752         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
9753     if (NumReducedVals < 4)
9754       return nullptr;
9755 
9756     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9757 
9758     // Track the reduced values in case if they are replaced by extractelement
9759     // because of the vectorization.
9760     DenseMap<Value *, WeakTrackingVH> TrackedVals;
9761     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9762     // The same extra argument may be used several times, so log each attempt
9763     // to use it.
9764     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9765       assert(Pair.first && "DebugLoc must be set.");
9766       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9767       TrackedVals.try_emplace(Pair.second, Pair.second);
9768     }
9769 
9770     // The compare instruction of a min/max is the insertion point for new
9771     // instructions and may be replaced with a new compare instruction.
9772     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9773       assert(isa<SelectInst>(RdxRootInst) &&
9774              "Expected min/max reduction to have select root instruction");
9775       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9776       assert(isa<Instruction>(ScalarCond) &&
9777              "Expected min/max reduction to have compare condition");
9778       return cast<Instruction>(ScalarCond);
9779     };
9780 
9781     // The reduction root is used as the insertion point for new instructions,
9782     // so set it as externally used to prevent it from being deleted.
9783     ExternallyUsedValues[ReductionRoot];
9784     SmallVector<Value *> IgnoreList;
9785     for (ReductionOpsType &RdxOps : ReductionOps)
9786       for (Value *RdxOp : RdxOps) {
9787         if (!RdxOp)
9788           continue;
9789         IgnoreList.push_back(RdxOp);
9790       }
9791 
9792     // Need to track reduced vals, they may be changed during vectorization of
9793     // subvectors.
9794     for (ArrayRef<Value *> Candidates : ReducedVals)
9795       for (Value *V : Candidates)
9796         TrackedVals.try_emplace(V, V);
9797 
9798     DenseMap<Value *, unsigned> VectorizedVals;
9799     Value *VectorizedTree = nullptr;
9800     // Try to vectorize elements based on their type.
9801     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9802       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
9803       InstructionsState S = getSameOpcode(OrigReducedVals);
9804       SmallVector<Value *> Candidates;
9805       DenseMap<Value *, Value *> TrackedToOrig;
9806       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
9807         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
9808         // Check if the reduction value was not overriden by the extractelement
9809         // instruction because of the vectorization and exclude it, if it is not
9810         // compatible with other values.
9811         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9812           if (isVectorLikeInstWithConstOps(Inst) &&
9813               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
9814             continue;
9815         Candidates.push_back(RdxVal);
9816         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
9817       }
9818       bool ShuffledExtracts = false;
9819       // Try to handle shuffled extractelements.
9820       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
9821           I + 1 < E) {
9822         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
9823         if (NextS.getOpcode() == Instruction::ExtractElement &&
9824             !NextS.isAltShuffle()) {
9825           SmallVector<Value *> CommonCandidates(Candidates);
9826           for (Value *RV : ReducedVals[I + 1]) {
9827             Value *RdxVal = TrackedVals.find(RV)->second;
9828             // Check if the reduction value was not overriden by the
9829             // extractelement instruction because of the vectorization and
9830             // exclude it, if it is not compatible with other values.
9831             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9832               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
9833                 continue;
9834             CommonCandidates.push_back(RdxVal);
9835             TrackedToOrig.try_emplace(RdxVal, RV);
9836           }
9837           SmallVector<int> Mask;
9838           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
9839             ++I;
9840             Candidates.swap(CommonCandidates);
9841             ShuffledExtracts = true;
9842           }
9843         }
9844       }
9845       unsigned NumReducedVals = Candidates.size();
9846       if (NumReducedVals < 4)
9847         continue;
9848 
9849       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9850       unsigned Start = 0;
9851       unsigned Pos = Start;
9852       // Restarts vectorization attempt with lower vector factor.
9853       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals]() {
9854         if (ReduxWidth == 4 || Pos >= NumReducedVals - ReduxWidth + 1) {
9855           ++Start;
9856           ReduxWidth = PowerOf2Floor(NumReducedVals - Start) * 2;
9857         }
9858         Pos = Start;
9859         ReduxWidth /= 2;
9860       };
9861       while (Pos < NumReducedVals - ReduxWidth + 1 && ReduxWidth >= 4) {
9862         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
9863         V.buildTree(VL, IgnoreList);
9864         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
9865           AdjustReducedVals();
9866           continue;
9867         }
9868         if (V.isLoadCombineReductionCandidate(RdxKind)) {
9869           AdjustReducedVals();
9870           continue;
9871         }
9872         V.reorderTopToBottom();
9873         // No need to reorder the root node at all.
9874         V.reorderBottomToTop(/*IgnoreReorder=*/true);
9875         // Keep extracted other reduction values, if they are used in the
9876         // vectorization trees.
9877         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
9878             ExternallyUsedValues);
9879         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
9880           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
9881             continue;
9882           for_each(ReducedVals[Cnt],
9883                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
9884                      if (isa<Instruction>(V))
9885                        LocalExternallyUsedValues[TrackedVals[V]];
9886                    });
9887         }
9888         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
9889           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
9890             continue;
9891           if (VectorizedVals.count(Candidates[Cnt]))
9892             continue;
9893           LocalExternallyUsedValues[Candidates[Cnt]];
9894         }
9895         V.buildExternalUses(LocalExternallyUsedValues);
9896 
9897         V.computeMinimumValueSizes();
9898 
9899         // Intersect the fast-math-flags from all reduction operations.
9900         FastMathFlags RdxFMF;
9901         RdxFMF.set();
9902         for (Value *RdxVal : VL) {
9903           if (auto *FPMO = dyn_cast<FPMathOperator>(
9904                   ReducedValsToOps.find(RdxVal)->second))
9905             RdxFMF &= FPMO->getFastMathFlags();
9906         }
9907         // Estimate cost.
9908         InstructionCost TreeCost = V.getTreeCost(VL);
9909         InstructionCost ReductionCost =
9910             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
9911         InstructionCost Cost = TreeCost + ReductionCost;
9912         if (!Cost.isValid()) {
9913           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9914           return nullptr;
9915         }
9916         if (Cost >= -SLPCostThreshold) {
9917           V.getORE()->emit([&]() {
9918             return OptimizationRemarkMissed(
9919                        SV_NAME, "HorSLPNotBeneficial",
9920                        ReducedValsToOps.find(VL[0])->second)
9921                    << "Vectorizing horizontal reduction is possible"
9922                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
9923                    << " and threshold "
9924                    << ore::NV("Threshold", -SLPCostThreshold);
9925           });
9926           AdjustReducedVals();
9927           continue;
9928         }
9929 
9930         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9931                           << Cost << ". (HorRdx)\n");
9932         V.getORE()->emit([&]() {
9933           return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9934                                     ReducedValsToOps.find(VL[0])->second)
9935                  << "Vectorized horizontal reduction with cost "
9936                  << ore::NV("Cost", Cost) << " and with tree size "
9937                  << ore::NV("TreeSize", V.getTreeSize());
9938         });
9939 
9940         Builder.setFastMathFlags(RdxFMF);
9941 
9942         // Vectorize a tree.
9943         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
9944 
9945         // Emit a reduction. If the root is a select (min/max idiom), the insert
9946         // point is the compare condition of that select.
9947         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9948         if (isCmpSelMinMax(RdxRootInst))
9949           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
9950         else
9951           Builder.SetInsertPoint(RdxRootInst);
9952 
9953         // To prevent poison from leaking across what used to be sequential,
9954         // safe, scalar boolean logic operations, the reduction operand must be
9955         // frozen.
9956         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9957           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9958 
9959         Value *ReducedSubTree =
9960             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9961 
9962         if (!VectorizedTree) {
9963           // Initialize the final value in the reduction.
9964           VectorizedTree = ReducedSubTree;
9965         } else {
9966           // Update the final value in the reduction.
9967           Builder.SetCurrentDebugLocation(
9968               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
9969           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9970                                     ReducedSubTree, "op.rdx", ReductionOps);
9971         }
9972         // Count vectorized reduced values to exclude them from final reduction.
9973         for (Value *V : VL)
9974           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
9975                 .first->getSecond();
9976         Pos += ReduxWidth;
9977         Start = Pos;
9978         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
9979       }
9980     }
9981     if (VectorizedTree) {
9982       // Finish the reduction.
9983       // Need to add extra arguments and not vectorized possible reduction
9984       // values.
9985       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9986         ArrayRef<Value *> Candidates = ReducedVals[I];
9987         for (Value *RdxVal : Candidates) {
9988           auto It = VectorizedVals.find(RdxVal);
9989           if (It != VectorizedVals.end()) {
9990             --It->getSecond();
9991             if (It->second == 0)
9992               VectorizedVals.erase(It);
9993             continue;
9994           }
9995           Instruction *RedOp = ReducedValsToOps.find(RdxVal)->second;
9996           Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
9997           ReductionOpsListType Ops;
9998           if (auto *Sel = dyn_cast<SelectInst>(RedOp))
9999             Ops.emplace_back().push_back(Sel->getCondition());
10000           Ops.emplace_back().push_back(RedOp);
10001           Value *StableRdxVal = RdxVal;
10002           auto TVIt = TrackedVals.find(RdxVal);
10003           if (TVIt != TrackedVals.end())
10004             StableRdxVal = TVIt->second;
10005 
10006           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10007                                     StableRdxVal, "op.rdx", RedOp);
10008         }
10009       }
10010       for (auto &Pair : ExternallyUsedValues) {
10011         // Add each externally used value to the final reduction.
10012         for (auto *I : Pair.second) {
10013           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10014           ReductionOpsListType Ops;
10015           if (auto *Sel = dyn_cast<SelectInst>(I))
10016             Ops.emplace_back().push_back(Sel->getCondition());
10017           Ops.emplace_back().push_back(I);
10018           Value *StableRdxVal = Pair.first;
10019           auto TVIt = TrackedVals.find(Pair.first);
10020           if (TVIt != TrackedVals.end())
10021             StableRdxVal = TVIt->second;
10022           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10023                                     StableRdxVal, "op.rdx", Ops);
10024         }
10025       }
10026 
10027       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10028 
10029       // The original scalar reduction is expected to have no remaining
10030       // uses outside the reduction tree itself.  Assert that we got this
10031       // correct, replace internal uses with undef, and mark for eventual
10032       // deletion.
10033 #ifndef NDEBUG
10034       SmallSet<Value *, 4> IgnoreSet;
10035       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
10036 #endif
10037       for (auto *Ignore : IgnoreList) {
10038 #ifndef NDEBUG
10039         for (auto *U : Ignore->users()) {
10040           assert(IgnoreSet.count(U));
10041         }
10042 #endif
10043         if (!Ignore->use_empty()) {
10044           Value *Undef = UndefValue::get(Ignore->getType());
10045           Ignore->replaceAllUsesWith(Undef);
10046         }
10047         V.eraseInstruction(cast<Instruction>(Ignore));
10048       }
10049     }
10050     return VectorizedTree;
10051   }
10052 
10053   unsigned numReductionValues() const { return ReducedVals.size(); }
10054 
10055 private:
10056   /// Calculate the cost of a reduction.
10057   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10058                                    Value *FirstReducedVal, unsigned ReduxWidth,
10059                                    FastMathFlags FMF) {
10060     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10061     Type *ScalarTy = FirstReducedVal->getType();
10062     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10063     InstructionCost VectorCost, ScalarCost;
10064     switch (RdxKind) {
10065     case RecurKind::Add:
10066     case RecurKind::Mul:
10067     case RecurKind::Or:
10068     case RecurKind::And:
10069     case RecurKind::Xor:
10070     case RecurKind::FAdd:
10071     case RecurKind::FMul: {
10072       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10073       VectorCost =
10074           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10075       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10076       break;
10077     }
10078     case RecurKind::FMax:
10079     case RecurKind::FMin: {
10080       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10081       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10082       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10083                                                /*IsUnsigned=*/false, CostKind);
10084       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10085       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10086                                            SclCondTy, RdxPred, CostKind) +
10087                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10088                                            SclCondTy, RdxPred, CostKind);
10089       break;
10090     }
10091     case RecurKind::SMax:
10092     case RecurKind::SMin:
10093     case RecurKind::UMax:
10094     case RecurKind::UMin: {
10095       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10096       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10097       bool IsUnsigned =
10098           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10099       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10100                                                CostKind);
10101       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10102       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10103                                            SclCondTy, RdxPred, CostKind) +
10104                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10105                                            SclCondTy, RdxPred, CostKind);
10106       break;
10107     }
10108     default:
10109       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10110     }
10111 
10112     // Scalar cost is repeated for N-1 elements.
10113     ScalarCost *= (ReduxWidth - 1);
10114     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10115                       << " for reduction that starts with " << *FirstReducedVal
10116                       << " (It is a splitting reduction)\n");
10117     return VectorCost - ScalarCost;
10118   }
10119 
10120   /// Emit a horizontal reduction of the vectorized value.
10121   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10122                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10123     assert(VectorizedValue && "Need to have a vectorized tree node");
10124     assert(isPowerOf2_32(ReduxWidth) &&
10125            "We only handle power-of-two reductions for now");
10126     assert(RdxKind != RecurKind::FMulAdd &&
10127            "A call to the llvm.fmuladd intrinsic is not handled yet");
10128 
10129     ++NumVectorInstructions;
10130     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10131   }
10132 };
10133 
10134 } // end anonymous namespace
10135 
10136 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10137   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10138     return cast<FixedVectorType>(IE->getType())->getNumElements();
10139 
10140   unsigned AggregateSize = 1;
10141   auto *IV = cast<InsertValueInst>(InsertInst);
10142   Type *CurrentType = IV->getType();
10143   do {
10144     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10145       for (auto *Elt : ST->elements())
10146         if (Elt != ST->getElementType(0)) // check homogeneity
10147           return None;
10148       AggregateSize *= ST->getNumElements();
10149       CurrentType = ST->getElementType(0);
10150     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10151       AggregateSize *= AT->getNumElements();
10152       CurrentType = AT->getElementType();
10153     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10154       AggregateSize *= VT->getNumElements();
10155       return AggregateSize;
10156     } else if (CurrentType->isSingleValueType()) {
10157       return AggregateSize;
10158     } else {
10159       return None;
10160     }
10161   } while (true);
10162 }
10163 
10164 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10165                                    TargetTransformInfo *TTI,
10166                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10167                                    SmallVectorImpl<Value *> &InsertElts,
10168                                    unsigned OperandOffset) {
10169   do {
10170     Value *InsertedOperand = LastInsertInst->getOperand(1);
10171     Optional<unsigned> OperandIndex =
10172         getInsertIndex(LastInsertInst, OperandOffset);
10173     if (!OperandIndex)
10174       return;
10175     if (isa<InsertElementInst>(InsertedOperand) ||
10176         isa<InsertValueInst>(InsertedOperand)) {
10177       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10178                              BuildVectorOpds, InsertElts, *OperandIndex);
10179 
10180     } else {
10181       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10182       InsertElts[*OperandIndex] = LastInsertInst;
10183     }
10184     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10185   } while (LastInsertInst != nullptr &&
10186            (isa<InsertValueInst>(LastInsertInst) ||
10187             isa<InsertElementInst>(LastInsertInst)) &&
10188            LastInsertInst->hasOneUse());
10189 }
10190 
10191 /// Recognize construction of vectors like
10192 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10193 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10194 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10195 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10196 ///  starting from the last insertelement or insertvalue instruction.
10197 ///
10198 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10199 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10200 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10201 ///
10202 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10203 ///
10204 /// \return true if it matches.
10205 static bool findBuildAggregate(Instruction *LastInsertInst,
10206                                TargetTransformInfo *TTI,
10207                                SmallVectorImpl<Value *> &BuildVectorOpds,
10208                                SmallVectorImpl<Value *> &InsertElts) {
10209 
10210   assert((isa<InsertElementInst>(LastInsertInst) ||
10211           isa<InsertValueInst>(LastInsertInst)) &&
10212          "Expected insertelement or insertvalue instruction!");
10213 
10214   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10215          "Expected empty result vectors!");
10216 
10217   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10218   if (!AggregateSize)
10219     return false;
10220   BuildVectorOpds.resize(*AggregateSize);
10221   InsertElts.resize(*AggregateSize);
10222 
10223   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10224   llvm::erase_value(BuildVectorOpds, nullptr);
10225   llvm::erase_value(InsertElts, nullptr);
10226   if (BuildVectorOpds.size() >= 2)
10227     return true;
10228 
10229   return false;
10230 }
10231 
10232 /// Try and get a reduction value from a phi node.
10233 ///
10234 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10235 /// if they come from either \p ParentBB or a containing loop latch.
10236 ///
10237 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10238 /// if not possible.
10239 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10240                                 BasicBlock *ParentBB, LoopInfo *LI) {
10241   // There are situations where the reduction value is not dominated by the
10242   // reduction phi. Vectorizing such cases has been reported to cause
10243   // miscompiles. See PR25787.
10244   auto DominatedReduxValue = [&](Value *R) {
10245     return isa<Instruction>(R) &&
10246            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10247   };
10248 
10249   Value *Rdx = nullptr;
10250 
10251   // Return the incoming value if it comes from the same BB as the phi node.
10252   if (P->getIncomingBlock(0) == ParentBB) {
10253     Rdx = P->getIncomingValue(0);
10254   } else if (P->getIncomingBlock(1) == ParentBB) {
10255     Rdx = P->getIncomingValue(1);
10256   }
10257 
10258   if (Rdx && DominatedReduxValue(Rdx))
10259     return Rdx;
10260 
10261   // Otherwise, check whether we have a loop latch to look at.
10262   Loop *BBL = LI->getLoopFor(ParentBB);
10263   if (!BBL)
10264     return nullptr;
10265   BasicBlock *BBLatch = BBL->getLoopLatch();
10266   if (!BBLatch)
10267     return nullptr;
10268 
10269   // There is a loop latch, return the incoming value if it comes from
10270   // that. This reduction pattern occasionally turns up.
10271   if (P->getIncomingBlock(0) == BBLatch) {
10272     Rdx = P->getIncomingValue(0);
10273   } else if (P->getIncomingBlock(1) == BBLatch) {
10274     Rdx = P->getIncomingValue(1);
10275   }
10276 
10277   if (Rdx && DominatedReduxValue(Rdx))
10278     return Rdx;
10279 
10280   return nullptr;
10281 }
10282 
10283 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10284   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10285     return true;
10286   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10287     return true;
10288   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10289     return true;
10290   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10291     return true;
10292   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10293     return true;
10294   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10295     return true;
10296   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10297     return true;
10298   return false;
10299 }
10300 
10301 /// Attempt to reduce a horizontal reduction.
10302 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10303 /// with reduction operators \a Root (or one of its operands) in a basic block
10304 /// \a BB, then check if it can be done. If horizontal reduction is not found
10305 /// and root instruction is a binary operation, vectorization of the operands is
10306 /// attempted.
10307 /// \returns true if a horizontal reduction was matched and reduced or operands
10308 /// of one of the binary instruction were vectorized.
10309 /// \returns false if a horizontal reduction was not matched (or not possible)
10310 /// or no vectorization of any binary operation feeding \a Root instruction was
10311 /// performed.
10312 static bool tryToVectorizeHorReductionOrInstOperands(
10313     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10314     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10315     const TargetLibraryInfo &TLI,
10316     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10317   if (!ShouldVectorizeHor)
10318     return false;
10319 
10320   if (!Root)
10321     return false;
10322 
10323   if (Root->getParent() != BB || isa<PHINode>(Root))
10324     return false;
10325   // Start analysis starting from Root instruction. If horizontal reduction is
10326   // found, try to vectorize it. If it is not a horizontal reduction or
10327   // vectorization is not possible or not effective, and currently analyzed
10328   // instruction is a binary operation, try to vectorize the operands, using
10329   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10330   // the same procedure considering each operand as a possible root of the
10331   // horizontal reduction.
10332   // Interrupt the process if the Root instruction itself was vectorized or all
10333   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10334   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10335   // CmpInsts so we can skip extra attempts in
10336   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10337   std::queue<std::pair<Instruction *, unsigned>> Stack;
10338   Stack.emplace(Root, 0);
10339   SmallPtrSet<Value *, 8> VisitedInstrs;
10340   SmallVector<WeakTrackingVH> PostponedInsts;
10341   bool Res = false;
10342   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10343                                                      Value *&B0,
10344                                                      Value *&B1) -> Value * {
10345     bool IsBinop = matchRdxBop(Inst, B0, B1);
10346     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10347     if (IsBinop || IsSelect) {
10348       HorizontalReduction HorRdx;
10349       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10350         return HorRdx.tryToReduce(R, TTI);
10351     }
10352     return nullptr;
10353   };
10354   while (!Stack.empty()) {
10355     Instruction *Inst;
10356     unsigned Level;
10357     std::tie(Inst, Level) = Stack.front();
10358     Stack.pop();
10359     // Do not try to analyze instruction that has already been vectorized.
10360     // This may happen when we vectorize instruction operands on a previous
10361     // iteration while stack was populated before that happened.
10362     if (R.isDeleted(Inst))
10363       continue;
10364     Value *B0 = nullptr, *B1 = nullptr;
10365     if (Value *V = TryToReduce(Inst, B0, B1)) {
10366       Res = true;
10367       // Set P to nullptr to avoid re-analysis of phi node in
10368       // matchAssociativeReduction function unless this is the root node.
10369       P = nullptr;
10370       if (auto *I = dyn_cast<Instruction>(V)) {
10371         // Try to find another reduction.
10372         Stack.emplace(I, Level);
10373         continue;
10374       }
10375     } else {
10376       bool IsBinop = B0 && B1;
10377       if (P && IsBinop) {
10378         Inst = dyn_cast<Instruction>(B0);
10379         if (Inst == P)
10380           Inst = dyn_cast<Instruction>(B1);
10381         if (!Inst) {
10382           // Set P to nullptr to avoid re-analysis of phi node in
10383           // matchAssociativeReduction function unless this is the root node.
10384           P = nullptr;
10385           continue;
10386         }
10387       }
10388       // Set P to nullptr to avoid re-analysis of phi node in
10389       // matchAssociativeReduction function unless this is the root node.
10390       P = nullptr;
10391       // Do not try to vectorize CmpInst operands, this is done separately.
10392       // Final attempt for binop args vectorization should happen after the loop
10393       // to try to find reductions.
10394       if (!isa<CmpInst>(Inst))
10395         PostponedInsts.push_back(Inst);
10396     }
10397 
10398     // Try to vectorize operands.
10399     // Continue analysis for the instruction from the same basic block only to
10400     // save compile time.
10401     if (++Level < RecursionMaxDepth)
10402       for (auto *Op : Inst->operand_values())
10403         if (VisitedInstrs.insert(Op).second)
10404           if (auto *I = dyn_cast<Instruction>(Op))
10405             // Do not try to vectorize CmpInst operands,  this is done
10406             // separately.
10407             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10408                 I->getParent() == BB)
10409               Stack.emplace(I, Level);
10410   }
10411   // Try to vectorized binops where reductions were not found.
10412   for (Value *V : PostponedInsts)
10413     if (auto *Inst = dyn_cast<Instruction>(V))
10414       if (!R.isDeleted(Inst))
10415         Res |= Vectorize(Inst, R);
10416   return Res;
10417 }
10418 
10419 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10420                                                  BasicBlock *BB, BoUpSLP &R,
10421                                                  TargetTransformInfo *TTI) {
10422   auto *I = dyn_cast_or_null<Instruction>(V);
10423   if (!I)
10424     return false;
10425 
10426   if (!isa<BinaryOperator>(I))
10427     P = nullptr;
10428   // Try to match and vectorize a horizontal reduction.
10429   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10430     return tryToVectorize(I, R);
10431   };
10432   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10433                                                   *TLI, ExtraVectorization);
10434 }
10435 
10436 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10437                                                  BasicBlock *BB, BoUpSLP &R) {
10438   const DataLayout &DL = BB->getModule()->getDataLayout();
10439   if (!R.canMapToVector(IVI->getType(), DL))
10440     return false;
10441 
10442   SmallVector<Value *, 16> BuildVectorOpds;
10443   SmallVector<Value *, 16> BuildVectorInsts;
10444   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10445     return false;
10446 
10447   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10448   // Aggregate value is unlikely to be processed in vector register.
10449   return tryToVectorizeList(BuildVectorOpds, R);
10450 }
10451 
10452 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10453                                                    BasicBlock *BB, BoUpSLP &R) {
10454   SmallVector<Value *, 16> BuildVectorInsts;
10455   SmallVector<Value *, 16> BuildVectorOpds;
10456   SmallVector<int> Mask;
10457   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10458       (llvm::all_of(
10459            BuildVectorOpds,
10460            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10461        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10462     return false;
10463 
10464   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10465   return tryToVectorizeList(BuildVectorInsts, R);
10466 }
10467 
10468 template <typename T>
10469 static bool
10470 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10471                        function_ref<unsigned(T *)> Limit,
10472                        function_ref<bool(T *, T *)> Comparator,
10473                        function_ref<bool(T *, T *)> AreCompatible,
10474                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10475                        bool LimitForRegisterSize) {
10476   bool Changed = false;
10477   // Sort by type, parent, operands.
10478   stable_sort(Incoming, Comparator);
10479 
10480   // Try to vectorize elements base on their type.
10481   SmallVector<T *> Candidates;
10482   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10483     // Look for the next elements with the same type, parent and operand
10484     // kinds.
10485     auto *SameTypeIt = IncIt;
10486     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10487       ++SameTypeIt;
10488 
10489     // Try to vectorize them.
10490     unsigned NumElts = (SameTypeIt - IncIt);
10491     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10492                       << NumElts << ")\n");
10493     // The vectorization is a 3-state attempt:
10494     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10495     // size of maximal register at first.
10496     // 2. Try to vectorize remaining instructions with the same type, if
10497     // possible. This may result in the better vectorization results rather than
10498     // if we try just to vectorize instructions with the same/alternate opcodes.
10499     // 3. Final attempt to try to vectorize all instructions with the
10500     // same/alternate ops only, this may result in some extra final
10501     // vectorization.
10502     if (NumElts > 1 &&
10503         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10504       // Success start over because instructions might have been changed.
10505       Changed = true;
10506     } else if (NumElts < Limit(*IncIt) &&
10507                (Candidates.empty() ||
10508                 Candidates.front()->getType() == (*IncIt)->getType())) {
10509       Candidates.append(IncIt, std::next(IncIt, NumElts));
10510     }
10511     // Final attempt to vectorize instructions with the same types.
10512     if (Candidates.size() > 1 &&
10513         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10514       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10515         // Success start over because instructions might have been changed.
10516         Changed = true;
10517       } else if (LimitForRegisterSize) {
10518         // Try to vectorize using small vectors.
10519         for (auto *It = Candidates.begin(), *End = Candidates.end();
10520              It != End;) {
10521           auto *SameTypeIt = It;
10522           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10523             ++SameTypeIt;
10524           unsigned NumElts = (SameTypeIt - It);
10525           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10526                                             /*LimitForRegisterSize=*/false))
10527             Changed = true;
10528           It = SameTypeIt;
10529         }
10530       }
10531       Candidates.clear();
10532     }
10533 
10534     // Start over at the next instruction of a different type (or the end).
10535     IncIt = SameTypeIt;
10536   }
10537   return Changed;
10538 }
10539 
10540 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10541 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10542 /// operands. If IsCompatibility is false, function implements strict weak
10543 /// ordering relation between two cmp instructions, returning true if the first
10544 /// instruction is "less" than the second, i.e. its predicate is less than the
10545 /// predicate of the second or the operands IDs are less than the operands IDs
10546 /// of the second cmp instruction.
10547 template <bool IsCompatibility>
10548 static bool compareCmp(Value *V, Value *V2,
10549                        function_ref<bool(Instruction *)> IsDeleted) {
10550   auto *CI1 = cast<CmpInst>(V);
10551   auto *CI2 = cast<CmpInst>(V2);
10552   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10553     return false;
10554   if (CI1->getOperand(0)->getType()->getTypeID() <
10555       CI2->getOperand(0)->getType()->getTypeID())
10556     return !IsCompatibility;
10557   if (CI1->getOperand(0)->getType()->getTypeID() >
10558       CI2->getOperand(0)->getType()->getTypeID())
10559     return false;
10560   CmpInst::Predicate Pred1 = CI1->getPredicate();
10561   CmpInst::Predicate Pred2 = CI2->getPredicate();
10562   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10563   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10564   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10565   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10566   if (BasePred1 < BasePred2)
10567     return !IsCompatibility;
10568   if (BasePred1 > BasePred2)
10569     return false;
10570   // Compare operands.
10571   bool LEPreds = Pred1 <= Pred2;
10572   bool GEPreds = Pred1 >= Pred2;
10573   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10574     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10575     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10576     if (Op1->getValueID() < Op2->getValueID())
10577       return !IsCompatibility;
10578     if (Op1->getValueID() > Op2->getValueID())
10579       return false;
10580     if (auto *I1 = dyn_cast<Instruction>(Op1))
10581       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10582         if (I1->getParent() != I2->getParent())
10583           return false;
10584         InstructionsState S = getSameOpcode({I1, I2});
10585         if (S.getOpcode())
10586           continue;
10587         return false;
10588       }
10589   }
10590   return IsCompatibility;
10591 }
10592 
10593 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10594     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10595     bool AtTerminator) {
10596   bool OpsChanged = false;
10597   SmallVector<Instruction *, 4> PostponedCmps;
10598   for (auto *I : reverse(Instructions)) {
10599     if (R.isDeleted(I))
10600       continue;
10601     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10602       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10603     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10604       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10605     else if (isa<CmpInst>(I))
10606       PostponedCmps.push_back(I);
10607   }
10608   if (AtTerminator) {
10609     // Try to find reductions first.
10610     for (Instruction *I : PostponedCmps) {
10611       if (R.isDeleted(I))
10612         continue;
10613       for (Value *Op : I->operands())
10614         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10615     }
10616     // Try to vectorize operands as vector bundles.
10617     for (Instruction *I : PostponedCmps) {
10618       if (R.isDeleted(I))
10619         continue;
10620       OpsChanged |= tryToVectorize(I, R);
10621     }
10622     // Try to vectorize list of compares.
10623     // Sort by type, compare predicate, etc.
10624     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10625       return compareCmp<false>(V, V2,
10626                                [&R](Instruction *I) { return R.isDeleted(I); });
10627     };
10628 
10629     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10630       if (V1 == V2)
10631         return true;
10632       return compareCmp<true>(V1, V2,
10633                               [&R](Instruction *I) { return R.isDeleted(I); });
10634     };
10635     auto Limit = [&R](Value *V) {
10636       unsigned EltSize = R.getVectorElementSize(V);
10637       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10638     };
10639 
10640     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10641     OpsChanged |= tryToVectorizeSequence<Value>(
10642         Vals, Limit, CompareSorter, AreCompatibleCompares,
10643         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10644           // Exclude possible reductions from other blocks.
10645           bool ArePossiblyReducedInOtherBlock =
10646               any_of(Candidates, [](Value *V) {
10647                 return any_of(V->users(), [V](User *U) {
10648                   return isa<SelectInst>(U) &&
10649                          cast<SelectInst>(U)->getParent() !=
10650                              cast<Instruction>(V)->getParent();
10651                 });
10652               });
10653           if (ArePossiblyReducedInOtherBlock)
10654             return false;
10655           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10656         },
10657         /*LimitForRegisterSize=*/true);
10658     Instructions.clear();
10659   } else {
10660     // Insert in reverse order since the PostponedCmps vector was filled in
10661     // reverse order.
10662     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10663   }
10664   return OpsChanged;
10665 }
10666 
10667 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10668   bool Changed = false;
10669   SmallVector<Value *, 4> Incoming;
10670   SmallPtrSet<Value *, 16> VisitedInstrs;
10671   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10672   // node. Allows better to identify the chains that can be vectorized in the
10673   // better way.
10674   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10675   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10676     assert(isValidElementType(V1->getType()) &&
10677            isValidElementType(V2->getType()) &&
10678            "Expected vectorizable types only.");
10679     // It is fine to compare type IDs here, since we expect only vectorizable
10680     // types, like ints, floats and pointers, we don't care about other type.
10681     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10682       return true;
10683     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10684       return false;
10685     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10686     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10687     if (Opcodes1.size() < Opcodes2.size())
10688       return true;
10689     if (Opcodes1.size() > Opcodes2.size())
10690       return false;
10691     Optional<bool> ConstOrder;
10692     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10693       // Undefs are compatible with any other value.
10694       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10695         if (!ConstOrder)
10696           ConstOrder =
10697               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10698         continue;
10699       }
10700       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10701         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10702           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10703           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10704           if (!NodeI1)
10705             return NodeI2 != nullptr;
10706           if (!NodeI2)
10707             return false;
10708           assert((NodeI1 == NodeI2) ==
10709                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10710                  "Different nodes should have different DFS numbers");
10711           if (NodeI1 != NodeI2)
10712             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10713           InstructionsState S = getSameOpcode({I1, I2});
10714           if (S.getOpcode())
10715             continue;
10716           return I1->getOpcode() < I2->getOpcode();
10717         }
10718       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10719         if (!ConstOrder)
10720           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10721         continue;
10722       }
10723       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10724         return true;
10725       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10726         return false;
10727     }
10728     return ConstOrder && *ConstOrder;
10729   };
10730   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10731     if (V1 == V2)
10732       return true;
10733     if (V1->getType() != V2->getType())
10734       return false;
10735     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10736     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10737     if (Opcodes1.size() != Opcodes2.size())
10738       return false;
10739     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10740       // Undefs are compatible with any other value.
10741       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10742         continue;
10743       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10744         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10745           if (I1->getParent() != I2->getParent())
10746             return false;
10747           InstructionsState S = getSameOpcode({I1, I2});
10748           if (S.getOpcode())
10749             continue;
10750           return false;
10751         }
10752       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10753         continue;
10754       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10755         return false;
10756     }
10757     return true;
10758   };
10759   auto Limit = [&R](Value *V) {
10760     unsigned EltSize = R.getVectorElementSize(V);
10761     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10762   };
10763 
10764   bool HaveVectorizedPhiNodes = false;
10765   do {
10766     // Collect the incoming values from the PHIs.
10767     Incoming.clear();
10768     for (Instruction &I : *BB) {
10769       PHINode *P = dyn_cast<PHINode>(&I);
10770       if (!P)
10771         break;
10772 
10773       // No need to analyze deleted, vectorized and non-vectorizable
10774       // instructions.
10775       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10776           isValidElementType(P->getType()))
10777         Incoming.push_back(P);
10778     }
10779 
10780     // Find the corresponding non-phi nodes for better matching when trying to
10781     // build the tree.
10782     for (Value *V : Incoming) {
10783       SmallVectorImpl<Value *> &Opcodes =
10784           PHIToOpcodes.try_emplace(V).first->getSecond();
10785       if (!Opcodes.empty())
10786         continue;
10787       SmallVector<Value *, 4> Nodes(1, V);
10788       SmallPtrSet<Value *, 4> Visited;
10789       while (!Nodes.empty()) {
10790         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10791         if (!Visited.insert(PHI).second)
10792           continue;
10793         for (Value *V : PHI->incoming_values()) {
10794           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10795             Nodes.push_back(PHI1);
10796             continue;
10797           }
10798           Opcodes.emplace_back(V);
10799         }
10800       }
10801     }
10802 
10803     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10804         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10805         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10806           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10807         },
10808         /*LimitForRegisterSize=*/true);
10809     Changed |= HaveVectorizedPhiNodes;
10810     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10811   } while (HaveVectorizedPhiNodes);
10812 
10813   VisitedInstrs.clear();
10814 
10815   SmallVector<Instruction *, 8> PostProcessInstructions;
10816   SmallDenseSet<Instruction *, 4> KeyNodes;
10817   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10818     // Skip instructions with scalable type. The num of elements is unknown at
10819     // compile-time for scalable type.
10820     if (isa<ScalableVectorType>(it->getType()))
10821       continue;
10822 
10823     // Skip instructions marked for the deletion.
10824     if (R.isDeleted(&*it))
10825       continue;
10826     // We may go through BB multiple times so skip the one we have checked.
10827     if (!VisitedInstrs.insert(&*it).second) {
10828       if (it->use_empty() && KeyNodes.contains(&*it) &&
10829           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10830                                       it->isTerminator())) {
10831         // We would like to start over since some instructions are deleted
10832         // and the iterator may become invalid value.
10833         Changed = true;
10834         it = BB->begin();
10835         e = BB->end();
10836       }
10837       continue;
10838     }
10839 
10840     if (isa<DbgInfoIntrinsic>(it))
10841       continue;
10842 
10843     // Try to vectorize reductions that use PHINodes.
10844     if (PHINode *P = dyn_cast<PHINode>(it)) {
10845       // Check that the PHI is a reduction PHI.
10846       if (P->getNumIncomingValues() == 2) {
10847         // Try to match and vectorize a horizontal reduction.
10848         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10849                                      TTI)) {
10850           Changed = true;
10851           it = BB->begin();
10852           e = BB->end();
10853           continue;
10854         }
10855       }
10856       // Try to vectorize the incoming values of the PHI, to catch reductions
10857       // that feed into PHIs.
10858       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10859         // Skip if the incoming block is the current BB for now. Also, bypass
10860         // unreachable IR for efficiency and to avoid crashing.
10861         // TODO: Collect the skipped incoming values and try to vectorize them
10862         // after processing BB.
10863         if (BB == P->getIncomingBlock(I) ||
10864             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10865           continue;
10866 
10867         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10868                                             P->getIncomingBlock(I), R, TTI);
10869       }
10870       continue;
10871     }
10872 
10873     // Ran into an instruction without users, like terminator, or function call
10874     // with ignored return value, store. Ignore unused instructions (basing on
10875     // instruction type, except for CallInst and InvokeInst).
10876     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10877                             isa<InvokeInst>(it))) {
10878       KeyNodes.insert(&*it);
10879       bool OpsChanged = false;
10880       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10881         for (auto *V : it->operand_values()) {
10882           // Try to match and vectorize a horizontal reduction.
10883           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10884         }
10885       }
10886       // Start vectorization of post-process list of instructions from the
10887       // top-tree instructions to try to vectorize as many instructions as
10888       // possible.
10889       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10890                                                 it->isTerminator());
10891       if (OpsChanged) {
10892         // We would like to start over since some instructions are deleted
10893         // and the iterator may become invalid value.
10894         Changed = true;
10895         it = BB->begin();
10896         e = BB->end();
10897         continue;
10898       }
10899     }
10900 
10901     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10902         isa<InsertValueInst>(it))
10903       PostProcessInstructions.push_back(&*it);
10904   }
10905 
10906   return Changed;
10907 }
10908 
10909 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10910   auto Changed = false;
10911   for (auto &Entry : GEPs) {
10912     // If the getelementptr list has fewer than two elements, there's nothing
10913     // to do.
10914     if (Entry.second.size() < 2)
10915       continue;
10916 
10917     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10918                       << Entry.second.size() << ".\n");
10919 
10920     // Process the GEP list in chunks suitable for the target's supported
10921     // vector size. If a vector register can't hold 1 element, we are done. We
10922     // are trying to vectorize the index computations, so the maximum number of
10923     // elements is based on the size of the index expression, rather than the
10924     // size of the GEP itself (the target's pointer size).
10925     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10926     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10927     if (MaxVecRegSize < EltSize)
10928       continue;
10929 
10930     unsigned MaxElts = MaxVecRegSize / EltSize;
10931     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10932       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10933       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10934 
10935       // Initialize a set a candidate getelementptrs. Note that we use a
10936       // SetVector here to preserve program order. If the index computations
10937       // are vectorizable and begin with loads, we want to minimize the chance
10938       // of having to reorder them later.
10939       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10940 
10941       // Some of the candidates may have already been vectorized after we
10942       // initially collected them. If so, they are marked as deleted, so remove
10943       // them from the set of candidates.
10944       Candidates.remove_if(
10945           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10946 
10947       // Remove from the set of candidates all pairs of getelementptrs with
10948       // constant differences. Such getelementptrs are likely not good
10949       // candidates for vectorization in a bottom-up phase since one can be
10950       // computed from the other. We also ensure all candidate getelementptr
10951       // indices are unique.
10952       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10953         auto *GEPI = GEPList[I];
10954         if (!Candidates.count(GEPI))
10955           continue;
10956         auto *SCEVI = SE->getSCEV(GEPList[I]);
10957         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10958           auto *GEPJ = GEPList[J];
10959           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10960           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10961             Candidates.remove(GEPI);
10962             Candidates.remove(GEPJ);
10963           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10964             Candidates.remove(GEPJ);
10965           }
10966         }
10967       }
10968 
10969       // We break out of the above computation as soon as we know there are
10970       // fewer than two candidates remaining.
10971       if (Candidates.size() < 2)
10972         continue;
10973 
10974       // Add the single, non-constant index of each candidate to the bundle. We
10975       // ensured the indices met these constraints when we originally collected
10976       // the getelementptrs.
10977       SmallVector<Value *, 16> Bundle(Candidates.size());
10978       auto BundleIndex = 0u;
10979       for (auto *V : Candidates) {
10980         auto *GEP = cast<GetElementPtrInst>(V);
10981         auto *GEPIdx = GEP->idx_begin()->get();
10982         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10983         Bundle[BundleIndex++] = GEPIdx;
10984       }
10985 
10986       // Try and vectorize the indices. We are currently only interested in
10987       // gather-like cases of the form:
10988       //
10989       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10990       //
10991       // where the loads of "a", the loads of "b", and the subtractions can be
10992       // performed in parallel. It's likely that detecting this pattern in a
10993       // bottom-up phase will be simpler and less costly than building a
10994       // full-blown top-down phase beginning at the consecutive loads.
10995       Changed |= tryToVectorizeList(Bundle, R);
10996     }
10997   }
10998   return Changed;
10999 }
11000 
11001 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11002   bool Changed = false;
11003   // Sort by type, base pointers and values operand. Value operands must be
11004   // compatible (have the same opcode, same parent), otherwise it is
11005   // definitely not profitable to try to vectorize them.
11006   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11007     if (V->getPointerOperandType()->getTypeID() <
11008         V2->getPointerOperandType()->getTypeID())
11009       return true;
11010     if (V->getPointerOperandType()->getTypeID() >
11011         V2->getPointerOperandType()->getTypeID())
11012       return false;
11013     // UndefValues are compatible with all other values.
11014     if (isa<UndefValue>(V->getValueOperand()) ||
11015         isa<UndefValue>(V2->getValueOperand()))
11016       return false;
11017     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11018       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11019         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11020             DT->getNode(I1->getParent());
11021         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11022             DT->getNode(I2->getParent());
11023         assert(NodeI1 && "Should only process reachable instructions");
11024         assert(NodeI1 && "Should only process reachable instructions");
11025         assert((NodeI1 == NodeI2) ==
11026                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11027                "Different nodes should have different DFS numbers");
11028         if (NodeI1 != NodeI2)
11029           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11030         InstructionsState S = getSameOpcode({I1, I2});
11031         if (S.getOpcode())
11032           return false;
11033         return I1->getOpcode() < I2->getOpcode();
11034       }
11035     if (isa<Constant>(V->getValueOperand()) &&
11036         isa<Constant>(V2->getValueOperand()))
11037       return false;
11038     return V->getValueOperand()->getValueID() <
11039            V2->getValueOperand()->getValueID();
11040   };
11041 
11042   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11043     if (V1 == V2)
11044       return true;
11045     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11046       return false;
11047     // Undefs are compatible with any other value.
11048     if (isa<UndefValue>(V1->getValueOperand()) ||
11049         isa<UndefValue>(V2->getValueOperand()))
11050       return true;
11051     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11052       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11053         if (I1->getParent() != I2->getParent())
11054           return false;
11055         InstructionsState S = getSameOpcode({I1, I2});
11056         return S.getOpcode() > 0;
11057       }
11058     if (isa<Constant>(V1->getValueOperand()) &&
11059         isa<Constant>(V2->getValueOperand()))
11060       return true;
11061     return V1->getValueOperand()->getValueID() ==
11062            V2->getValueOperand()->getValueID();
11063   };
11064   auto Limit = [&R, this](StoreInst *SI) {
11065     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11066     return R.getMinVF(EltSize);
11067   };
11068 
11069   // Attempt to sort and vectorize each of the store-groups.
11070   for (auto &Pair : Stores) {
11071     if (Pair.second.size() < 2)
11072       continue;
11073 
11074     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11075                       << Pair.second.size() << ".\n");
11076 
11077     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11078       continue;
11079 
11080     Changed |= tryToVectorizeSequence<StoreInst>(
11081         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11082         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11083           return vectorizeStores(Candidates, R);
11084         },
11085         /*LimitForRegisterSize=*/false);
11086   }
11087   return Changed;
11088 }
11089 
11090 char SLPVectorizer::ID = 0;
11091 
11092 static const char lv_name[] = "SLP Vectorizer";
11093 
11094 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11095 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11096 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11097 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11098 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11099 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11100 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11101 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11102 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11103 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11104 
11105 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11106