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