1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/Operator.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #ifdef EXPENSIVE_CHECKS
75 #include "llvm/IR/Verifier.h"
76 #endif
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/Local.h"
91 #include "llvm/Transforms/Utils/LoopUtils.h"
92 #include "llvm/Transforms/Vectorize.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <memory>
98 #include <set>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 #include <vector>
103 
104 using namespace llvm;
105 using namespace llvm::PatternMatch;
106 using namespace slpvectorizer;
107 
108 #define SV_NAME "slp-vectorizer"
109 #define DEBUG_TYPE "SLP"
110 
111 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
112 
113 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
114                                   cl::desc("Run the SLP vectorization passes"));
115 
116 static cl::opt<int>
117     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
118                      cl::desc("Only vectorize if you gain more than this "
119                               "number "));
120 
121 static cl::opt<bool>
122 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
123                    cl::desc("Attempt to vectorize horizontal reductions"));
124 
125 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
126     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
127     cl::desc(
128         "Attempt to vectorize horizontal reductions feeding into a store"));
129 
130 static cl::opt<int>
131 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
132     cl::desc("Attempt to vectorize for this register size in bits"));
133 
134 static cl::opt<unsigned>
135 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
136     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
137 
138 static cl::opt<int>
139 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
140     cl::desc("Maximum depth of the lookup for consecutive stores."));
141 
142 /// Limits the size of scheduling regions in a block.
143 /// It avoid long compile times for _very_ large blocks where vector
144 /// instructions are spread over a wide range.
145 /// This limit is way higher than needed by real-world functions.
146 static cl::opt<int>
147 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
148     cl::desc("Limit the size of the SLP scheduling region per block"));
149 
150 static cl::opt<int> MinVectorRegSizeOption(
151     "slp-min-reg-size", cl::init(128), cl::Hidden,
152     cl::desc("Attempt to vectorize for this register size in bits"));
153 
154 static cl::opt<unsigned> RecursionMaxDepth(
155     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
156     cl::desc("Limit the recursion depth when building a vectorizable tree"));
157 
158 static cl::opt<unsigned> MinTreeSize(
159     "slp-min-tree-size", cl::init(3), cl::Hidden,
160     cl::desc("Only vectorize small trees if they are fully vectorizable"));
161 
162 // The maximum depth that the look-ahead score heuristic will explore.
163 // The higher this value, the higher the compilation time overhead.
164 static cl::opt<int> LookAheadMaxDepth(
165     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
166     cl::desc("The maximum look-ahead depth for operand reordering scores"));
167 
168 static cl::opt<bool>
169     ViewSLPTree("view-slp-tree", cl::Hidden,
170                 cl::desc("Display the SLP trees with Graphviz"));
171 
172 // Limit the number of alias checks. The limit is chosen so that
173 // it has no negative effect on the llvm benchmarks.
174 static const unsigned AliasedCheckLimit = 10;
175 
176 // Another limit for the alias checks: The maximum distance between load/store
177 // instructions where alias checks are done.
178 // This limit is useful for very large basic blocks.
179 static const unsigned MaxMemDepDistance = 160;
180 
181 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
182 /// regions to be handled.
183 static const int MinScheduleRegionSize = 16;
184 
185 /// Predicate for the element types that the SLP vectorizer supports.
186 ///
187 /// The most important thing to filter here are types which are invalid in LLVM
188 /// vectors. We also filter target specific types which have absolutely no
189 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
190 /// avoids spending time checking the cost model and realizing that they will
191 /// be inevitably scalarized.
192 static bool isValidElementType(Type *Ty) {
193   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
194          !Ty->isPPC_FP128Ty();
195 }
196 
197 /// \returns True if the value is a constant (but not globals/constant
198 /// expressions).
199 static bool isConstant(Value *V) {
200   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
201 }
202 
203 /// Checks if \p V is one of vector-like instructions, i.e. undef,
204 /// insertelement/extractelement with constant indices for fixed vector type or
205 /// extractvalue instruction.
206 static bool isVectorLikeInstWithConstOps(Value *V) {
207   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
208       !isa<ExtractValueInst, UndefValue>(V))
209     return false;
210   auto *I = dyn_cast<Instruction>(V);
211   if (!I || isa<ExtractValueInst>(I))
212     return true;
213   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
214     return false;
215   if (isa<ExtractElementInst>(I))
216     return isConstant(I->getOperand(1));
217   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
218   return isConstant(I->getOperand(2));
219 }
220 
221 /// \returns true if all of the instructions in \p VL are in the same block or
222 /// false otherwise.
223 static bool allSameBlock(ArrayRef<Value *> VL) {
224   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
225   if (!I0)
226     return false;
227   if (all_of(VL, isVectorLikeInstWithConstOps))
228     return true;
229 
230   BasicBlock *BB = I0->getParent();
231   for (int I = 1, E = VL.size(); I < E; I++) {
232     auto *II = dyn_cast<Instruction>(VL[I]);
233     if (!II)
234       return false;
235 
236     if (BB != II->getParent())
237       return false;
238   }
239   return true;
240 }
241 
242 /// \returns True if all of the values in \p VL are constants (but not
243 /// globals/constant expressions).
244 static bool allConstant(ArrayRef<Value *> VL) {
245   // Constant expressions and globals can't be vectorized like normal integer/FP
246   // constants.
247   return all_of(VL, isConstant);
248 }
249 
250 /// \returns True if all of the values in \p VL are identical or some of them
251 /// are UndefValue.
252 static bool isSplat(ArrayRef<Value *> VL) {
253   Value *FirstNonUndef = nullptr;
254   for (Value *V : VL) {
255     if (isa<UndefValue>(V))
256       continue;
257     if (!FirstNonUndef) {
258       FirstNonUndef = V;
259       continue;
260     }
261     if (V != FirstNonUndef)
262       return false;
263   }
264   return FirstNonUndef != nullptr;
265 }
266 
267 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
268 static bool isCommutative(Instruction *I) {
269   if (auto *Cmp = dyn_cast<CmpInst>(I))
270     return Cmp->isCommutative();
271   if (auto *BO = dyn_cast<BinaryOperator>(I))
272     return BO->isCommutative();
273   // TODO: This should check for generic Instruction::isCommutative(), but
274   //       we need to confirm that the caller code correctly handles Intrinsics
275   //       for example (does not have 2 operands).
276   return false;
277 }
278 
279 /// Checks if the given value is actually an undefined constant vector.
280 static bool isUndefVector(const Value *V) {
281   if (isa<UndefValue>(V))
282     return true;
283   auto *C = dyn_cast<Constant>(V);
284   if (!C)
285     return false;
286   if (!C->containsUndefOrPoisonElement())
287     return false;
288   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
289   if (!VecTy)
290     return false;
291   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
292     if (Constant *Elem = C->getAggregateElement(I))
293       if (!isa<UndefValue>(Elem))
294         return false;
295   }
296   return true;
297 }
298 
299 /// Checks if the vector of instructions can be represented as a shuffle, like:
300 /// %x0 = extractelement <4 x i8> %x, i32 0
301 /// %x3 = extractelement <4 x i8> %x, i32 3
302 /// %y1 = extractelement <4 x i8> %y, i32 1
303 /// %y2 = extractelement <4 x i8> %y, i32 2
304 /// %x0x0 = mul i8 %x0, %x0
305 /// %x3x3 = mul i8 %x3, %x3
306 /// %y1y1 = mul i8 %y1, %y1
307 /// %y2y2 = mul i8 %y2, %y2
308 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
309 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
310 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
311 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
312 /// ret <4 x i8> %ins4
313 /// can be transformed into:
314 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
315 ///                                                         i32 6>
316 /// %2 = mul <4 x i8> %1, %1
317 /// ret <4 x i8> %2
318 /// We convert this initially to something like:
319 /// %x0 = extractelement <4 x i8> %x, i32 0
320 /// %x3 = extractelement <4 x i8> %x, i32 3
321 /// %y1 = extractelement <4 x i8> %y, i32 1
322 /// %y2 = extractelement <4 x i8> %y, i32 2
323 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
324 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
325 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
326 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
327 /// %5 = mul <4 x i8> %4, %4
328 /// %6 = extractelement <4 x i8> %5, i32 0
329 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
330 /// %7 = extractelement <4 x i8> %5, i32 1
331 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
332 /// %8 = extractelement <4 x i8> %5, i32 2
333 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
334 /// %9 = extractelement <4 x i8> %5, i32 3
335 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
336 /// ret <4 x i8> %ins4
337 /// InstCombiner transforms this into a shuffle and vector mul
338 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
339 /// TODO: Can we split off and reuse the shuffle mask detection from
340 /// TargetTransformInfo::getInstructionThroughput?
341 static Optional<TargetTransformInfo::ShuffleKind>
342 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
343   const auto *It =
344       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
345   if (It == VL.end())
346     return None;
347   auto *EI0 = cast<ExtractElementInst>(*It);
348   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
349     return None;
350   unsigned Size =
351       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
352   Value *Vec1 = nullptr;
353   Value *Vec2 = nullptr;
354   enum ShuffleMode { Unknown, Select, Permute };
355   ShuffleMode CommonShuffleMode = Unknown;
356   Mask.assign(VL.size(), UndefMaskElem);
357   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
358     // Undef can be represented as an undef element in a vector.
359     if (isa<UndefValue>(VL[I]))
360       continue;
361     auto *EI = cast<ExtractElementInst>(VL[I]);
362     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
363       return None;
364     auto *Vec = EI->getVectorOperand();
365     // We can extractelement from undef or poison vector.
366     if (isUndefVector(Vec))
367       continue;
368     // All vector operands must have the same number of vector elements.
369     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
370       return None;
371     if (isa<UndefValue>(EI->getIndexOperand()))
372       continue;
373     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
374     if (!Idx)
375       return None;
376     // Undefined behavior if Idx is negative or >= Size.
377     if (Idx->getValue().uge(Size))
378       continue;
379     unsigned IntIdx = Idx->getValue().getZExtValue();
380     Mask[I] = IntIdx;
381     // For correct shuffling we have to have at most 2 different vector operands
382     // in all extractelement instructions.
383     if (!Vec1 || Vec1 == Vec) {
384       Vec1 = Vec;
385     } else if (!Vec2 || Vec2 == Vec) {
386       Vec2 = Vec;
387       Mask[I] += Size;
388     } else {
389       return None;
390     }
391     if (CommonShuffleMode == Permute)
392       continue;
393     // If the extract index is not the same as the operation number, it is a
394     // permutation.
395     if (IntIdx != I) {
396       CommonShuffleMode = Permute;
397       continue;
398     }
399     CommonShuffleMode = Select;
400   }
401   // If we're not crossing lanes in different vectors, consider it as blending.
402   if (CommonShuffleMode == Select && Vec2)
403     return TargetTransformInfo::SK_Select;
404   // If Vec2 was never used, we have a permutation of a single vector, otherwise
405   // we have permutation of 2 vectors.
406   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
407               : TargetTransformInfo::SK_PermuteSingleSrc;
408 }
409 
410 namespace {
411 
412 /// Main data required for vectorization of instructions.
413 struct InstructionsState {
414   /// The very first instruction in the list with the main opcode.
415   Value *OpValue = nullptr;
416 
417   /// The main/alternate instruction.
418   Instruction *MainOp = nullptr;
419   Instruction *AltOp = nullptr;
420 
421   /// The main/alternate opcodes for the list of instructions.
422   unsigned getOpcode() const {
423     return MainOp ? MainOp->getOpcode() : 0;
424   }
425 
426   unsigned getAltOpcode() const {
427     return AltOp ? AltOp->getOpcode() : 0;
428   }
429 
430   /// Some of the instructions in the list have alternate opcodes.
431   bool isAltShuffle() const { return AltOp != MainOp; }
432 
433   bool isOpcodeOrAlt(Instruction *I) const {
434     unsigned CheckedOpcode = I->getOpcode();
435     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
436   }
437 
438   InstructionsState() = delete;
439   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
440       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
441 };
442 
443 } // end anonymous namespace
444 
445 /// Chooses the correct key for scheduling data. If \p Op has the same (or
446 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
447 /// OpValue.
448 static Value *isOneOf(const InstructionsState &S, Value *Op) {
449   auto *I = dyn_cast<Instruction>(Op);
450   if (I && S.isOpcodeOrAlt(I))
451     return Op;
452   return S.OpValue;
453 }
454 
455 /// \returns true if \p Opcode is allowed as part of of the main/alternate
456 /// instruction for SLP vectorization.
457 ///
458 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
459 /// "shuffled out" lane would result in division by zero.
460 static bool isValidForAlternation(unsigned Opcode) {
461   if (Instruction::isIntDivRem(Opcode))
462     return false;
463 
464   return true;
465 }
466 
467 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
468                                        unsigned BaseIndex = 0);
469 
470 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
471 /// compatible instructions or constants, or just some other regular values.
472 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
473                                 Value *Op1) {
474   return (isConstant(BaseOp0) && isConstant(Op0)) ||
475          (isConstant(BaseOp1) && isConstant(Op1)) ||
476          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
477           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
478          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
479          getSameOpcode({BaseOp1, Op1}).getOpcode();
480 }
481 
482 /// \returns analysis of the Instructions in \p VL described in
483 /// InstructionsState, the Opcode that we suppose the whole list
484 /// could be vectorized even if its structure is diverse.
485 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
486                                        unsigned BaseIndex) {
487   // Make sure these are all Instructions.
488   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
489     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
490 
491   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
492   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
493   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
494   CmpInst::Predicate BasePred =
495       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
496               : CmpInst::BAD_ICMP_PREDICATE;
497   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
498   unsigned AltOpcode = Opcode;
499   unsigned AltIndex = BaseIndex;
500 
501   // Check for one alternate opcode from another BinaryOperator.
502   // TODO - generalize to support all operators (types, calls etc.).
503   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
504     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
505     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
506       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
507         continue;
508       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
509           isValidForAlternation(Opcode)) {
510         AltOpcode = InstOpcode;
511         AltIndex = Cnt;
512         continue;
513       }
514     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
515       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
516       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
517       if (Ty0 == Ty1) {
518         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
519           continue;
520         if (Opcode == AltOpcode) {
521           assert(isValidForAlternation(Opcode) &&
522                  isValidForAlternation(InstOpcode) &&
523                  "Cast isn't safe for alternation, logic needs to be updated!");
524           AltOpcode = InstOpcode;
525           AltIndex = Cnt;
526           continue;
527         }
528       }
529     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
530       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
531       auto *Inst = cast<Instruction>(VL[Cnt]);
532       Type *Ty0 = BaseInst->getOperand(0)->getType();
533       Type *Ty1 = Inst->getOperand(0)->getType();
534       if (Ty0 == Ty1) {
535         Value *BaseOp0 = BaseInst->getOperand(0);
536         Value *BaseOp1 = BaseInst->getOperand(1);
537         Value *Op0 = Inst->getOperand(0);
538         Value *Op1 = Inst->getOperand(1);
539         CmpInst::Predicate CurrentPred =
540             cast<CmpInst>(VL[Cnt])->getPredicate();
541         CmpInst::Predicate SwappedCurrentPred =
542             CmpInst::getSwappedPredicate(CurrentPred);
543         // Check for compatible operands. If the corresponding operands are not
544         // compatible - need to perform alternate vectorization.
545         if (InstOpcode == Opcode) {
546           if (BasePred == CurrentPred &&
547               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
548             continue;
549           if (BasePred == SwappedCurrentPred &&
550               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
551             continue;
552           if (E == 2 &&
553               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
554             continue;
555           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
556           CmpInst::Predicate AltPred = AltInst->getPredicate();
557           Value *AltOp0 = AltInst->getOperand(0);
558           Value *AltOp1 = AltInst->getOperand(1);
559           // Check if operands are compatible with alternate operands.
560           if (AltPred == CurrentPred &&
561               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
562             continue;
563           if (AltPred == SwappedCurrentPred &&
564               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
565             continue;
566         }
567         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
568           assert(isValidForAlternation(Opcode) &&
569                  isValidForAlternation(InstOpcode) &&
570                  "Cast isn't safe for alternation, logic needs to be updated!");
571           AltIndex = Cnt;
572           continue;
573         }
574         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
575         CmpInst::Predicate AltPred = AltInst->getPredicate();
576         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
577             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
578           continue;
579       }
580     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
581       continue;
582     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
583   }
584 
585   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
586                            cast<Instruction>(VL[AltIndex]));
587 }
588 
589 /// \returns true if all of the values in \p VL have the same type or false
590 /// otherwise.
591 static bool allSameType(ArrayRef<Value *> VL) {
592   Type *Ty = VL[0]->getType();
593   for (int i = 1, e = VL.size(); i < e; i++)
594     if (VL[i]->getType() != Ty)
595       return false;
596 
597   return true;
598 }
599 
600 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
601 static Optional<unsigned> getExtractIndex(Instruction *E) {
602   unsigned Opcode = E->getOpcode();
603   assert((Opcode == Instruction::ExtractElement ||
604           Opcode == Instruction::ExtractValue) &&
605          "Expected extractelement or extractvalue instruction.");
606   if (Opcode == Instruction::ExtractElement) {
607     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
608     if (!CI)
609       return None;
610     return CI->getZExtValue();
611   }
612   ExtractValueInst *EI = cast<ExtractValueInst>(E);
613   if (EI->getNumIndices() != 1)
614     return None;
615   return *EI->idx_begin();
616 }
617 
618 /// \returns True if in-tree use also needs extract. This refers to
619 /// possible scalar operand in vectorized instruction.
620 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
621                                     TargetLibraryInfo *TLI) {
622   unsigned Opcode = UserInst->getOpcode();
623   switch (Opcode) {
624   case Instruction::Load: {
625     LoadInst *LI = cast<LoadInst>(UserInst);
626     return (LI->getPointerOperand() == Scalar);
627   }
628   case Instruction::Store: {
629     StoreInst *SI = cast<StoreInst>(UserInst);
630     return (SI->getPointerOperand() == Scalar);
631   }
632   case Instruction::Call: {
633     CallInst *CI = cast<CallInst>(UserInst);
634     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
635     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
636       if (hasVectorInstrinsicScalarOpd(ID, i))
637         return (CI->getArgOperand(i) == Scalar);
638     }
639     LLVM_FALLTHROUGH;
640   }
641   default:
642     return false;
643   }
644 }
645 
646 /// \returns the AA location that is being access by the instruction.
647 static MemoryLocation getLocation(Instruction *I) {
648   if (StoreInst *SI = dyn_cast<StoreInst>(I))
649     return MemoryLocation::get(SI);
650   if (LoadInst *LI = dyn_cast<LoadInst>(I))
651     return MemoryLocation::get(LI);
652   return MemoryLocation();
653 }
654 
655 /// \returns True if the instruction is not a volatile or atomic load/store.
656 static bool isSimple(Instruction *I) {
657   if (LoadInst *LI = dyn_cast<LoadInst>(I))
658     return LI->isSimple();
659   if (StoreInst *SI = dyn_cast<StoreInst>(I))
660     return SI->isSimple();
661   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
662     return !MI->isVolatile();
663   return true;
664 }
665 
666 /// Shuffles \p Mask in accordance with the given \p SubMask.
667 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
668   if (SubMask.empty())
669     return;
670   if (Mask.empty()) {
671     Mask.append(SubMask.begin(), SubMask.end());
672     return;
673   }
674   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
675   int TermValue = std::min(Mask.size(), SubMask.size());
676   for (int I = 0, E = SubMask.size(); I < E; ++I) {
677     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
678         Mask[SubMask[I]] >= TermValue)
679       continue;
680     NewMask[I] = Mask[SubMask[I]];
681   }
682   Mask.swap(NewMask);
683 }
684 
685 /// Order may have elements assigned special value (size) which is out of
686 /// bounds. Such indices only appear on places which correspond to undef values
687 /// (see canReuseExtract for details) and used in order to avoid undef values
688 /// have effect on operands ordering.
689 /// The first loop below simply finds all unused indices and then the next loop
690 /// nest assigns these indices for undef values positions.
691 /// As an example below Order has two undef positions and they have assigned
692 /// values 3 and 7 respectively:
693 /// before:  6 9 5 4 9 2 1 0
694 /// after:   6 3 5 4 7 2 1 0
695 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
696   const unsigned Sz = Order.size();
697   SmallBitVector UnusedIndices(Sz, /*t=*/true);
698   SmallBitVector MaskedIndices(Sz);
699   for (unsigned I = 0; I < Sz; ++I) {
700     if (Order[I] < Sz)
701       UnusedIndices.reset(Order[I]);
702     else
703       MaskedIndices.set(I);
704   }
705   if (MaskedIndices.none())
706     return;
707   assert(UnusedIndices.count() == MaskedIndices.count() &&
708          "Non-synced masked/available indices.");
709   int Idx = UnusedIndices.find_first();
710   int MIdx = MaskedIndices.find_first();
711   while (MIdx >= 0) {
712     assert(Idx >= 0 && "Indices must be synced.");
713     Order[MIdx] = Idx;
714     Idx = UnusedIndices.find_next(Idx);
715     MIdx = MaskedIndices.find_next(MIdx);
716   }
717 }
718 
719 namespace llvm {
720 
721 static void inversePermutation(ArrayRef<unsigned> Indices,
722                                SmallVectorImpl<int> &Mask) {
723   Mask.clear();
724   const unsigned E = Indices.size();
725   Mask.resize(E, UndefMaskElem);
726   for (unsigned I = 0; I < E; ++I)
727     Mask[Indices[I]] = I;
728 }
729 
730 /// \returns inserting index of InsertElement or InsertValue instruction,
731 /// using Offset as base offset for index.
732 static Optional<unsigned> getInsertIndex(Value *InsertInst,
733                                          unsigned Offset = 0) {
734   int Index = Offset;
735   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
736     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
737       auto *VT = cast<FixedVectorType>(IE->getType());
738       if (CI->getValue().uge(VT->getNumElements()))
739         return None;
740       Index *= VT->getNumElements();
741       Index += CI->getZExtValue();
742       return Index;
743     }
744     return None;
745   }
746 
747   auto *IV = cast<InsertValueInst>(InsertInst);
748   Type *CurrentType = IV->getType();
749   for (unsigned I : IV->indices()) {
750     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
751       Index *= ST->getNumElements();
752       CurrentType = ST->getElementType(I);
753     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
754       Index *= AT->getNumElements();
755       CurrentType = AT->getElementType();
756     } else {
757       return None;
758     }
759     Index += I;
760   }
761   return Index;
762 }
763 
764 /// Reorders the list of scalars in accordance with the given \p Mask.
765 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
766                            ArrayRef<int> Mask) {
767   assert(!Mask.empty() && "Expected non-empty mask.");
768   SmallVector<Value *> Prev(Scalars.size(),
769                             UndefValue::get(Scalars.front()->getType()));
770   Prev.swap(Scalars);
771   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
772     if (Mask[I] != UndefMaskElem)
773       Scalars[Mask[I]] = Prev[I];
774 }
775 
776 /// Checks if the provided value does not require scheduling. It does not
777 /// require scheduling if this is not an instruction or it is an instruction
778 /// that does not read/write memory and all operands are either not instructions
779 /// or phi nodes or instructions from different blocks.
780 static bool areAllOperandsNonInsts(Value *V) {
781   auto *I = dyn_cast<Instruction>(V);
782   if (!I)
783     return true;
784   return !mayHaveNonDefUseDependency(*I) &&
785     all_of(I->operands(), [I](Value *V) {
786       auto *IO = dyn_cast<Instruction>(V);
787       if (!IO)
788         return true;
789       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
790     });
791 }
792 
793 /// Checks if the provided value does not require scheduling. It does not
794 /// require scheduling if this is not an instruction or it is an instruction
795 /// that does not read/write memory and all users are phi nodes or instructions
796 /// from the different blocks.
797 static bool isUsedOutsideBlock(Value *V) {
798   auto *I = dyn_cast<Instruction>(V);
799   if (!I)
800     return true;
801   // Limits the number of uses to save compile time.
802   constexpr int UsesLimit = 8;
803   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
804          all_of(I->users(), [I](User *U) {
805            auto *IU = dyn_cast<Instruction>(U);
806            if (!IU)
807              return true;
808            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
809          });
810 }
811 
812 /// Checks if the specified value does not require scheduling. It does not
813 /// require scheduling if all operands and all users do not need to be scheduled
814 /// in the current basic block.
815 static bool doesNotNeedToBeScheduled(Value *V) {
816   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
817 }
818 
819 /// Checks if the specified array of instructions does not require scheduling.
820 /// It is so if all either instructions have operands that do not require
821 /// scheduling or their users do not require scheduling since they are phis or
822 /// in other basic blocks.
823 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
824   return !VL.empty() &&
825          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
826 }
827 
828 namespace slpvectorizer {
829 
830 /// Bottom Up SLP Vectorizer.
831 class BoUpSLP {
832   struct TreeEntry;
833   struct ScheduleData;
834 
835 public:
836   using ValueList = SmallVector<Value *, 8>;
837   using InstrList = SmallVector<Instruction *, 16>;
838   using ValueSet = SmallPtrSet<Value *, 16>;
839   using StoreList = SmallVector<StoreInst *, 8>;
840   using ExtraValueToDebugLocsMap =
841       MapVector<Value *, SmallVector<Instruction *, 2>>;
842   using OrdersType = SmallVector<unsigned, 4>;
843 
844   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
845           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
846           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
847           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
848       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
849         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
850     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
851     // Use the vector register size specified by the target unless overridden
852     // by a command-line option.
853     // TODO: It would be better to limit the vectorization factor based on
854     //       data type rather than just register size. For example, x86 AVX has
855     //       256-bit registers, but it does not support integer operations
856     //       at that width (that requires AVX2).
857     if (MaxVectorRegSizeOption.getNumOccurrences())
858       MaxVecRegSize = MaxVectorRegSizeOption;
859     else
860       MaxVecRegSize =
861           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
862               .getFixedSize();
863 
864     if (MinVectorRegSizeOption.getNumOccurrences())
865       MinVecRegSize = MinVectorRegSizeOption;
866     else
867       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
868   }
869 
870   /// Vectorize the tree that starts with the elements in \p VL.
871   /// Returns the vectorized root.
872   Value *vectorizeTree();
873 
874   /// Vectorize the tree but with the list of externally used values \p
875   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
876   /// generated extractvalue instructions.
877   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
878 
879   /// \returns the cost incurred by unwanted spills and fills, caused by
880   /// holding live values over call sites.
881   InstructionCost getSpillCost() const;
882 
883   /// \returns the vectorization cost of the subtree that starts at \p VL.
884   /// A negative number means that this is profitable.
885   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
886 
887   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
888   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
889   void buildTree(ArrayRef<Value *> Roots,
890                  ArrayRef<Value *> UserIgnoreLst = None);
891 
892   /// Builds external uses of the vectorized scalars, i.e. the list of
893   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
894   /// ExternallyUsedValues contains additional list of external uses to handle
895   /// vectorization of reductions.
896   void
897   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
898 
899   /// Clear the internal data structures that are created by 'buildTree'.
900   void deleteTree() {
901     VectorizableTree.clear();
902     ScalarToTreeEntry.clear();
903     MustGather.clear();
904     ExternalUses.clear();
905     for (auto &Iter : BlocksSchedules) {
906       BlockScheduling *BS = Iter.second.get();
907       BS->clear();
908     }
909     MinBWs.clear();
910     InstrElementSize.clear();
911   }
912 
913   unsigned getTreeSize() const { return VectorizableTree.size(); }
914 
915   /// Perform LICM and CSE on the newly generated gather sequences.
916   void optimizeGatherSequence();
917 
918   /// Checks if the specified gather tree entry \p TE can be represented as a
919   /// shuffled vector entry + (possibly) permutation with other gathers. It
920   /// implements the checks only for possibly ordered scalars (Loads,
921   /// ExtractElement, ExtractValue), which can be part of the graph.
922   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
923 
924   /// Gets reordering data for the given tree entry. If the entry is vectorized
925   /// - just return ReorderIndices, otherwise check if the scalars can be
926   /// reordered and return the most optimal order.
927   /// \param TopToBottom If true, include the order of vectorized stores and
928   /// insertelement nodes, otherwise skip them.
929   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
930 
931   /// Reorders the current graph to the most profitable order starting from the
932   /// root node to the leaf nodes. The best order is chosen only from the nodes
933   /// of the same size (vectorization factor). Smaller nodes are considered
934   /// parts of subgraph with smaller VF and they are reordered independently. We
935   /// can make it because we still need to extend smaller nodes to the wider VF
936   /// and we can merge reordering shuffles with the widening shuffles.
937   void reorderTopToBottom();
938 
939   /// Reorders the current graph to the most profitable order starting from
940   /// leaves to the root. It allows to rotate small subgraphs and reduce the
941   /// number of reshuffles if the leaf nodes use the same order. In this case we
942   /// can merge the orders and just shuffle user node instead of shuffling its
943   /// operands. Plus, even the leaf nodes have different orders, it allows to
944   /// sink reordering in the graph closer to the root node and merge it later
945   /// during analysis.
946   void reorderBottomToTop(bool IgnoreReorder = false);
947 
948   /// \return The vector element size in bits to use when vectorizing the
949   /// expression tree ending at \p V. If V is a store, the size is the width of
950   /// the stored value. Otherwise, the size is the width of the largest loaded
951   /// value reaching V. This method is used by the vectorizer to calculate
952   /// vectorization factors.
953   unsigned getVectorElementSize(Value *V);
954 
955   /// Compute the minimum type sizes required to represent the entries in a
956   /// vectorizable tree.
957   void computeMinimumValueSizes();
958 
959   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
960   unsigned getMaxVecRegSize() const {
961     return MaxVecRegSize;
962   }
963 
964   // \returns minimum vector register size as set by cl::opt.
965   unsigned getMinVecRegSize() const {
966     return MinVecRegSize;
967   }
968 
969   unsigned getMinVF(unsigned Sz) const {
970     return std::max(2U, getMinVecRegSize() / Sz);
971   }
972 
973   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
974     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
975       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
976     return MaxVF ? MaxVF : UINT_MAX;
977   }
978 
979   /// Check if homogeneous aggregate is isomorphic to some VectorType.
980   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
981   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
982   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
983   ///
984   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
985   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
986 
987   /// \returns True if the VectorizableTree is both tiny and not fully
988   /// vectorizable. We do not vectorize such trees.
989   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
990 
991   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
992   /// can be load combined in the backend. Load combining may not be allowed in
993   /// the IR optimizer, so we do not want to alter the pattern. For example,
994   /// partially transforming a scalar bswap() pattern into vector code is
995   /// effectively impossible for the backend to undo.
996   /// TODO: If load combining is allowed in the IR optimizer, this analysis
997   ///       may not be necessary.
998   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
999 
1000   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1001   /// can be load combined in the backend. Load combining may not be allowed in
1002   /// the IR optimizer, so we do not want to alter the pattern. For example,
1003   /// partially transforming a scalar bswap() pattern into vector code is
1004   /// effectively impossible for the backend to undo.
1005   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1006   ///       may not be necessary.
1007   bool isLoadCombineCandidate() const;
1008 
1009   OptimizationRemarkEmitter *getORE() { return ORE; }
1010 
1011   /// This structure holds any data we need about the edges being traversed
1012   /// during buildTree_rec(). We keep track of:
1013   /// (i) the user TreeEntry index, and
1014   /// (ii) the index of the edge.
1015   struct EdgeInfo {
1016     EdgeInfo() = default;
1017     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1018         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1019     /// The user TreeEntry.
1020     TreeEntry *UserTE = nullptr;
1021     /// The operand index of the use.
1022     unsigned EdgeIdx = UINT_MAX;
1023 #ifndef NDEBUG
1024     friend inline raw_ostream &operator<<(raw_ostream &OS,
1025                                           const BoUpSLP::EdgeInfo &EI) {
1026       EI.dump(OS);
1027       return OS;
1028     }
1029     /// Debug print.
1030     void dump(raw_ostream &OS) const {
1031       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1032          << " EdgeIdx:" << EdgeIdx << "}";
1033     }
1034     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1035 #endif
1036   };
1037 
1038   /// A helper data structure to hold the operands of a vector of instructions.
1039   /// This supports a fixed vector length for all operand vectors.
1040   class VLOperands {
1041     /// For each operand we need (i) the value, and (ii) the opcode that it
1042     /// would be attached to if the expression was in a left-linearized form.
1043     /// This is required to avoid illegal operand reordering.
1044     /// For example:
1045     /// \verbatim
1046     ///                         0 Op1
1047     ///                         |/
1048     /// Op1 Op2   Linearized    + Op2
1049     ///   \ /     ---------->   |/
1050     ///    -                    -
1051     ///
1052     /// Op1 - Op2            (0 + Op1) - Op2
1053     /// \endverbatim
1054     ///
1055     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1056     ///
1057     /// Another way to think of this is to track all the operations across the
1058     /// path from the operand all the way to the root of the tree and to
1059     /// calculate the operation that corresponds to this path. For example, the
1060     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1061     /// corresponding operation is a '-' (which matches the one in the
1062     /// linearized tree, as shown above).
1063     ///
1064     /// For lack of a better term, we refer to this operation as Accumulated
1065     /// Path Operation (APO).
1066     struct OperandData {
1067       OperandData() = default;
1068       OperandData(Value *V, bool APO, bool IsUsed)
1069           : V(V), APO(APO), IsUsed(IsUsed) {}
1070       /// The operand value.
1071       Value *V = nullptr;
1072       /// TreeEntries only allow a single opcode, or an alternate sequence of
1073       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1074       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1075       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1076       /// (e.g., Add/Mul)
1077       bool APO = false;
1078       /// Helper data for the reordering function.
1079       bool IsUsed = false;
1080     };
1081 
1082     /// During operand reordering, we are trying to select the operand at lane
1083     /// that matches best with the operand at the neighboring lane. Our
1084     /// selection is based on the type of value we are looking for. For example,
1085     /// if the neighboring lane has a load, we need to look for a load that is
1086     /// accessing a consecutive address. These strategies are summarized in the
1087     /// 'ReorderingMode' enumerator.
1088     enum class ReorderingMode {
1089       Load,     ///< Matching loads to consecutive memory addresses
1090       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1091       Constant, ///< Matching constants
1092       Splat,    ///< Matching the same instruction multiple times (broadcast)
1093       Failed,   ///< We failed to create a vectorizable group
1094     };
1095 
1096     using OperandDataVec = SmallVector<OperandData, 2>;
1097 
1098     /// A vector of operand vectors.
1099     SmallVector<OperandDataVec, 4> OpsVec;
1100 
1101     const DataLayout &DL;
1102     ScalarEvolution &SE;
1103     const BoUpSLP &R;
1104 
1105     /// \returns the operand data at \p OpIdx and \p Lane.
1106     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1107       return OpsVec[OpIdx][Lane];
1108     }
1109 
1110     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1111     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1112       return OpsVec[OpIdx][Lane];
1113     }
1114 
1115     /// Clears the used flag for all entries.
1116     void clearUsed() {
1117       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1118            OpIdx != NumOperands; ++OpIdx)
1119         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1120              ++Lane)
1121           OpsVec[OpIdx][Lane].IsUsed = false;
1122     }
1123 
1124     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1125     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1126       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1127     }
1128 
1129     // The hard-coded scores listed here are not very important, though it shall
1130     // be higher for better matches to improve the resulting cost. When
1131     // computing the scores of matching one sub-tree with another, we are
1132     // basically counting the number of values that are matching. So even if all
1133     // scores are set to 1, we would still get a decent matching result.
1134     // However, sometimes we have to break ties. For example we may have to
1135     // choose between matching loads vs matching opcodes. This is what these
1136     // scores are helping us with: they provide the order of preference. Also,
1137     // this is important if the scalar is externally used or used in another
1138     // tree entry node in the different lane.
1139 
1140     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1141     static const int ScoreConsecutiveLoads = 4;
1142     /// The same load multiple times. This should have a better score than
1143     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1144     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1145     /// a vector load and 1.0 for a broadcast.
1146     static const int ScoreSplatLoads = 3;
1147     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1148     static const int ScoreReversedLoads = 3;
1149     /// ExtractElementInst from same vector and consecutive indexes.
1150     static const int ScoreConsecutiveExtracts = 4;
1151     /// ExtractElementInst from same vector and reversed indices.
1152     static const int ScoreReversedExtracts = 3;
1153     /// Constants.
1154     static const int ScoreConstants = 2;
1155     /// Instructions with the same opcode.
1156     static const int ScoreSameOpcode = 2;
1157     /// Instructions with alt opcodes (e.g, add + sub).
1158     static const int ScoreAltOpcodes = 1;
1159     /// Identical instructions (a.k.a. splat or broadcast).
1160     static const int ScoreSplat = 1;
1161     /// Matching with an undef is preferable to failing.
1162     static const int ScoreUndef = 1;
1163     /// Score for failing to find a decent match.
1164     static const int ScoreFail = 0;
1165     /// Score if all users are vectorized.
1166     static const int ScoreAllUserVectorized = 1;
1167 
1168     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1169     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1170     /// MainAltOps.
1171     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1172                                ScalarEvolution &SE, int NumLanes,
1173                                ArrayRef<Value *> MainAltOps,
1174                                const TargetTransformInfo *TTI) {
1175       if (V1 == V2) {
1176         if (isa<LoadInst>(V1)) {
1177           // A broadcast of a load can be cheaper on some targets.
1178           // TODO: For now accept a broadcast load with no other internal uses.
1179           if (TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1180               (int)V1->getNumUses() == NumLanes)
1181             return VLOperands::ScoreSplatLoads;
1182         }
1183         return VLOperands::ScoreSplat;
1184       }
1185 
1186       auto *LI1 = dyn_cast<LoadInst>(V1);
1187       auto *LI2 = dyn_cast<LoadInst>(V2);
1188       if (LI1 && LI2) {
1189         if (LI1->getParent() != LI2->getParent())
1190           return VLOperands::ScoreFail;
1191 
1192         Optional<int> Dist = getPointersDiff(
1193             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1194             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1195         if (!Dist || *Dist == 0)
1196           return VLOperands::ScoreFail;
1197         // The distance is too large - still may be profitable to use masked
1198         // loads/gathers.
1199         if (std::abs(*Dist) > NumLanes / 2)
1200           return VLOperands::ScoreAltOpcodes;
1201         // This still will detect consecutive loads, but we might have "holes"
1202         // in some cases. It is ok for non-power-2 vectorization and may produce
1203         // better results. It should not affect current vectorization.
1204         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1205                            : VLOperands::ScoreReversedLoads;
1206       }
1207 
1208       auto *C1 = dyn_cast<Constant>(V1);
1209       auto *C2 = dyn_cast<Constant>(V2);
1210       if (C1 && C2)
1211         return VLOperands::ScoreConstants;
1212 
1213       // Extracts from consecutive indexes of the same vector better score as
1214       // the extracts could be optimized away.
1215       Value *EV1;
1216       ConstantInt *Ex1Idx;
1217       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1218         // Undefs are always profitable for extractelements.
1219         if (isa<UndefValue>(V2))
1220           return VLOperands::ScoreConsecutiveExtracts;
1221         Value *EV2 = nullptr;
1222         ConstantInt *Ex2Idx = nullptr;
1223         if (match(V2,
1224                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1225                                                          m_Undef())))) {
1226           // Undefs are always profitable for extractelements.
1227           if (!Ex2Idx)
1228             return VLOperands::ScoreConsecutiveExtracts;
1229           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1230             return VLOperands::ScoreConsecutiveExtracts;
1231           if (EV2 == EV1) {
1232             int Idx1 = Ex1Idx->getZExtValue();
1233             int Idx2 = Ex2Idx->getZExtValue();
1234             int Dist = Idx2 - Idx1;
1235             // The distance is too large - still may be profitable to use
1236             // shuffles.
1237             if (std::abs(Dist) == 0)
1238               return VLOperands::ScoreSplat;
1239             if (std::abs(Dist) > NumLanes / 2)
1240               return VLOperands::ScoreSameOpcode;
1241             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1242                               : VLOperands::ScoreReversedExtracts;
1243           }
1244           return VLOperands::ScoreAltOpcodes;
1245         }
1246         return VLOperands::ScoreFail;
1247       }
1248 
1249       auto *I1 = dyn_cast<Instruction>(V1);
1250       auto *I2 = dyn_cast<Instruction>(V2);
1251       if (I1 && I2) {
1252         if (I1->getParent() != I2->getParent())
1253           return VLOperands::ScoreFail;
1254         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1255         Ops.push_back(I1);
1256         Ops.push_back(I2);
1257         InstructionsState S = getSameOpcode(Ops);
1258         // Note: Only consider instructions with <= 2 operands to avoid
1259         // complexity explosion.
1260         if (S.getOpcode() &&
1261             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1262              !S.isAltShuffle()) &&
1263             all_of(Ops, [&S](Value *V) {
1264               return cast<Instruction>(V)->getNumOperands() ==
1265                      S.MainOp->getNumOperands();
1266             }))
1267           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1268                                   : VLOperands::ScoreSameOpcode;
1269       }
1270 
1271       if (isa<UndefValue>(V2))
1272         return VLOperands::ScoreUndef;
1273 
1274       return VLOperands::ScoreFail;
1275     }
1276 
1277     /// \param Lane lane of the operands under analysis.
1278     /// \param OpIdx operand index in \p Lane lane we're looking the best
1279     /// candidate for.
1280     /// \param Idx operand index of the current candidate value.
1281     /// \returns The additional score due to possible broadcasting of the
1282     /// elements in the lane. It is more profitable to have power-of-2 unique
1283     /// elements in the lane, it will be vectorized with higher probability
1284     /// after removing duplicates. Currently the SLP vectorizer supports only
1285     /// vectorization of the power-of-2 number of unique scalars.
1286     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1287       Value *IdxLaneV = getData(Idx, Lane).V;
1288       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1289         return 0;
1290       SmallPtrSet<Value *, 4> Uniques;
1291       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1292         if (Ln == Lane)
1293           continue;
1294         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1295         if (!isa<Instruction>(OpIdxLnV))
1296           return 0;
1297         Uniques.insert(OpIdxLnV);
1298       }
1299       int UniquesCount = Uniques.size();
1300       int UniquesCntWithIdxLaneV =
1301           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1302       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1303       int UniquesCntWithOpIdxLaneV =
1304           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1305       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1306         return 0;
1307       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1308               UniquesCntWithOpIdxLaneV) -
1309              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1310     }
1311 
1312     /// \param Lane lane of the operands under analysis.
1313     /// \param OpIdx operand index in \p Lane lane we're looking the best
1314     /// candidate for.
1315     /// \param Idx operand index of the current candidate value.
1316     /// \returns The additional score for the scalar which users are all
1317     /// vectorized.
1318     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1319       Value *IdxLaneV = getData(Idx, Lane).V;
1320       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1321       // Do not care about number of uses for vector-like instructions
1322       // (extractelement/extractvalue with constant indices), they are extracts
1323       // themselves and already externally used. Vectorization of such
1324       // instructions does not add extra extractelement instruction, just may
1325       // remove it.
1326       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1327           isVectorLikeInstWithConstOps(OpIdxLaneV))
1328         return VLOperands::ScoreAllUserVectorized;
1329       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1330       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1331         return 0;
1332       return R.areAllUsersVectorized(IdxLaneI, None)
1333                  ? VLOperands::ScoreAllUserVectorized
1334                  : 0;
1335     }
1336 
1337     /// Go through the operands of \p LHS and \p RHS recursively until \p
1338     /// MaxLevel, and return the cummulative score. For example:
1339     /// \verbatim
1340     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1341     ///     \ /         \ /         \ /        \ /
1342     ///      +           +           +          +
1343     ///     G1          G2          G3         G4
1344     /// \endverbatim
1345     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1346     /// each level recursively, accumulating the score. It starts from matching
1347     /// the additions at level 0, then moves on to the loads (level 1). The
1348     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1349     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1350     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1351     /// Please note that the order of the operands does not matter, as we
1352     /// evaluate the score of all profitable combinations of operands. In
1353     /// other words the score of G1 and G4 is the same as G1 and G2. This
1354     /// heuristic is based on ideas described in:
1355     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1356     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1357     ///   Luís F. W. Góes
1358     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1359                            ArrayRef<Value *> MainAltOps) {
1360 
1361       // Get the shallow score of V1 and V2.
1362       int ShallowScoreAtThisLevel =
1363           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps, R.TTI);
1364 
1365       // If reached MaxLevel,
1366       //  or if V1 and V2 are not instructions,
1367       //  or if they are SPLAT,
1368       //  or if they are not consecutive,
1369       //  or if profitable to vectorize loads or extractelements, early return
1370       //  the current cost.
1371       auto *I1 = dyn_cast<Instruction>(LHS);
1372       auto *I2 = dyn_cast<Instruction>(RHS);
1373       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1374           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1375           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1376             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1377             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1378            ShallowScoreAtThisLevel))
1379         return ShallowScoreAtThisLevel;
1380       assert(I1 && I2 && "Should have early exited.");
1381 
1382       // Contains the I2 operand indexes that got matched with I1 operands.
1383       SmallSet<unsigned, 4> Op2Used;
1384 
1385       // Recursion towards the operands of I1 and I2. We are trying all possible
1386       // operand pairs, and keeping track of the best score.
1387       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1388            OpIdx1 != NumOperands1; ++OpIdx1) {
1389         // Try to pair op1I with the best operand of I2.
1390         int MaxTmpScore = 0;
1391         unsigned MaxOpIdx2 = 0;
1392         bool FoundBest = false;
1393         // If I2 is commutative try all combinations.
1394         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1395         unsigned ToIdx = isCommutative(I2)
1396                              ? I2->getNumOperands()
1397                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1398         assert(FromIdx <= ToIdx && "Bad index");
1399         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1400           // Skip operands already paired with OpIdx1.
1401           if (Op2Used.count(OpIdx2))
1402             continue;
1403           // Recursively calculate the cost at each level
1404           int TmpScore =
1405               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1406                                  CurrLevel + 1, MaxLevel, None);
1407           // Look for the best score.
1408           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1409             MaxTmpScore = TmpScore;
1410             MaxOpIdx2 = OpIdx2;
1411             FoundBest = true;
1412           }
1413         }
1414         if (FoundBest) {
1415           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1416           Op2Used.insert(MaxOpIdx2);
1417           ShallowScoreAtThisLevel += MaxTmpScore;
1418         }
1419       }
1420       return ShallowScoreAtThisLevel;
1421     }
1422 
1423     /// Score scaling factor for fully compatible instructions but with
1424     /// different number of external uses. Allows better selection of the
1425     /// instructions with less external uses.
1426     static const int ScoreScaleFactor = 10;
1427 
1428     /// \Returns the look-ahead score, which tells us how much the sub-trees
1429     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1430     /// score. This helps break ties in an informed way when we cannot decide on
1431     /// the order of the operands by just considering the immediate
1432     /// predecessors.
1433     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1434                           int Lane, unsigned OpIdx, unsigned Idx,
1435                           bool &IsUsed) {
1436       int Score =
1437           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1438       if (Score) {
1439         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1440         if (Score <= -SplatScore) {
1441           // Set the minimum score for splat-like sequence to avoid setting
1442           // failed state.
1443           Score = 1;
1444         } else {
1445           Score += SplatScore;
1446           // Scale score to see the difference between different operands
1447           // and similar operands but all vectorized/not all vectorized
1448           // uses. It does not affect actual selection of the best
1449           // compatible operand in general, just allows to select the
1450           // operand with all vectorized uses.
1451           Score *= ScoreScaleFactor;
1452           Score += getExternalUseScore(Lane, OpIdx, Idx);
1453           IsUsed = true;
1454         }
1455       }
1456       return Score;
1457     }
1458 
1459     /// Best defined scores per lanes between the passes. Used to choose the
1460     /// best operand (with the highest score) between the passes.
1461     /// The key - {Operand Index, Lane}.
1462     /// The value - the best score between the passes for the lane and the
1463     /// operand.
1464     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1465         BestScoresPerLanes;
1466 
1467     // Search all operands in Ops[*][Lane] for the one that matches best
1468     // Ops[OpIdx][LastLane] and return its opreand index.
1469     // If no good match can be found, return None.
1470     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1471                                       ArrayRef<ReorderingMode> ReorderingModes,
1472                                       ArrayRef<Value *> MainAltOps) {
1473       unsigned NumOperands = getNumOperands();
1474 
1475       // The operand of the previous lane at OpIdx.
1476       Value *OpLastLane = getData(OpIdx, LastLane).V;
1477 
1478       // Our strategy mode for OpIdx.
1479       ReorderingMode RMode = ReorderingModes[OpIdx];
1480       if (RMode == ReorderingMode::Failed)
1481         return None;
1482 
1483       // The linearized opcode of the operand at OpIdx, Lane.
1484       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1485 
1486       // The best operand index and its score.
1487       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1488       // are using the score to differentiate between the two.
1489       struct BestOpData {
1490         Optional<unsigned> Idx = None;
1491         unsigned Score = 0;
1492       } BestOp;
1493       BestOp.Score =
1494           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1495               .first->second;
1496 
1497       // Track if the operand must be marked as used. If the operand is set to
1498       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1499       // want to reestimate the operands again on the following iterations).
1500       bool IsUsed =
1501           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1502       // Iterate through all unused operands and look for the best.
1503       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1504         // Get the operand at Idx and Lane.
1505         OperandData &OpData = getData(Idx, Lane);
1506         Value *Op = OpData.V;
1507         bool OpAPO = OpData.APO;
1508 
1509         // Skip already selected operands.
1510         if (OpData.IsUsed)
1511           continue;
1512 
1513         // Skip if we are trying to move the operand to a position with a
1514         // different opcode in the linearized tree form. This would break the
1515         // semantics.
1516         if (OpAPO != OpIdxAPO)
1517           continue;
1518 
1519         // Look for an operand that matches the current mode.
1520         switch (RMode) {
1521         case ReorderingMode::Load:
1522         case ReorderingMode::Constant:
1523         case ReorderingMode::Opcode: {
1524           bool LeftToRight = Lane > LastLane;
1525           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1526           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1527           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1528                                         OpIdx, Idx, IsUsed);
1529           if (Score > static_cast<int>(BestOp.Score)) {
1530             BestOp.Idx = Idx;
1531             BestOp.Score = Score;
1532             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1533           }
1534           break;
1535         }
1536         case ReorderingMode::Splat:
1537           if (Op == OpLastLane)
1538             BestOp.Idx = Idx;
1539           break;
1540         case ReorderingMode::Failed:
1541           llvm_unreachable("Not expected Failed reordering mode.");
1542         }
1543       }
1544 
1545       if (BestOp.Idx) {
1546         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1547         return BestOp.Idx;
1548       }
1549       // If we could not find a good match return None.
1550       return None;
1551     }
1552 
1553     /// Helper for reorderOperandVecs.
1554     /// \returns the lane that we should start reordering from. This is the one
1555     /// which has the least number of operands that can freely move about or
1556     /// less profitable because it already has the most optimal set of operands.
1557     unsigned getBestLaneToStartReordering() const {
1558       unsigned Min = UINT_MAX;
1559       unsigned SameOpNumber = 0;
1560       // std::pair<unsigned, unsigned> is used to implement a simple voting
1561       // algorithm and choose the lane with the least number of operands that
1562       // can freely move about or less profitable because it already has the
1563       // most optimal set of operands. The first unsigned is a counter for
1564       // voting, the second unsigned is the counter of lanes with instructions
1565       // with same/alternate opcodes and same parent basic block.
1566       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1567       // Try to be closer to the original results, if we have multiple lanes
1568       // with same cost. If 2 lanes have the same cost, use the one with the
1569       // lowest index.
1570       for (int I = getNumLanes(); I > 0; --I) {
1571         unsigned Lane = I - 1;
1572         OperandsOrderData NumFreeOpsHash =
1573             getMaxNumOperandsThatCanBeReordered(Lane);
1574         // Compare the number of operands that can move and choose the one with
1575         // the least number.
1576         if (NumFreeOpsHash.NumOfAPOs < Min) {
1577           Min = NumFreeOpsHash.NumOfAPOs;
1578           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1579           HashMap.clear();
1580           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1581         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1582                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1583           // Select the most optimal lane in terms of number of operands that
1584           // should be moved around.
1585           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1586           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1587         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1588                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1589           auto It = HashMap.find(NumFreeOpsHash.Hash);
1590           if (It == HashMap.end())
1591             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1592           else
1593             ++It->second.first;
1594         }
1595       }
1596       // Select the lane with the minimum counter.
1597       unsigned BestLane = 0;
1598       unsigned CntMin = UINT_MAX;
1599       for (const auto &Data : reverse(HashMap)) {
1600         if (Data.second.first < CntMin) {
1601           CntMin = Data.second.first;
1602           BestLane = Data.second.second;
1603         }
1604       }
1605       return BestLane;
1606     }
1607 
1608     /// Data structure that helps to reorder operands.
1609     struct OperandsOrderData {
1610       /// The best number of operands with the same APOs, which can be
1611       /// reordered.
1612       unsigned NumOfAPOs = UINT_MAX;
1613       /// Number of operands with the same/alternate instruction opcode and
1614       /// parent.
1615       unsigned NumOpsWithSameOpcodeParent = 0;
1616       /// Hash for the actual operands ordering.
1617       /// Used to count operands, actually their position id and opcode
1618       /// value. It is used in the voting mechanism to find the lane with the
1619       /// least number of operands that can freely move about or less profitable
1620       /// because it already has the most optimal set of operands. Can be
1621       /// replaced with SmallVector<unsigned> instead but hash code is faster
1622       /// and requires less memory.
1623       unsigned Hash = 0;
1624     };
1625     /// \returns the maximum number of operands that are allowed to be reordered
1626     /// for \p Lane and the number of compatible instructions(with the same
1627     /// parent/opcode). This is used as a heuristic for selecting the first lane
1628     /// to start operand reordering.
1629     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1630       unsigned CntTrue = 0;
1631       unsigned NumOperands = getNumOperands();
1632       // Operands with the same APO can be reordered. We therefore need to count
1633       // how many of them we have for each APO, like this: Cnt[APO] = x.
1634       // Since we only have two APOs, namely true and false, we can avoid using
1635       // a map. Instead we can simply count the number of operands that
1636       // correspond to one of them (in this case the 'true' APO), and calculate
1637       // the other by subtracting it from the total number of operands.
1638       // Operands with the same instruction opcode and parent are more
1639       // profitable since we don't need to move them in many cases, with a high
1640       // probability such lane already can be vectorized effectively.
1641       bool AllUndefs = true;
1642       unsigned NumOpsWithSameOpcodeParent = 0;
1643       Instruction *OpcodeI = nullptr;
1644       BasicBlock *Parent = nullptr;
1645       unsigned Hash = 0;
1646       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1647         const OperandData &OpData = getData(OpIdx, Lane);
1648         if (OpData.APO)
1649           ++CntTrue;
1650         // Use Boyer-Moore majority voting for finding the majority opcode and
1651         // the number of times it occurs.
1652         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1653           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1654               I->getParent() != Parent) {
1655             if (NumOpsWithSameOpcodeParent == 0) {
1656               NumOpsWithSameOpcodeParent = 1;
1657               OpcodeI = I;
1658               Parent = I->getParent();
1659             } else {
1660               --NumOpsWithSameOpcodeParent;
1661             }
1662           } else {
1663             ++NumOpsWithSameOpcodeParent;
1664           }
1665         }
1666         Hash = hash_combine(
1667             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1668         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1669       }
1670       if (AllUndefs)
1671         return {};
1672       OperandsOrderData Data;
1673       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1674       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1675       Data.Hash = Hash;
1676       return Data;
1677     }
1678 
1679     /// Go through the instructions in VL and append their operands.
1680     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1681       assert(!VL.empty() && "Bad VL");
1682       assert((empty() || VL.size() == getNumLanes()) &&
1683              "Expected same number of lanes");
1684       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1685       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1686       OpsVec.resize(NumOperands);
1687       unsigned NumLanes = VL.size();
1688       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1689         OpsVec[OpIdx].resize(NumLanes);
1690         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1691           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1692           // Our tree has just 3 nodes: the root and two operands.
1693           // It is therefore trivial to get the APO. We only need to check the
1694           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1695           // RHS operand. The LHS operand of both add and sub is never attached
1696           // to an inversese operation in the linearized form, therefore its APO
1697           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1698 
1699           // Since operand reordering is performed on groups of commutative
1700           // operations or alternating sequences (e.g., +, -), we can safely
1701           // tell the inverse operations by checking commutativity.
1702           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1703           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1704           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1705                                  APO, false};
1706         }
1707       }
1708     }
1709 
1710     /// \returns the number of operands.
1711     unsigned getNumOperands() const { return OpsVec.size(); }
1712 
1713     /// \returns the number of lanes.
1714     unsigned getNumLanes() const { return OpsVec[0].size(); }
1715 
1716     /// \returns the operand value at \p OpIdx and \p Lane.
1717     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1718       return getData(OpIdx, Lane).V;
1719     }
1720 
1721     /// \returns true if the data structure is empty.
1722     bool empty() const { return OpsVec.empty(); }
1723 
1724     /// Clears the data.
1725     void clear() { OpsVec.clear(); }
1726 
1727     /// \Returns true if there are enough operands identical to \p Op to fill
1728     /// the whole vector.
1729     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1730     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1731       bool OpAPO = getData(OpIdx, Lane).APO;
1732       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1733         if (Ln == Lane)
1734           continue;
1735         // This is set to true if we found a candidate for broadcast at Lane.
1736         bool FoundCandidate = false;
1737         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1738           OperandData &Data = getData(OpI, Ln);
1739           if (Data.APO != OpAPO || Data.IsUsed)
1740             continue;
1741           if (Data.V == Op) {
1742             FoundCandidate = true;
1743             Data.IsUsed = true;
1744             break;
1745           }
1746         }
1747         if (!FoundCandidate)
1748           return false;
1749       }
1750       return true;
1751     }
1752 
1753   public:
1754     /// Initialize with all the operands of the instruction vector \p RootVL.
1755     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1756                ScalarEvolution &SE, const BoUpSLP &R)
1757         : DL(DL), SE(SE), R(R) {
1758       // Append all the operands of RootVL.
1759       appendOperandsOfVL(RootVL);
1760     }
1761 
1762     /// \Returns a value vector with the operands across all lanes for the
1763     /// opearnd at \p OpIdx.
1764     ValueList getVL(unsigned OpIdx) const {
1765       ValueList OpVL(OpsVec[OpIdx].size());
1766       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1767              "Expected same num of lanes across all operands");
1768       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1769         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1770       return OpVL;
1771     }
1772 
1773     // Performs operand reordering for 2 or more operands.
1774     // The original operands are in OrigOps[OpIdx][Lane].
1775     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1776     void reorder() {
1777       unsigned NumOperands = getNumOperands();
1778       unsigned NumLanes = getNumLanes();
1779       // Each operand has its own mode. We are using this mode to help us select
1780       // the instructions for each lane, so that they match best with the ones
1781       // we have selected so far.
1782       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1783 
1784       // This is a greedy single-pass algorithm. We are going over each lane
1785       // once and deciding on the best order right away with no back-tracking.
1786       // However, in order to increase its effectiveness, we start with the lane
1787       // that has operands that can move the least. For example, given the
1788       // following lanes:
1789       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1790       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1791       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1792       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1793       // we will start at Lane 1, since the operands of the subtraction cannot
1794       // be reordered. Then we will visit the rest of the lanes in a circular
1795       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1796 
1797       // Find the first lane that we will start our search from.
1798       unsigned FirstLane = getBestLaneToStartReordering();
1799 
1800       // Initialize the modes.
1801       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1802         Value *OpLane0 = getValue(OpIdx, FirstLane);
1803         // Keep track if we have instructions with all the same opcode on one
1804         // side.
1805         if (isa<LoadInst>(OpLane0))
1806           ReorderingModes[OpIdx] = ReorderingMode::Load;
1807         else if (isa<Instruction>(OpLane0)) {
1808           // Check if OpLane0 should be broadcast.
1809           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1810             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1811           else
1812             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1813         }
1814         else if (isa<Constant>(OpLane0))
1815           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1816         else if (isa<Argument>(OpLane0))
1817           // Our best hope is a Splat. It may save some cost in some cases.
1818           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1819         else
1820           // NOTE: This should be unreachable.
1821           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1822       }
1823 
1824       // Check that we don't have same operands. No need to reorder if operands
1825       // are just perfect diamond or shuffled diamond match. Do not do it only
1826       // for possible broadcasts or non-power of 2 number of scalars (just for
1827       // now).
1828       auto &&SkipReordering = [this]() {
1829         SmallPtrSet<Value *, 4> UniqueValues;
1830         ArrayRef<OperandData> Op0 = OpsVec.front();
1831         for (const OperandData &Data : Op0)
1832           UniqueValues.insert(Data.V);
1833         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1834           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1835                 return !UniqueValues.contains(Data.V);
1836               }))
1837             return false;
1838         }
1839         // TODO: Check if we can remove a check for non-power-2 number of
1840         // scalars after full support of non-power-2 vectorization.
1841         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1842       };
1843 
1844       // If the initial strategy fails for any of the operand indexes, then we
1845       // perform reordering again in a second pass. This helps avoid assigning
1846       // high priority to the failed strategy, and should improve reordering for
1847       // the non-failed operand indexes.
1848       for (int Pass = 0; Pass != 2; ++Pass) {
1849         // Check if no need to reorder operands since they're are perfect or
1850         // shuffled diamond match.
1851         // Need to to do it to avoid extra external use cost counting for
1852         // shuffled matches, which may cause regressions.
1853         if (SkipReordering())
1854           break;
1855         // Skip the second pass if the first pass did not fail.
1856         bool StrategyFailed = false;
1857         // Mark all operand data as free to use.
1858         clearUsed();
1859         // We keep the original operand order for the FirstLane, so reorder the
1860         // rest of the lanes. We are visiting the nodes in a circular fashion,
1861         // using FirstLane as the center point and increasing the radius
1862         // distance.
1863         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1864         for (unsigned I = 0; I < NumOperands; ++I)
1865           MainAltOps[I].push_back(getData(I, FirstLane).V);
1866 
1867         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1868           // Visit the lane on the right and then the lane on the left.
1869           for (int Direction : {+1, -1}) {
1870             int Lane = FirstLane + Direction * Distance;
1871             if (Lane < 0 || Lane >= (int)NumLanes)
1872               continue;
1873             int LastLane = Lane - Direction;
1874             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1875                    "Out of bounds");
1876             // Look for a good match for each operand.
1877             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1878               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1879               Optional<unsigned> BestIdx = getBestOperand(
1880                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1881               // By not selecting a value, we allow the operands that follow to
1882               // select a better matching value. We will get a non-null value in
1883               // the next run of getBestOperand().
1884               if (BestIdx) {
1885                 // Swap the current operand with the one returned by
1886                 // getBestOperand().
1887                 swap(OpIdx, BestIdx.getValue(), Lane);
1888               } else {
1889                 // We failed to find a best operand, set mode to 'Failed'.
1890                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1891                 // Enable the second pass.
1892                 StrategyFailed = true;
1893               }
1894               // Try to get the alternate opcode and follow it during analysis.
1895               if (MainAltOps[OpIdx].size() != 2) {
1896                 OperandData &AltOp = getData(OpIdx, Lane);
1897                 InstructionsState OpS =
1898                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1899                 if (OpS.getOpcode() && OpS.isAltShuffle())
1900                   MainAltOps[OpIdx].push_back(AltOp.V);
1901               }
1902             }
1903           }
1904         }
1905         // Skip second pass if the strategy did not fail.
1906         if (!StrategyFailed)
1907           break;
1908       }
1909     }
1910 
1911 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1912     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1913       switch (RMode) {
1914       case ReorderingMode::Load:
1915         return "Load";
1916       case ReorderingMode::Opcode:
1917         return "Opcode";
1918       case ReorderingMode::Constant:
1919         return "Constant";
1920       case ReorderingMode::Splat:
1921         return "Splat";
1922       case ReorderingMode::Failed:
1923         return "Failed";
1924       }
1925       llvm_unreachable("Unimplemented Reordering Type");
1926     }
1927 
1928     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1929                                                    raw_ostream &OS) {
1930       return OS << getModeStr(RMode);
1931     }
1932 
1933     /// Debug print.
1934     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1935       printMode(RMode, dbgs());
1936     }
1937 
1938     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1939       return printMode(RMode, OS);
1940     }
1941 
1942     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1943       const unsigned Indent = 2;
1944       unsigned Cnt = 0;
1945       for (const OperandDataVec &OpDataVec : OpsVec) {
1946         OS << "Operand " << Cnt++ << "\n";
1947         for (const OperandData &OpData : OpDataVec) {
1948           OS.indent(Indent) << "{";
1949           if (Value *V = OpData.V)
1950             OS << *V;
1951           else
1952             OS << "null";
1953           OS << ", APO:" << OpData.APO << "}\n";
1954         }
1955         OS << "\n";
1956       }
1957       return OS;
1958     }
1959 
1960     /// Debug print.
1961     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1962 #endif
1963   };
1964 
1965   /// Checks if the instruction is marked for deletion.
1966   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1967 
1968   /// Removes an instruction from its block and eventually deletes it.
1969   /// It's like Instruction::eraseFromParent() except that the actual deletion
1970   /// is delayed until BoUpSLP is destructed.
1971   void eraseInstruction(Instruction *I) {
1972     DeletedInstructions.insert(I);
1973   }
1974 
1975   ~BoUpSLP();
1976 
1977 private:
1978   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1979   /// reordering (i.e. the operands can be reordered because they have only one
1980   /// user and reordarable).
1981   /// \param ReorderableGathers List of all gather nodes that require reordering
1982   /// (e.g., gather of extractlements or partially vectorizable loads).
1983   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1984   /// reordering, subset of \p NonVectorized.
1985   bool
1986   canReorderOperands(TreeEntry *UserTE,
1987                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1988                      ArrayRef<TreeEntry *> ReorderableGathers,
1989                      SmallVectorImpl<TreeEntry *> &GatherOps);
1990 
1991   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1992   /// if any. If it is not vectorized (gather node), returns nullptr.
1993   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1994     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1995     TreeEntry *TE = nullptr;
1996     const auto *It = find_if(VL, [this, &TE](Value *V) {
1997       TE = getTreeEntry(V);
1998       return TE;
1999     });
2000     if (It != VL.end() && TE->isSame(VL))
2001       return TE;
2002     return nullptr;
2003   }
2004 
2005   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2006   /// if any. If it is not vectorized (gather node), returns nullptr.
2007   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2008                                         unsigned OpIdx) const {
2009     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2010         const_cast<TreeEntry *>(UserTE), OpIdx);
2011   }
2012 
2013   /// Checks if all users of \p I are the part of the vectorization tree.
2014   bool areAllUsersVectorized(Instruction *I,
2015                              ArrayRef<Value *> VectorizedVals) const;
2016 
2017   /// \returns the cost of the vectorizable entry.
2018   InstructionCost getEntryCost(const TreeEntry *E,
2019                                ArrayRef<Value *> VectorizedVals);
2020 
2021   /// This is the recursive part of buildTree.
2022   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2023                      const EdgeInfo &EI);
2024 
2025   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2026   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2027   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2028   /// returns false, setting \p CurrentOrder to either an empty vector or a
2029   /// non-identity permutation that allows to reuse extract instructions.
2030   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2031                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2032 
2033   /// Vectorize a single entry in the tree.
2034   Value *vectorizeTree(TreeEntry *E);
2035 
2036   /// Vectorize a single entry in the tree, starting in \p VL.
2037   Value *vectorizeTree(ArrayRef<Value *> VL);
2038 
2039   /// Create a new vector from a list of scalar values.  Produces a sequence
2040   /// which exploits values reused across lanes, and arranges the inserts
2041   /// for ease of later optimization.
2042   Value *createBuildVector(ArrayRef<Value *> VL);
2043 
2044   /// \returns the scalarization cost for this type. Scalarization in this
2045   /// context means the creation of vectors from a group of scalars. If \p
2046   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2047   /// vector elements.
2048   InstructionCost getGatherCost(FixedVectorType *Ty,
2049                                 const APInt &ShuffledIndices,
2050                                 bool NeedToShuffle) const;
2051 
2052   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2053   /// tree entries.
2054   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2055   /// previous tree entries. \p Mask is filled with the shuffle mask.
2056   Optional<TargetTransformInfo::ShuffleKind>
2057   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2058                         SmallVectorImpl<const TreeEntry *> &Entries);
2059 
2060   /// \returns the scalarization cost for this list of values. Assuming that
2061   /// this subtree gets vectorized, we may need to extract the values from the
2062   /// roots. This method calculates the cost of extracting the values.
2063   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2064 
2065   /// Set the Builder insert point to one after the last instruction in
2066   /// the bundle
2067   void setInsertPointAfterBundle(const TreeEntry *E);
2068 
2069   /// \returns a vector from a collection of scalars in \p VL.
2070   Value *gather(ArrayRef<Value *> VL);
2071 
2072   /// \returns whether the VectorizableTree is fully vectorizable and will
2073   /// be beneficial even the tree height is tiny.
2074   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2075 
2076   /// Reorder commutative or alt operands to get better probability of
2077   /// generating vectorized code.
2078   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2079                                              SmallVectorImpl<Value *> &Left,
2080                                              SmallVectorImpl<Value *> &Right,
2081                                              const DataLayout &DL,
2082                                              ScalarEvolution &SE,
2083                                              const BoUpSLP &R);
2084   struct TreeEntry {
2085     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2086     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2087 
2088     /// \returns true if the scalars in VL are equal to this entry.
2089     bool isSame(ArrayRef<Value *> VL) const {
2090       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2091         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2092           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2093         return VL.size() == Mask.size() &&
2094                std::equal(VL.begin(), VL.end(), Mask.begin(),
2095                           [Scalars](Value *V, int Idx) {
2096                             return (isa<UndefValue>(V) &&
2097                                     Idx == UndefMaskElem) ||
2098                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2099                           });
2100       };
2101       if (!ReorderIndices.empty()) {
2102         // TODO: implement matching if the nodes are just reordered, still can
2103         // treat the vector as the same if the list of scalars matches VL
2104         // directly, without reordering.
2105         SmallVector<int> Mask;
2106         inversePermutation(ReorderIndices, Mask);
2107         if (VL.size() == Scalars.size())
2108           return IsSame(Scalars, Mask);
2109         if (VL.size() == ReuseShuffleIndices.size()) {
2110           ::addMask(Mask, ReuseShuffleIndices);
2111           return IsSame(Scalars, Mask);
2112         }
2113         return false;
2114       }
2115       return IsSame(Scalars, ReuseShuffleIndices);
2116     }
2117 
2118     /// \returns true if current entry has same operands as \p TE.
2119     bool hasEqualOperands(const TreeEntry &TE) const {
2120       if (TE.getNumOperands() != getNumOperands())
2121         return false;
2122       SmallBitVector Used(getNumOperands());
2123       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2124         unsigned PrevCount = Used.count();
2125         for (unsigned K = 0; K < E; ++K) {
2126           if (Used.test(K))
2127             continue;
2128           if (getOperand(K) == TE.getOperand(I)) {
2129             Used.set(K);
2130             break;
2131           }
2132         }
2133         // Check if we actually found the matching operand.
2134         if (PrevCount == Used.count())
2135           return false;
2136       }
2137       return true;
2138     }
2139 
2140     /// \return Final vectorization factor for the node. Defined by the total
2141     /// number of vectorized scalars, including those, used several times in the
2142     /// entry and counted in the \a ReuseShuffleIndices, if any.
2143     unsigned getVectorFactor() const {
2144       if (!ReuseShuffleIndices.empty())
2145         return ReuseShuffleIndices.size();
2146       return Scalars.size();
2147     };
2148 
2149     /// A vector of scalars.
2150     ValueList Scalars;
2151 
2152     /// The Scalars are vectorized into this value. It is initialized to Null.
2153     Value *VectorizedValue = nullptr;
2154 
2155     /// Do we need to gather this sequence or vectorize it
2156     /// (either with vector instruction or with scatter/gather
2157     /// intrinsics for store/load)?
2158     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2159     EntryState State;
2160 
2161     /// Does this sequence require some shuffling?
2162     SmallVector<int, 4> ReuseShuffleIndices;
2163 
2164     /// Does this entry require reordering?
2165     SmallVector<unsigned, 4> ReorderIndices;
2166 
2167     /// Points back to the VectorizableTree.
2168     ///
2169     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2170     /// to be a pointer and needs to be able to initialize the child iterator.
2171     /// Thus we need a reference back to the container to translate the indices
2172     /// to entries.
2173     VecTreeTy &Container;
2174 
2175     /// The TreeEntry index containing the user of this entry.  We can actually
2176     /// have multiple users so the data structure is not truly a tree.
2177     SmallVector<EdgeInfo, 1> UserTreeIndices;
2178 
2179     /// The index of this treeEntry in VectorizableTree.
2180     int Idx = -1;
2181 
2182   private:
2183     /// The operands of each instruction in each lane Operands[op_index][lane].
2184     /// Note: This helps avoid the replication of the code that performs the
2185     /// reordering of operands during buildTree_rec() and vectorizeTree().
2186     SmallVector<ValueList, 2> Operands;
2187 
2188     /// The main/alternate instruction.
2189     Instruction *MainOp = nullptr;
2190     Instruction *AltOp = nullptr;
2191 
2192   public:
2193     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2194     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2195       if (Operands.size() < OpIdx + 1)
2196         Operands.resize(OpIdx + 1);
2197       assert(Operands[OpIdx].empty() && "Already resized?");
2198       assert(OpVL.size() <= Scalars.size() &&
2199              "Number of operands is greater than the number of scalars.");
2200       Operands[OpIdx].resize(OpVL.size());
2201       copy(OpVL, Operands[OpIdx].begin());
2202     }
2203 
2204     /// Set the operands of this bundle in their original order.
2205     void setOperandsInOrder() {
2206       assert(Operands.empty() && "Already initialized?");
2207       auto *I0 = cast<Instruction>(Scalars[0]);
2208       Operands.resize(I0->getNumOperands());
2209       unsigned NumLanes = Scalars.size();
2210       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2211            OpIdx != NumOperands; ++OpIdx) {
2212         Operands[OpIdx].resize(NumLanes);
2213         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2214           auto *I = cast<Instruction>(Scalars[Lane]);
2215           assert(I->getNumOperands() == NumOperands &&
2216                  "Expected same number of operands");
2217           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2218         }
2219       }
2220     }
2221 
2222     /// Reorders operands of the node to the given mask \p Mask.
2223     void reorderOperands(ArrayRef<int> Mask) {
2224       for (ValueList &Operand : Operands)
2225         reorderScalars(Operand, Mask);
2226     }
2227 
2228     /// \returns the \p OpIdx operand of this TreeEntry.
2229     ValueList &getOperand(unsigned OpIdx) {
2230       assert(OpIdx < Operands.size() && "Off bounds");
2231       return Operands[OpIdx];
2232     }
2233 
2234     /// \returns the \p OpIdx operand of this TreeEntry.
2235     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2236       assert(OpIdx < Operands.size() && "Off bounds");
2237       return Operands[OpIdx];
2238     }
2239 
2240     /// \returns the number of operands.
2241     unsigned getNumOperands() const { return Operands.size(); }
2242 
2243     /// \return the single \p OpIdx operand.
2244     Value *getSingleOperand(unsigned OpIdx) const {
2245       assert(OpIdx < Operands.size() && "Off bounds");
2246       assert(!Operands[OpIdx].empty() && "No operand available");
2247       return Operands[OpIdx][0];
2248     }
2249 
2250     /// Some of the instructions in the list have alternate opcodes.
2251     bool isAltShuffle() const { return MainOp != AltOp; }
2252 
2253     bool isOpcodeOrAlt(Instruction *I) const {
2254       unsigned CheckedOpcode = I->getOpcode();
2255       return (getOpcode() == CheckedOpcode ||
2256               getAltOpcode() == CheckedOpcode);
2257     }
2258 
2259     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2260     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2261     /// \p OpValue.
2262     Value *isOneOf(Value *Op) const {
2263       auto *I = dyn_cast<Instruction>(Op);
2264       if (I && isOpcodeOrAlt(I))
2265         return Op;
2266       return MainOp;
2267     }
2268 
2269     void setOperations(const InstructionsState &S) {
2270       MainOp = S.MainOp;
2271       AltOp = S.AltOp;
2272     }
2273 
2274     Instruction *getMainOp() const {
2275       return MainOp;
2276     }
2277 
2278     Instruction *getAltOp() const {
2279       return AltOp;
2280     }
2281 
2282     /// The main/alternate opcodes for the list of instructions.
2283     unsigned getOpcode() const {
2284       return MainOp ? MainOp->getOpcode() : 0;
2285     }
2286 
2287     unsigned getAltOpcode() const {
2288       return AltOp ? AltOp->getOpcode() : 0;
2289     }
2290 
2291     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2292     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2293     int findLaneForValue(Value *V) const {
2294       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2295       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2296       if (!ReorderIndices.empty())
2297         FoundLane = ReorderIndices[FoundLane];
2298       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2299       if (!ReuseShuffleIndices.empty()) {
2300         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2301                                   find(ReuseShuffleIndices, FoundLane));
2302       }
2303       return FoundLane;
2304     }
2305 
2306 #ifndef NDEBUG
2307     /// Debug printer.
2308     LLVM_DUMP_METHOD void dump() const {
2309       dbgs() << Idx << ".\n";
2310       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2311         dbgs() << "Operand " << OpI << ":\n";
2312         for (const Value *V : Operands[OpI])
2313           dbgs().indent(2) << *V << "\n";
2314       }
2315       dbgs() << "Scalars: \n";
2316       for (Value *V : Scalars)
2317         dbgs().indent(2) << *V << "\n";
2318       dbgs() << "State: ";
2319       switch (State) {
2320       case Vectorize:
2321         dbgs() << "Vectorize\n";
2322         break;
2323       case ScatterVectorize:
2324         dbgs() << "ScatterVectorize\n";
2325         break;
2326       case NeedToGather:
2327         dbgs() << "NeedToGather\n";
2328         break;
2329       }
2330       dbgs() << "MainOp: ";
2331       if (MainOp)
2332         dbgs() << *MainOp << "\n";
2333       else
2334         dbgs() << "NULL\n";
2335       dbgs() << "AltOp: ";
2336       if (AltOp)
2337         dbgs() << *AltOp << "\n";
2338       else
2339         dbgs() << "NULL\n";
2340       dbgs() << "VectorizedValue: ";
2341       if (VectorizedValue)
2342         dbgs() << *VectorizedValue << "\n";
2343       else
2344         dbgs() << "NULL\n";
2345       dbgs() << "ReuseShuffleIndices: ";
2346       if (ReuseShuffleIndices.empty())
2347         dbgs() << "Empty";
2348       else
2349         for (int ReuseIdx : ReuseShuffleIndices)
2350           dbgs() << ReuseIdx << ", ";
2351       dbgs() << "\n";
2352       dbgs() << "ReorderIndices: ";
2353       for (unsigned ReorderIdx : ReorderIndices)
2354         dbgs() << ReorderIdx << ", ";
2355       dbgs() << "\n";
2356       dbgs() << "UserTreeIndices: ";
2357       for (const auto &EInfo : UserTreeIndices)
2358         dbgs() << EInfo << ", ";
2359       dbgs() << "\n";
2360     }
2361 #endif
2362   };
2363 
2364 #ifndef NDEBUG
2365   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2366                      InstructionCost VecCost,
2367                      InstructionCost ScalarCost) const {
2368     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2369     dbgs() << "SLP: Costs:\n";
2370     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2371     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2372     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2373     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2374                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2375   }
2376 #endif
2377 
2378   /// Create a new VectorizableTree entry.
2379   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2380                           const InstructionsState &S,
2381                           const EdgeInfo &UserTreeIdx,
2382                           ArrayRef<int> ReuseShuffleIndices = None,
2383                           ArrayRef<unsigned> ReorderIndices = None) {
2384     TreeEntry::EntryState EntryState =
2385         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2386     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2387                         ReuseShuffleIndices, ReorderIndices);
2388   }
2389 
2390   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2391                           TreeEntry::EntryState EntryState,
2392                           Optional<ScheduleData *> Bundle,
2393                           const InstructionsState &S,
2394                           const EdgeInfo &UserTreeIdx,
2395                           ArrayRef<int> ReuseShuffleIndices = None,
2396                           ArrayRef<unsigned> ReorderIndices = None) {
2397     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2398             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2399            "Need to vectorize gather entry?");
2400     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2401     TreeEntry *Last = VectorizableTree.back().get();
2402     Last->Idx = VectorizableTree.size() - 1;
2403     Last->State = EntryState;
2404     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2405                                      ReuseShuffleIndices.end());
2406     if (ReorderIndices.empty()) {
2407       Last->Scalars.assign(VL.begin(), VL.end());
2408       Last->setOperations(S);
2409     } else {
2410       // Reorder scalars and build final mask.
2411       Last->Scalars.assign(VL.size(), nullptr);
2412       transform(ReorderIndices, Last->Scalars.begin(),
2413                 [VL](unsigned Idx) -> Value * {
2414                   if (Idx >= VL.size())
2415                     return UndefValue::get(VL.front()->getType());
2416                   return VL[Idx];
2417                 });
2418       InstructionsState S = getSameOpcode(Last->Scalars);
2419       Last->setOperations(S);
2420       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2421     }
2422     if (Last->State != TreeEntry::NeedToGather) {
2423       for (Value *V : VL) {
2424         assert(!getTreeEntry(V) && "Scalar already in tree!");
2425         ScalarToTreeEntry[V] = Last;
2426       }
2427       // Update the scheduler bundle to point to this TreeEntry.
2428       ScheduleData *BundleMember = Bundle.getValue();
2429       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2430               isVectorLikeInstWithConstOps(S.MainOp) ||
2431               doesNotNeedToSchedule(VL)) &&
2432              "Bundle and VL out of sync");
2433       if (BundleMember) {
2434         for (Value *V : VL) {
2435           if (doesNotNeedToBeScheduled(V))
2436             continue;
2437           assert(BundleMember && "Unexpected end of bundle.");
2438           BundleMember->TE = Last;
2439           BundleMember = BundleMember->NextInBundle;
2440         }
2441       }
2442       assert(!BundleMember && "Bundle and VL out of sync");
2443     } else {
2444       MustGather.insert(VL.begin(), VL.end());
2445     }
2446 
2447     if (UserTreeIdx.UserTE)
2448       Last->UserTreeIndices.push_back(UserTreeIdx);
2449 
2450     return Last;
2451   }
2452 
2453   /// -- Vectorization State --
2454   /// Holds all of the tree entries.
2455   TreeEntry::VecTreeTy VectorizableTree;
2456 
2457 #ifndef NDEBUG
2458   /// Debug printer.
2459   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2460     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2461       VectorizableTree[Id]->dump();
2462       dbgs() << "\n";
2463     }
2464   }
2465 #endif
2466 
2467   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2468 
2469   const TreeEntry *getTreeEntry(Value *V) const {
2470     return ScalarToTreeEntry.lookup(V);
2471   }
2472 
2473   /// Maps a specific scalar to its tree entry.
2474   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2475 
2476   /// Maps a value to the proposed vectorizable size.
2477   SmallDenseMap<Value *, unsigned> InstrElementSize;
2478 
2479   /// A list of scalars that we found that we need to keep as scalars.
2480   ValueSet MustGather;
2481 
2482   /// This POD struct describes one external user in the vectorized tree.
2483   struct ExternalUser {
2484     ExternalUser(Value *S, llvm::User *U, int L)
2485         : Scalar(S), User(U), Lane(L) {}
2486 
2487     // Which scalar in our function.
2488     Value *Scalar;
2489 
2490     // Which user that uses the scalar.
2491     llvm::User *User;
2492 
2493     // Which lane does the scalar belong to.
2494     int Lane;
2495   };
2496   using UserList = SmallVector<ExternalUser, 16>;
2497 
2498   /// Checks if two instructions may access the same memory.
2499   ///
2500   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2501   /// is invariant in the calling loop.
2502   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2503                  Instruction *Inst2) {
2504     // First check if the result is already in the cache.
2505     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2506     Optional<bool> &result = AliasCache[key];
2507     if (result.hasValue()) {
2508       return result.getValue();
2509     }
2510     bool aliased = true;
2511     if (Loc1.Ptr && isSimple(Inst1))
2512       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2513     // Store the result in the cache.
2514     result = aliased;
2515     return aliased;
2516   }
2517 
2518   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2519 
2520   /// Cache for alias results.
2521   /// TODO: consider moving this to the AliasAnalysis itself.
2522   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2523 
2524   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2525   // globally through SLP because we don't perform any action which
2526   // invalidates capture results.
2527   BatchAAResults BatchAA;
2528 
2529   /// Temporary store for deleted instructions. Instructions will be deleted
2530   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2531   /// ensure that there are no incorrect collisions in the AliasCache, which
2532   /// can happen if a new instruction is allocated at the same address as a
2533   /// previously deleted instruction.
2534   DenseSet<Instruction *> DeletedInstructions;
2535 
2536   /// A list of values that need to extracted out of the tree.
2537   /// This list holds pairs of (Internal Scalar : External User). External User
2538   /// can be nullptr, it means that this Internal Scalar will be used later,
2539   /// after vectorization.
2540   UserList ExternalUses;
2541 
2542   /// Values used only by @llvm.assume calls.
2543   SmallPtrSet<const Value *, 32> EphValues;
2544 
2545   /// Holds all of the instructions that we gathered.
2546   SetVector<Instruction *> GatherShuffleSeq;
2547 
2548   /// A list of blocks that we are going to CSE.
2549   SetVector<BasicBlock *> CSEBlocks;
2550 
2551   /// Contains all scheduling relevant data for an instruction.
2552   /// A ScheduleData either represents a single instruction or a member of an
2553   /// instruction bundle (= a group of instructions which is combined into a
2554   /// vector instruction).
2555   struct ScheduleData {
2556     // The initial value for the dependency counters. It means that the
2557     // dependencies are not calculated yet.
2558     enum { InvalidDeps = -1 };
2559 
2560     ScheduleData() = default;
2561 
2562     void init(int BlockSchedulingRegionID, Value *OpVal) {
2563       FirstInBundle = this;
2564       NextInBundle = nullptr;
2565       NextLoadStore = nullptr;
2566       IsScheduled = false;
2567       SchedulingRegionID = BlockSchedulingRegionID;
2568       clearDependencies();
2569       OpValue = OpVal;
2570       TE = nullptr;
2571     }
2572 
2573     /// Verify basic self consistency properties
2574     void verify() {
2575       if (hasValidDependencies()) {
2576         assert(UnscheduledDeps <= Dependencies && "invariant");
2577       } else {
2578         assert(UnscheduledDeps == Dependencies && "invariant");
2579       }
2580 
2581       if (IsScheduled) {
2582         assert(isSchedulingEntity() &&
2583                 "unexpected scheduled state");
2584         for (const ScheduleData *BundleMember = this; BundleMember;
2585              BundleMember = BundleMember->NextInBundle) {
2586           assert(BundleMember->hasValidDependencies() &&
2587                  BundleMember->UnscheduledDeps == 0 &&
2588                  "unexpected scheduled state");
2589           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2590                  "only bundle is marked scheduled");
2591         }
2592       }
2593 
2594       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2595              "all bundle members must be in same basic block");
2596     }
2597 
2598     /// Returns true if the dependency information has been calculated.
2599     /// Note that depenendency validity can vary between instructions within
2600     /// a single bundle.
2601     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2602 
2603     /// Returns true for single instructions and for bundle representatives
2604     /// (= the head of a bundle).
2605     bool isSchedulingEntity() const { return FirstInBundle == this; }
2606 
2607     /// Returns true if it represents an instruction bundle and not only a
2608     /// single instruction.
2609     bool isPartOfBundle() const {
2610       return NextInBundle != nullptr || FirstInBundle != this || TE;
2611     }
2612 
2613     /// Returns true if it is ready for scheduling, i.e. it has no more
2614     /// unscheduled depending instructions/bundles.
2615     bool isReady() const {
2616       assert(isSchedulingEntity() &&
2617              "can't consider non-scheduling entity for ready list");
2618       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2619     }
2620 
2621     /// Modifies the number of unscheduled dependencies for this instruction,
2622     /// and returns the number of remaining dependencies for the containing
2623     /// bundle.
2624     int incrementUnscheduledDeps(int Incr) {
2625       assert(hasValidDependencies() &&
2626              "increment of unscheduled deps would be meaningless");
2627       UnscheduledDeps += Incr;
2628       return FirstInBundle->unscheduledDepsInBundle();
2629     }
2630 
2631     /// Sets the number of unscheduled dependencies to the number of
2632     /// dependencies.
2633     void resetUnscheduledDeps() {
2634       UnscheduledDeps = Dependencies;
2635     }
2636 
2637     /// Clears all dependency information.
2638     void clearDependencies() {
2639       Dependencies = InvalidDeps;
2640       resetUnscheduledDeps();
2641       MemoryDependencies.clear();
2642       ControlDependencies.clear();
2643     }
2644 
2645     int unscheduledDepsInBundle() const {
2646       assert(isSchedulingEntity() && "only meaningful on the bundle");
2647       int Sum = 0;
2648       for (const ScheduleData *BundleMember = this; BundleMember;
2649            BundleMember = BundleMember->NextInBundle) {
2650         if (BundleMember->UnscheduledDeps == InvalidDeps)
2651           return InvalidDeps;
2652         Sum += BundleMember->UnscheduledDeps;
2653       }
2654       return Sum;
2655     }
2656 
2657     void dump(raw_ostream &os) const {
2658       if (!isSchedulingEntity()) {
2659         os << "/ " << *Inst;
2660       } else if (NextInBundle) {
2661         os << '[' << *Inst;
2662         ScheduleData *SD = NextInBundle;
2663         while (SD) {
2664           os << ';' << *SD->Inst;
2665           SD = SD->NextInBundle;
2666         }
2667         os << ']';
2668       } else {
2669         os << *Inst;
2670       }
2671     }
2672 
2673     Instruction *Inst = nullptr;
2674 
2675     /// Opcode of the current instruction in the schedule data.
2676     Value *OpValue = nullptr;
2677 
2678     /// The TreeEntry that this instruction corresponds to.
2679     TreeEntry *TE = nullptr;
2680 
2681     /// Points to the head in an instruction bundle (and always to this for
2682     /// single instructions).
2683     ScheduleData *FirstInBundle = nullptr;
2684 
2685     /// Single linked list of all instructions in a bundle. Null if it is a
2686     /// single instruction.
2687     ScheduleData *NextInBundle = nullptr;
2688 
2689     /// Single linked list of all memory instructions (e.g. load, store, call)
2690     /// in the block - until the end of the scheduling region.
2691     ScheduleData *NextLoadStore = nullptr;
2692 
2693     /// The dependent memory instructions.
2694     /// This list is derived on demand in calculateDependencies().
2695     SmallVector<ScheduleData *, 4> MemoryDependencies;
2696 
2697     /// List of instructions which this instruction could be control dependent
2698     /// on.  Allowing such nodes to be scheduled below this one could introduce
2699     /// a runtime fault which didn't exist in the original program.
2700     /// ex: this is a load or udiv following a readonly call which inf loops
2701     SmallVector<ScheduleData *, 4> ControlDependencies;
2702 
2703     /// This ScheduleData is in the current scheduling region if this matches
2704     /// the current SchedulingRegionID of BlockScheduling.
2705     int SchedulingRegionID = 0;
2706 
2707     /// Used for getting a "good" final ordering of instructions.
2708     int SchedulingPriority = 0;
2709 
2710     /// The number of dependencies. Constitutes of the number of users of the
2711     /// instruction plus the number of dependent memory instructions (if any).
2712     /// This value is calculated on demand.
2713     /// If InvalidDeps, the number of dependencies is not calculated yet.
2714     int Dependencies = InvalidDeps;
2715 
2716     /// The number of dependencies minus the number of dependencies of scheduled
2717     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2718     /// for scheduling.
2719     /// Note that this is negative as long as Dependencies is not calculated.
2720     int UnscheduledDeps = InvalidDeps;
2721 
2722     /// True if this instruction is scheduled (or considered as scheduled in the
2723     /// dry-run).
2724     bool IsScheduled = false;
2725   };
2726 
2727 #ifndef NDEBUG
2728   friend inline raw_ostream &operator<<(raw_ostream &os,
2729                                         const BoUpSLP::ScheduleData &SD) {
2730     SD.dump(os);
2731     return os;
2732   }
2733 #endif
2734 
2735   friend struct GraphTraits<BoUpSLP *>;
2736   friend struct DOTGraphTraits<BoUpSLP *>;
2737 
2738   /// Contains all scheduling data for a basic block.
2739   /// It does not schedules instructions, which are not memory read/write
2740   /// instructions and their operands are either constants, or arguments, or
2741   /// phis, or instructions from others blocks, or their users are phis or from
2742   /// the other blocks. The resulting vector instructions can be placed at the
2743   /// beginning of the basic block without scheduling (if operands does not need
2744   /// to be scheduled) or at the end of the block (if users are outside of the
2745   /// block). It allows to save some compile time and memory used by the
2746   /// compiler.
2747   /// ScheduleData is assigned for each instruction in between the boundaries of
2748   /// the tree entry, even for those, which are not part of the graph. It is
2749   /// required to correctly follow the dependencies between the instructions and
2750   /// their correct scheduling. The ScheduleData is not allocated for the
2751   /// instructions, which do not require scheduling, like phis, nodes with
2752   /// extractelements/insertelements only or nodes with instructions, with
2753   /// uses/operands outside of the block.
2754   struct BlockScheduling {
2755     BlockScheduling(BasicBlock *BB)
2756         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2757 
2758     void clear() {
2759       ReadyInsts.clear();
2760       ScheduleStart = nullptr;
2761       ScheduleEnd = nullptr;
2762       FirstLoadStoreInRegion = nullptr;
2763       LastLoadStoreInRegion = nullptr;
2764       RegionHasStackSave = false;
2765 
2766       // Reduce the maximum schedule region size by the size of the
2767       // previous scheduling run.
2768       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2769       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2770         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2771       ScheduleRegionSize = 0;
2772 
2773       // Make a new scheduling region, i.e. all existing ScheduleData is not
2774       // in the new region yet.
2775       ++SchedulingRegionID;
2776     }
2777 
2778     ScheduleData *getScheduleData(Instruction *I) {
2779       if (BB != I->getParent())
2780         // Avoid lookup if can't possibly be in map.
2781         return nullptr;
2782       ScheduleData *SD = ScheduleDataMap.lookup(I);
2783       if (SD && isInSchedulingRegion(SD))
2784         return SD;
2785       return nullptr;
2786     }
2787 
2788     ScheduleData *getScheduleData(Value *V) {
2789       if (auto *I = dyn_cast<Instruction>(V))
2790         return getScheduleData(I);
2791       return nullptr;
2792     }
2793 
2794     ScheduleData *getScheduleData(Value *V, Value *Key) {
2795       if (V == Key)
2796         return getScheduleData(V);
2797       auto I = ExtraScheduleDataMap.find(V);
2798       if (I != ExtraScheduleDataMap.end()) {
2799         ScheduleData *SD = I->second.lookup(Key);
2800         if (SD && isInSchedulingRegion(SD))
2801           return SD;
2802       }
2803       return nullptr;
2804     }
2805 
2806     bool isInSchedulingRegion(ScheduleData *SD) const {
2807       return SD->SchedulingRegionID == SchedulingRegionID;
2808     }
2809 
2810     /// Marks an instruction as scheduled and puts all dependent ready
2811     /// instructions into the ready-list.
2812     template <typename ReadyListType>
2813     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2814       SD->IsScheduled = true;
2815       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2816 
2817       for (ScheduleData *BundleMember = SD; BundleMember;
2818            BundleMember = BundleMember->NextInBundle) {
2819         if (BundleMember->Inst != BundleMember->OpValue)
2820           continue;
2821 
2822         // Handle the def-use chain dependencies.
2823 
2824         // Decrement the unscheduled counter and insert to ready list if ready.
2825         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2826           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2827             if (OpDef && OpDef->hasValidDependencies() &&
2828                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2829               // There are no more unscheduled dependencies after
2830               // decrementing, so we can put the dependent instruction
2831               // into the ready list.
2832               ScheduleData *DepBundle = OpDef->FirstInBundle;
2833               assert(!DepBundle->IsScheduled &&
2834                      "already scheduled bundle gets ready");
2835               ReadyList.insert(DepBundle);
2836               LLVM_DEBUG(dbgs()
2837                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2838             }
2839           });
2840         };
2841 
2842         // If BundleMember is a vector bundle, its operands may have been
2843         // reordered during buildTree(). We therefore need to get its operands
2844         // through the TreeEntry.
2845         if (TreeEntry *TE = BundleMember->TE) {
2846           // Need to search for the lane since the tree entry can be reordered.
2847           int Lane = std::distance(TE->Scalars.begin(),
2848                                    find(TE->Scalars, BundleMember->Inst));
2849           assert(Lane >= 0 && "Lane not set");
2850 
2851           // Since vectorization tree is being built recursively this assertion
2852           // ensures that the tree entry has all operands set before reaching
2853           // this code. Couple of exceptions known at the moment are extracts
2854           // where their second (immediate) operand is not added. Since
2855           // immediates do not affect scheduler behavior this is considered
2856           // okay.
2857           auto *In = BundleMember->Inst;
2858           assert(In &&
2859                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2860                   In->getNumOperands() == TE->getNumOperands()) &&
2861                  "Missed TreeEntry operands?");
2862           (void)In; // fake use to avoid build failure when assertions disabled
2863 
2864           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2865                OpIdx != NumOperands; ++OpIdx)
2866             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2867               DecrUnsched(I);
2868         } else {
2869           // If BundleMember is a stand-alone instruction, no operand reordering
2870           // has taken place, so we directly access its operands.
2871           for (Use &U : BundleMember->Inst->operands())
2872             if (auto *I = dyn_cast<Instruction>(U.get()))
2873               DecrUnsched(I);
2874         }
2875         // Handle the memory dependencies.
2876         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2877           if (MemoryDepSD->hasValidDependencies() &&
2878               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2879             // There are no more unscheduled dependencies after decrementing,
2880             // so we can put the dependent instruction into the ready list.
2881             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2882             assert(!DepBundle->IsScheduled &&
2883                    "already scheduled bundle gets ready");
2884             ReadyList.insert(DepBundle);
2885             LLVM_DEBUG(dbgs()
2886                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2887           }
2888         }
2889         // Handle the control dependencies.
2890         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2891           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2892             // There are no more unscheduled dependencies after decrementing,
2893             // so we can put the dependent instruction into the ready list.
2894             ScheduleData *DepBundle = DepSD->FirstInBundle;
2895             assert(!DepBundle->IsScheduled &&
2896                    "already scheduled bundle gets ready");
2897             ReadyList.insert(DepBundle);
2898             LLVM_DEBUG(dbgs()
2899                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2900           }
2901         }
2902 
2903       }
2904     }
2905 
2906     /// Verify basic self consistency properties of the data structure.
2907     void verify() {
2908       if (!ScheduleStart)
2909         return;
2910 
2911       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2912              ScheduleStart->comesBefore(ScheduleEnd) &&
2913              "Not a valid scheduling region?");
2914 
2915       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2916         auto *SD = getScheduleData(I);
2917         if (!SD)
2918           continue;
2919         assert(isInSchedulingRegion(SD) &&
2920                "primary schedule data not in window?");
2921         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2922                "entire bundle in window!");
2923         (void)SD;
2924         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2925       }
2926 
2927       for (auto *SD : ReadyInsts) {
2928         assert(SD->isSchedulingEntity() && SD->isReady() &&
2929                "item in ready list not ready?");
2930         (void)SD;
2931       }
2932     }
2933 
2934     void doForAllOpcodes(Value *V,
2935                          function_ref<void(ScheduleData *SD)> Action) {
2936       if (ScheduleData *SD = getScheduleData(V))
2937         Action(SD);
2938       auto I = ExtraScheduleDataMap.find(V);
2939       if (I != ExtraScheduleDataMap.end())
2940         for (auto &P : I->second)
2941           if (isInSchedulingRegion(P.second))
2942             Action(P.second);
2943     }
2944 
2945     /// Put all instructions into the ReadyList which are ready for scheduling.
2946     template <typename ReadyListType>
2947     void initialFillReadyList(ReadyListType &ReadyList) {
2948       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2949         doForAllOpcodes(I, [&](ScheduleData *SD) {
2950           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2951               SD->isReady()) {
2952             ReadyList.insert(SD);
2953             LLVM_DEBUG(dbgs()
2954                        << "SLP:    initially in ready list: " << *SD << "\n");
2955           }
2956         });
2957       }
2958     }
2959 
2960     /// Build a bundle from the ScheduleData nodes corresponding to the
2961     /// scalar instruction for each lane.
2962     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2963 
2964     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2965     /// cyclic dependencies. This is only a dry-run, no instructions are
2966     /// actually moved at this stage.
2967     /// \returns the scheduling bundle. The returned Optional value is non-None
2968     /// if \p VL is allowed to be scheduled.
2969     Optional<ScheduleData *>
2970     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2971                       const InstructionsState &S);
2972 
2973     /// Un-bundles a group of instructions.
2974     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2975 
2976     /// Allocates schedule data chunk.
2977     ScheduleData *allocateScheduleDataChunks();
2978 
2979     /// Extends the scheduling region so that V is inside the region.
2980     /// \returns true if the region size is within the limit.
2981     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2982 
2983     /// Initialize the ScheduleData structures for new instructions in the
2984     /// scheduling region.
2985     void initScheduleData(Instruction *FromI, Instruction *ToI,
2986                           ScheduleData *PrevLoadStore,
2987                           ScheduleData *NextLoadStore);
2988 
2989     /// Updates the dependency information of a bundle and of all instructions/
2990     /// bundles which depend on the original bundle.
2991     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2992                                BoUpSLP *SLP);
2993 
2994     /// Sets all instruction in the scheduling region to un-scheduled.
2995     void resetSchedule();
2996 
2997     BasicBlock *BB;
2998 
2999     /// Simple memory allocation for ScheduleData.
3000     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3001 
3002     /// The size of a ScheduleData array in ScheduleDataChunks.
3003     int ChunkSize;
3004 
3005     /// The allocator position in the current chunk, which is the last entry
3006     /// of ScheduleDataChunks.
3007     int ChunkPos;
3008 
3009     /// Attaches ScheduleData to Instruction.
3010     /// Note that the mapping survives during all vectorization iterations, i.e.
3011     /// ScheduleData structures are recycled.
3012     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3013 
3014     /// Attaches ScheduleData to Instruction with the leading key.
3015     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3016         ExtraScheduleDataMap;
3017 
3018     /// The ready-list for scheduling (only used for the dry-run).
3019     SetVector<ScheduleData *> ReadyInsts;
3020 
3021     /// The first instruction of the scheduling region.
3022     Instruction *ScheduleStart = nullptr;
3023 
3024     /// The first instruction _after_ the scheduling region.
3025     Instruction *ScheduleEnd = nullptr;
3026 
3027     /// The first memory accessing instruction in the scheduling region
3028     /// (can be null).
3029     ScheduleData *FirstLoadStoreInRegion = nullptr;
3030 
3031     /// The last memory accessing instruction in the scheduling region
3032     /// (can be null).
3033     ScheduleData *LastLoadStoreInRegion = nullptr;
3034 
3035     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3036     /// region?  Used to optimize the dependence calculation for the
3037     /// common case where there isn't.
3038     bool RegionHasStackSave = false;
3039 
3040     /// The current size of the scheduling region.
3041     int ScheduleRegionSize = 0;
3042 
3043     /// The maximum size allowed for the scheduling region.
3044     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3045 
3046     /// The ID of the scheduling region. For a new vectorization iteration this
3047     /// is incremented which "removes" all ScheduleData from the region.
3048     /// Make sure that the initial SchedulingRegionID is greater than the
3049     /// initial SchedulingRegionID in ScheduleData (which is 0).
3050     int SchedulingRegionID = 1;
3051   };
3052 
3053   /// Attaches the BlockScheduling structures to basic blocks.
3054   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3055 
3056   /// Performs the "real" scheduling. Done before vectorization is actually
3057   /// performed in a basic block.
3058   void scheduleBlock(BlockScheduling *BS);
3059 
3060   /// List of users to ignore during scheduling and that don't need extracting.
3061   ArrayRef<Value *> UserIgnoreList;
3062 
3063   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3064   /// sorted SmallVectors of unsigned.
3065   struct OrdersTypeDenseMapInfo {
3066     static OrdersType getEmptyKey() {
3067       OrdersType V;
3068       V.push_back(~1U);
3069       return V;
3070     }
3071 
3072     static OrdersType getTombstoneKey() {
3073       OrdersType V;
3074       V.push_back(~2U);
3075       return V;
3076     }
3077 
3078     static unsigned getHashValue(const OrdersType &V) {
3079       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3080     }
3081 
3082     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3083       return LHS == RHS;
3084     }
3085   };
3086 
3087   // Analysis and block reference.
3088   Function *F;
3089   ScalarEvolution *SE;
3090   TargetTransformInfo *TTI;
3091   TargetLibraryInfo *TLI;
3092   LoopInfo *LI;
3093   DominatorTree *DT;
3094   AssumptionCache *AC;
3095   DemandedBits *DB;
3096   const DataLayout *DL;
3097   OptimizationRemarkEmitter *ORE;
3098 
3099   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3100   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3101 
3102   /// Instruction builder to construct the vectorized tree.
3103   IRBuilder<> Builder;
3104 
3105   /// A map of scalar integer values to the smallest bit width with which they
3106   /// can legally be represented. The values map to (width, signed) pairs,
3107   /// where "width" indicates the minimum bit width and "signed" is True if the
3108   /// value must be signed-extended, rather than zero-extended, back to its
3109   /// original width.
3110   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3111 };
3112 
3113 } // end namespace slpvectorizer
3114 
3115 template <> struct GraphTraits<BoUpSLP *> {
3116   using TreeEntry = BoUpSLP::TreeEntry;
3117 
3118   /// NodeRef has to be a pointer per the GraphWriter.
3119   using NodeRef = TreeEntry *;
3120 
3121   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3122 
3123   /// Add the VectorizableTree to the index iterator to be able to return
3124   /// TreeEntry pointers.
3125   struct ChildIteratorType
3126       : public iterator_adaptor_base<
3127             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3128     ContainerTy &VectorizableTree;
3129 
3130     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3131                       ContainerTy &VT)
3132         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3133 
3134     NodeRef operator*() { return I->UserTE; }
3135   };
3136 
3137   static NodeRef getEntryNode(BoUpSLP &R) {
3138     return R.VectorizableTree[0].get();
3139   }
3140 
3141   static ChildIteratorType child_begin(NodeRef N) {
3142     return {N->UserTreeIndices.begin(), N->Container};
3143   }
3144 
3145   static ChildIteratorType child_end(NodeRef N) {
3146     return {N->UserTreeIndices.end(), N->Container};
3147   }
3148 
3149   /// For the node iterator we just need to turn the TreeEntry iterator into a
3150   /// TreeEntry* iterator so that it dereferences to NodeRef.
3151   class nodes_iterator {
3152     using ItTy = ContainerTy::iterator;
3153     ItTy It;
3154 
3155   public:
3156     nodes_iterator(const ItTy &It2) : It(It2) {}
3157     NodeRef operator*() { return It->get(); }
3158     nodes_iterator operator++() {
3159       ++It;
3160       return *this;
3161     }
3162     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3163   };
3164 
3165   static nodes_iterator nodes_begin(BoUpSLP *R) {
3166     return nodes_iterator(R->VectorizableTree.begin());
3167   }
3168 
3169   static nodes_iterator nodes_end(BoUpSLP *R) {
3170     return nodes_iterator(R->VectorizableTree.end());
3171   }
3172 
3173   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3174 };
3175 
3176 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3177   using TreeEntry = BoUpSLP::TreeEntry;
3178 
3179   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3180 
3181   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3182     std::string Str;
3183     raw_string_ostream OS(Str);
3184     if (isSplat(Entry->Scalars))
3185       OS << "<splat> ";
3186     for (auto V : Entry->Scalars) {
3187       OS << *V;
3188       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3189             return EU.Scalar == V;
3190           }))
3191         OS << " <extract>";
3192       OS << "\n";
3193     }
3194     return Str;
3195   }
3196 
3197   static std::string getNodeAttributes(const TreeEntry *Entry,
3198                                        const BoUpSLP *) {
3199     if (Entry->State == TreeEntry::NeedToGather)
3200       return "color=red";
3201     return "";
3202   }
3203 };
3204 
3205 } // end namespace llvm
3206 
3207 BoUpSLP::~BoUpSLP() {
3208   SmallVector<WeakTrackingVH> DeadInsts;
3209   for (auto *I : DeletedInstructions) {
3210     for (Use &U : I->operands()) {
3211       auto *Op = dyn_cast<Instruction>(U.get());
3212       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3213           wouldInstructionBeTriviallyDead(Op, TLI))
3214         DeadInsts.emplace_back(Op);
3215     }
3216     I->dropAllReferences();
3217   }
3218   for (auto *I : DeletedInstructions) {
3219     assert(I->use_empty() &&
3220            "trying to erase instruction with users.");
3221     I->eraseFromParent();
3222   }
3223 
3224   // Cleanup any dead scalar code feeding the vectorized instructions
3225   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3226 
3227 #ifdef EXPENSIVE_CHECKS
3228   // If we could guarantee that this call is not extremely slow, we could
3229   // remove the ifdef limitation (see PR47712).
3230   assert(!verifyFunction(*F, &dbgs()));
3231 #endif
3232 }
3233 
3234 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3235 /// contains original mask for the scalars reused in the node. Procedure
3236 /// transform this mask in accordance with the given \p Mask.
3237 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3238   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3239          "Expected non-empty mask.");
3240   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3241   Prev.swap(Reuses);
3242   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3243     if (Mask[I] != UndefMaskElem)
3244       Reuses[Mask[I]] = Prev[I];
3245 }
3246 
3247 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3248 /// the original order of the scalars. Procedure transforms the provided order
3249 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3250 /// identity order, \p Order is cleared.
3251 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3252   assert(!Mask.empty() && "Expected non-empty mask.");
3253   SmallVector<int> MaskOrder;
3254   if (Order.empty()) {
3255     MaskOrder.resize(Mask.size());
3256     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3257   } else {
3258     inversePermutation(Order, MaskOrder);
3259   }
3260   reorderReuses(MaskOrder, Mask);
3261   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3262     Order.clear();
3263     return;
3264   }
3265   Order.assign(Mask.size(), Mask.size());
3266   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3267     if (MaskOrder[I] != UndefMaskElem)
3268       Order[MaskOrder[I]] = I;
3269   fixupOrderingIndices(Order);
3270 }
3271 
3272 Optional<BoUpSLP::OrdersType>
3273 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3274   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3275   unsigned NumScalars = TE.Scalars.size();
3276   OrdersType CurrentOrder(NumScalars, NumScalars);
3277   SmallVector<int> Positions;
3278   SmallBitVector UsedPositions(NumScalars);
3279   const TreeEntry *STE = nullptr;
3280   // Try to find all gathered scalars that are gets vectorized in other
3281   // vectorize node. Here we can have only one single tree vector node to
3282   // correctly identify order of the gathered scalars.
3283   for (unsigned I = 0; I < NumScalars; ++I) {
3284     Value *V = TE.Scalars[I];
3285     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3286       continue;
3287     if (const auto *LocalSTE = getTreeEntry(V)) {
3288       if (!STE)
3289         STE = LocalSTE;
3290       else if (STE != LocalSTE)
3291         // Take the order only from the single vector node.
3292         return None;
3293       unsigned Lane =
3294           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3295       if (Lane >= NumScalars)
3296         return None;
3297       if (CurrentOrder[Lane] != NumScalars) {
3298         if (Lane != I)
3299           continue;
3300         UsedPositions.reset(CurrentOrder[Lane]);
3301       }
3302       // The partial identity (where only some elements of the gather node are
3303       // in the identity order) is good.
3304       CurrentOrder[Lane] = I;
3305       UsedPositions.set(I);
3306     }
3307   }
3308   // Need to keep the order if we have a vector entry and at least 2 scalars or
3309   // the vectorized entry has just 2 scalars.
3310   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3311     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3312       for (unsigned I = 0; I < NumScalars; ++I)
3313         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3314           return false;
3315       return true;
3316     };
3317     if (IsIdentityOrder(CurrentOrder)) {
3318       CurrentOrder.clear();
3319       return CurrentOrder;
3320     }
3321     auto *It = CurrentOrder.begin();
3322     for (unsigned I = 0; I < NumScalars;) {
3323       if (UsedPositions.test(I)) {
3324         ++I;
3325         continue;
3326       }
3327       if (*It == NumScalars) {
3328         *It = I;
3329         ++I;
3330       }
3331       ++It;
3332     }
3333     return CurrentOrder;
3334   }
3335   return None;
3336 }
3337 
3338 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3339                                                          bool TopToBottom) {
3340   // No need to reorder if need to shuffle reuses, still need to shuffle the
3341   // node.
3342   if (!TE.ReuseShuffleIndices.empty())
3343     return None;
3344   if (TE.State == TreeEntry::Vectorize &&
3345       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3346        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3347       !TE.isAltShuffle())
3348     return TE.ReorderIndices;
3349   if (TE.State == TreeEntry::NeedToGather) {
3350     // TODO: add analysis of other gather nodes with extractelement
3351     // instructions and other values/instructions, not only undefs.
3352     if (((TE.getOpcode() == Instruction::ExtractElement &&
3353           !TE.isAltShuffle()) ||
3354          (all_of(TE.Scalars,
3355                  [](Value *V) {
3356                    return isa<UndefValue, ExtractElementInst>(V);
3357                  }) &&
3358           any_of(TE.Scalars,
3359                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3360         all_of(TE.Scalars,
3361                [](Value *V) {
3362                  auto *EE = dyn_cast<ExtractElementInst>(V);
3363                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3364                }) &&
3365         allSameType(TE.Scalars)) {
3366       // Check that gather of extractelements can be represented as
3367       // just a shuffle of a single vector.
3368       OrdersType CurrentOrder;
3369       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3370       if (Reuse || !CurrentOrder.empty()) {
3371         if (!CurrentOrder.empty())
3372           fixupOrderingIndices(CurrentOrder);
3373         return CurrentOrder;
3374       }
3375     }
3376     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3377       return CurrentOrder;
3378   }
3379   return None;
3380 }
3381 
3382 void BoUpSLP::reorderTopToBottom() {
3383   // Maps VF to the graph nodes.
3384   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3385   // ExtractElement gather nodes which can be vectorized and need to handle
3386   // their ordering.
3387   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3388   // Find all reorderable nodes with the given VF.
3389   // Currently the are vectorized stores,loads,extracts + some gathering of
3390   // extracts.
3391   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3392                                  const std::unique_ptr<TreeEntry> &TE) {
3393     if (Optional<OrdersType> CurrentOrder =
3394             getReorderingData(*TE, /*TopToBottom=*/true)) {
3395       // Do not include ordering for nodes used in the alt opcode vectorization,
3396       // better to reorder them during bottom-to-top stage. If follow the order
3397       // here, it causes reordering of the whole graph though actually it is
3398       // profitable just to reorder the subgraph that starts from the alternate
3399       // opcode vectorization node. Such nodes already end-up with the shuffle
3400       // instruction and it is just enough to change this shuffle rather than
3401       // rotate the scalars for the whole graph.
3402       unsigned Cnt = 0;
3403       const TreeEntry *UserTE = TE.get();
3404       while (UserTE && Cnt < RecursionMaxDepth) {
3405         if (UserTE->UserTreeIndices.size() != 1)
3406           break;
3407         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3408               return EI.UserTE->State == TreeEntry::Vectorize &&
3409                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3410             }))
3411           return;
3412         if (UserTE->UserTreeIndices.empty())
3413           UserTE = nullptr;
3414         else
3415           UserTE = UserTE->UserTreeIndices.back().UserTE;
3416         ++Cnt;
3417       }
3418       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3419       if (TE->State != TreeEntry::Vectorize)
3420         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3421     }
3422   });
3423 
3424   // Reorder the graph nodes according to their vectorization factor.
3425   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3426        VF /= 2) {
3427     auto It = VFToOrderedEntries.find(VF);
3428     if (It == VFToOrderedEntries.end())
3429       continue;
3430     // Try to find the most profitable order. We just are looking for the most
3431     // used order and reorder scalar elements in the nodes according to this
3432     // mostly used order.
3433     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3434     // All operands are reordered and used only in this node - propagate the
3435     // most used order to the user node.
3436     MapVector<OrdersType, unsigned,
3437               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3438         OrdersUses;
3439     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3440     for (const TreeEntry *OpTE : OrderedEntries) {
3441       // No need to reorder this nodes, still need to extend and to use shuffle,
3442       // just need to merge reordering shuffle and the reuse shuffle.
3443       if (!OpTE->ReuseShuffleIndices.empty())
3444         continue;
3445       // Count number of orders uses.
3446       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3447         if (OpTE->State == TreeEntry::NeedToGather)
3448           return GathersToOrders.find(OpTE)->second;
3449         return OpTE->ReorderIndices;
3450       }();
3451       // Stores actually store the mask, not the order, need to invert.
3452       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3453           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3454         SmallVector<int> Mask;
3455         inversePermutation(Order, Mask);
3456         unsigned E = Order.size();
3457         OrdersType CurrentOrder(E, E);
3458         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3459           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3460         });
3461         fixupOrderingIndices(CurrentOrder);
3462         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3463       } else {
3464         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3465       }
3466     }
3467     // Set order of the user node.
3468     if (OrdersUses.empty())
3469       continue;
3470     // Choose the most used order.
3471     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3472     unsigned Cnt = OrdersUses.front().second;
3473     for (const auto &Pair : drop_begin(OrdersUses)) {
3474       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3475         BestOrder = Pair.first;
3476         Cnt = Pair.second;
3477       }
3478     }
3479     // Set order of the user node.
3480     if (BestOrder.empty())
3481       continue;
3482     SmallVector<int> Mask;
3483     inversePermutation(BestOrder, Mask);
3484     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3485     unsigned E = BestOrder.size();
3486     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3487       return I < E ? static_cast<int>(I) : UndefMaskElem;
3488     });
3489     // Do an actual reordering, if profitable.
3490     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3491       // Just do the reordering for the nodes with the given VF.
3492       if (TE->Scalars.size() != VF) {
3493         if (TE->ReuseShuffleIndices.size() == VF) {
3494           // Need to reorder the reuses masks of the operands with smaller VF to
3495           // be able to find the match between the graph nodes and scalar
3496           // operands of the given node during vectorization/cost estimation.
3497           assert(all_of(TE->UserTreeIndices,
3498                         [VF, &TE](const EdgeInfo &EI) {
3499                           return EI.UserTE->Scalars.size() == VF ||
3500                                  EI.UserTE->Scalars.size() ==
3501                                      TE->Scalars.size();
3502                         }) &&
3503                  "All users must be of VF size.");
3504           // Update ordering of the operands with the smaller VF than the given
3505           // one.
3506           reorderReuses(TE->ReuseShuffleIndices, Mask);
3507         }
3508         continue;
3509       }
3510       if (TE->State == TreeEntry::Vectorize &&
3511           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3512               InsertElementInst>(TE->getMainOp()) &&
3513           !TE->isAltShuffle()) {
3514         // Build correct orders for extract{element,value}, loads and
3515         // stores.
3516         reorderOrder(TE->ReorderIndices, Mask);
3517         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3518           TE->reorderOperands(Mask);
3519       } else {
3520         // Reorder the node and its operands.
3521         TE->reorderOperands(Mask);
3522         assert(TE->ReorderIndices.empty() &&
3523                "Expected empty reorder sequence.");
3524         reorderScalars(TE->Scalars, Mask);
3525       }
3526       if (!TE->ReuseShuffleIndices.empty()) {
3527         // Apply reversed order to keep the original ordering of the reused
3528         // elements to avoid extra reorder indices shuffling.
3529         OrdersType CurrentOrder;
3530         reorderOrder(CurrentOrder, MaskOrder);
3531         SmallVector<int> NewReuses;
3532         inversePermutation(CurrentOrder, NewReuses);
3533         addMask(NewReuses, TE->ReuseShuffleIndices);
3534         TE->ReuseShuffleIndices.swap(NewReuses);
3535       }
3536     }
3537   }
3538 }
3539 
3540 bool BoUpSLP::canReorderOperands(
3541     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3542     ArrayRef<TreeEntry *> ReorderableGathers,
3543     SmallVectorImpl<TreeEntry *> &GatherOps) {
3544   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3545     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3546           return OpData.first == I &&
3547                  OpData.second->State == TreeEntry::Vectorize;
3548         }))
3549       continue;
3550     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3551       // Do not reorder if operand node is used by many user nodes.
3552       if (any_of(TE->UserTreeIndices,
3553                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3554         return false;
3555       // Add the node to the list of the ordered nodes with the identity
3556       // order.
3557       Edges.emplace_back(I, TE);
3558       continue;
3559     }
3560     ArrayRef<Value *> VL = UserTE->getOperand(I);
3561     TreeEntry *Gather = nullptr;
3562     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3563           assert(TE->State != TreeEntry::Vectorize &&
3564                  "Only non-vectorized nodes are expected.");
3565           if (TE->isSame(VL)) {
3566             Gather = TE;
3567             return true;
3568           }
3569           return false;
3570         }) > 1)
3571       return false;
3572     if (Gather)
3573       GatherOps.push_back(Gather);
3574   }
3575   return true;
3576 }
3577 
3578 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3579   SetVector<TreeEntry *> OrderedEntries;
3580   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3581   // Find all reorderable leaf nodes with the given VF.
3582   // Currently the are vectorized loads,extracts without alternate operands +
3583   // some gathering of extracts.
3584   SmallVector<TreeEntry *> NonVectorized;
3585   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3586                               &NonVectorized](
3587                                  const std::unique_ptr<TreeEntry> &TE) {
3588     if (TE->State != TreeEntry::Vectorize)
3589       NonVectorized.push_back(TE.get());
3590     if (Optional<OrdersType> CurrentOrder =
3591             getReorderingData(*TE, /*TopToBottom=*/false)) {
3592       OrderedEntries.insert(TE.get());
3593       if (TE->State != TreeEntry::Vectorize)
3594         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3595     }
3596   });
3597 
3598   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3599   // I.e., if the node has operands, that are reordered, try to make at least
3600   // one operand order in the natural order and reorder others + reorder the
3601   // user node itself.
3602   SmallPtrSet<const TreeEntry *, 4> Visited;
3603   while (!OrderedEntries.empty()) {
3604     // 1. Filter out only reordered nodes.
3605     // 2. If the entry has multiple uses - skip it and jump to the next node.
3606     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3607     SmallVector<TreeEntry *> Filtered;
3608     for (TreeEntry *TE : OrderedEntries) {
3609       if (!(TE->State == TreeEntry::Vectorize ||
3610             (TE->State == TreeEntry::NeedToGather &&
3611              GathersToOrders.count(TE))) ||
3612           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3613           !all_of(drop_begin(TE->UserTreeIndices),
3614                   [TE](const EdgeInfo &EI) {
3615                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3616                   }) ||
3617           !Visited.insert(TE).second) {
3618         Filtered.push_back(TE);
3619         continue;
3620       }
3621       // Build a map between user nodes and their operands order to speedup
3622       // search. The graph currently does not provide this dependency directly.
3623       for (EdgeInfo &EI : TE->UserTreeIndices) {
3624         TreeEntry *UserTE = EI.UserTE;
3625         auto It = Users.find(UserTE);
3626         if (It == Users.end())
3627           It = Users.insert({UserTE, {}}).first;
3628         It->second.emplace_back(EI.EdgeIdx, TE);
3629       }
3630     }
3631     // Erase filtered entries.
3632     for_each(Filtered,
3633              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3634     for (auto &Data : Users) {
3635       // Check that operands are used only in the User node.
3636       SmallVector<TreeEntry *> GatherOps;
3637       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3638                               GatherOps)) {
3639         for_each(Data.second,
3640                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3641                    OrderedEntries.remove(Op.second);
3642                  });
3643         continue;
3644       }
3645       // All operands are reordered and used only in this node - propagate the
3646       // most used order to the user node.
3647       MapVector<OrdersType, unsigned,
3648                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3649           OrdersUses;
3650       // Do the analysis for each tree entry only once, otherwise the order of
3651       // the same node my be considered several times, though might be not
3652       // profitable.
3653       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3654       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3655       for (const auto &Op : Data.second) {
3656         TreeEntry *OpTE = Op.second;
3657         if (!VisitedOps.insert(OpTE).second)
3658           continue;
3659         if (!OpTE->ReuseShuffleIndices.empty() ||
3660             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3661           continue;
3662         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3663           if (OpTE->State == TreeEntry::NeedToGather)
3664             return GathersToOrders.find(OpTE)->second;
3665           return OpTE->ReorderIndices;
3666         }();
3667         unsigned NumOps = count_if(
3668             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3669               return P.second == OpTE;
3670             });
3671         // Stores actually store the mask, not the order, need to invert.
3672         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3673             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3674           SmallVector<int> Mask;
3675           inversePermutation(Order, Mask);
3676           unsigned E = Order.size();
3677           OrdersType CurrentOrder(E, E);
3678           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3679             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3680           });
3681           fixupOrderingIndices(CurrentOrder);
3682           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3683               NumOps;
3684         } else {
3685           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3686         }
3687         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3688         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3689                                             const TreeEntry *TE) {
3690           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3691               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3692               (IgnoreReorder && TE->Idx == 0))
3693             return true;
3694           if (TE->State == TreeEntry::NeedToGather) {
3695             auto It = GathersToOrders.find(TE);
3696             if (It != GathersToOrders.end())
3697               return !It->second.empty();
3698             return true;
3699           }
3700           return false;
3701         };
3702         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3703           TreeEntry *UserTE = EI.UserTE;
3704           if (!VisitedUsers.insert(UserTE).second)
3705             continue;
3706           // May reorder user node if it requires reordering, has reused
3707           // scalars, is an alternate op vectorize node or its op nodes require
3708           // reordering.
3709           if (AllowsReordering(UserTE))
3710             continue;
3711           // Check if users allow reordering.
3712           // Currently look up just 1 level of operands to avoid increase of
3713           // the compile time.
3714           // Profitable to reorder if definitely more operands allow
3715           // reordering rather than those with natural order.
3716           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3717           if (static_cast<unsigned>(count_if(
3718                   Ops, [UserTE, &AllowsReordering](
3719                            const std::pair<unsigned, TreeEntry *> &Op) {
3720                     return AllowsReordering(Op.second) &&
3721                            all_of(Op.second->UserTreeIndices,
3722                                   [UserTE](const EdgeInfo &EI) {
3723                                     return EI.UserTE == UserTE;
3724                                   });
3725                   })) <= Ops.size() / 2)
3726             ++Res.first->second;
3727         }
3728       }
3729       // If no orders - skip current nodes and jump to the next one, if any.
3730       if (OrdersUses.empty()) {
3731         for_each(Data.second,
3732                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3733                    OrderedEntries.remove(Op.second);
3734                  });
3735         continue;
3736       }
3737       // Choose the best order.
3738       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3739       unsigned Cnt = OrdersUses.front().second;
3740       for (const auto &Pair : drop_begin(OrdersUses)) {
3741         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3742           BestOrder = Pair.first;
3743           Cnt = Pair.second;
3744         }
3745       }
3746       // Set order of the user node (reordering of operands and user nodes).
3747       if (BestOrder.empty()) {
3748         for_each(Data.second,
3749                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3750                    OrderedEntries.remove(Op.second);
3751                  });
3752         continue;
3753       }
3754       // Erase operands from OrderedEntries list and adjust their orders.
3755       VisitedOps.clear();
3756       SmallVector<int> Mask;
3757       inversePermutation(BestOrder, Mask);
3758       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3759       unsigned E = BestOrder.size();
3760       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3761         return I < E ? static_cast<int>(I) : UndefMaskElem;
3762       });
3763       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3764         TreeEntry *TE = Op.second;
3765         OrderedEntries.remove(TE);
3766         if (!VisitedOps.insert(TE).second)
3767           continue;
3768         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3769           // Just reorder reuses indices.
3770           reorderReuses(TE->ReuseShuffleIndices, Mask);
3771           continue;
3772         }
3773         // Gathers are processed separately.
3774         if (TE->State != TreeEntry::Vectorize)
3775           continue;
3776         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3777                 TE->ReorderIndices.empty()) &&
3778                "Non-matching sizes of user/operand entries.");
3779         reorderOrder(TE->ReorderIndices, Mask);
3780       }
3781       // For gathers just need to reorder its scalars.
3782       for (TreeEntry *Gather : GatherOps) {
3783         assert(Gather->ReorderIndices.empty() &&
3784                "Unexpected reordering of gathers.");
3785         if (!Gather->ReuseShuffleIndices.empty()) {
3786           // Just reorder reuses indices.
3787           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3788           continue;
3789         }
3790         reorderScalars(Gather->Scalars, Mask);
3791         OrderedEntries.remove(Gather);
3792       }
3793       // Reorder operands of the user node and set the ordering for the user
3794       // node itself.
3795       if (Data.first->State != TreeEntry::Vectorize ||
3796           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3797               Data.first->getMainOp()) ||
3798           Data.first->isAltShuffle())
3799         Data.first->reorderOperands(Mask);
3800       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3801           Data.first->isAltShuffle()) {
3802         reorderScalars(Data.first->Scalars, Mask);
3803         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3804         if (Data.first->ReuseShuffleIndices.empty() &&
3805             !Data.first->ReorderIndices.empty() &&
3806             !Data.first->isAltShuffle()) {
3807           // Insert user node to the list to try to sink reordering deeper in
3808           // the graph.
3809           OrderedEntries.insert(Data.first);
3810         }
3811       } else {
3812         reorderOrder(Data.first->ReorderIndices, Mask);
3813       }
3814     }
3815   }
3816   // If the reordering is unnecessary, just remove the reorder.
3817   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3818       VectorizableTree.front()->ReuseShuffleIndices.empty())
3819     VectorizableTree.front()->ReorderIndices.clear();
3820 }
3821 
3822 void BoUpSLP::buildExternalUses(
3823     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3824   // Collect the values that we need to extract from the tree.
3825   for (auto &TEPtr : VectorizableTree) {
3826     TreeEntry *Entry = TEPtr.get();
3827 
3828     // No need to handle users of gathered values.
3829     if (Entry->State == TreeEntry::NeedToGather)
3830       continue;
3831 
3832     // For each lane:
3833     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3834       Value *Scalar = Entry->Scalars[Lane];
3835       int FoundLane = Entry->findLaneForValue(Scalar);
3836 
3837       // Check if the scalar is externally used as an extra arg.
3838       auto ExtI = ExternallyUsedValues.find(Scalar);
3839       if (ExtI != ExternallyUsedValues.end()) {
3840         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3841                           << Lane << " from " << *Scalar << ".\n");
3842         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3843       }
3844       for (User *U : Scalar->users()) {
3845         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3846 
3847         Instruction *UserInst = dyn_cast<Instruction>(U);
3848         if (!UserInst)
3849           continue;
3850 
3851         if (isDeleted(UserInst))
3852           continue;
3853 
3854         // Skip in-tree scalars that become vectors
3855         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3856           Value *UseScalar = UseEntry->Scalars[0];
3857           // Some in-tree scalars will remain as scalar in vectorized
3858           // instructions. If that is the case, the one in Lane 0 will
3859           // be used.
3860           if (UseScalar != U ||
3861               UseEntry->State == TreeEntry::ScatterVectorize ||
3862               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3863             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3864                               << ".\n");
3865             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3866             continue;
3867           }
3868         }
3869 
3870         // Ignore users in the user ignore list.
3871         if (is_contained(UserIgnoreList, UserInst))
3872           continue;
3873 
3874         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3875                           << Lane << " from " << *Scalar << ".\n");
3876         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3877       }
3878     }
3879   }
3880 }
3881 
3882 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3883                         ArrayRef<Value *> UserIgnoreLst) {
3884   deleteTree();
3885   UserIgnoreList = UserIgnoreLst;
3886   if (!allSameType(Roots))
3887     return;
3888   buildTree_rec(Roots, 0, EdgeInfo());
3889 }
3890 
3891 namespace {
3892 /// Tracks the state we can represent the loads in the given sequence.
3893 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3894 } // anonymous namespace
3895 
3896 /// Checks if the given array of loads can be represented as a vectorized,
3897 /// scatter or just simple gather.
3898 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3899                                     const TargetTransformInfo &TTI,
3900                                     const DataLayout &DL, ScalarEvolution &SE,
3901                                     SmallVectorImpl<unsigned> &Order,
3902                                     SmallVectorImpl<Value *> &PointerOps) {
3903   // Check that a vectorized load would load the same memory as a scalar
3904   // load. For example, we don't want to vectorize loads that are smaller
3905   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3906   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3907   // from such a struct, we read/write packed bits disagreeing with the
3908   // unvectorized version.
3909   Type *ScalarTy = VL0->getType();
3910 
3911   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3912     return LoadsState::Gather;
3913 
3914   // Make sure all loads in the bundle are simple - we can't vectorize
3915   // atomic or volatile loads.
3916   PointerOps.clear();
3917   PointerOps.resize(VL.size());
3918   auto *POIter = PointerOps.begin();
3919   for (Value *V : VL) {
3920     auto *L = cast<LoadInst>(V);
3921     if (!L->isSimple())
3922       return LoadsState::Gather;
3923     *POIter = L->getPointerOperand();
3924     ++POIter;
3925   }
3926 
3927   Order.clear();
3928   // Check the order of pointer operands.
3929   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3930     Value *Ptr0;
3931     Value *PtrN;
3932     if (Order.empty()) {
3933       Ptr0 = PointerOps.front();
3934       PtrN = PointerOps.back();
3935     } else {
3936       Ptr0 = PointerOps[Order.front()];
3937       PtrN = PointerOps[Order.back()];
3938     }
3939     Optional<int> Diff =
3940         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3941     // Check that the sorted loads are consecutive.
3942     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3943       return LoadsState::Vectorize;
3944     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3945     for (Value *V : VL)
3946       CommonAlignment =
3947           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3948     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3949                                 CommonAlignment))
3950       return LoadsState::ScatterVectorize;
3951   }
3952 
3953   return LoadsState::Gather;
3954 }
3955 
3956 /// \return true if the specified list of values has only one instruction that
3957 /// requires scheduling, false otherwise.
3958 #ifndef NDEBUG
3959 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3960   Value *NeedsScheduling = nullptr;
3961   for (Value *V : VL) {
3962     if (doesNotNeedToBeScheduled(V))
3963       continue;
3964     if (!NeedsScheduling) {
3965       NeedsScheduling = V;
3966       continue;
3967     }
3968     return false;
3969   }
3970   return NeedsScheduling;
3971 }
3972 #endif
3973 
3974 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3975                             const EdgeInfo &UserTreeIdx) {
3976   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3977 
3978   SmallVector<int> ReuseShuffleIndicies;
3979   SmallVector<Value *> UniqueValues;
3980   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3981                                 &UserTreeIdx,
3982                                 this](const InstructionsState &S) {
3983     // Check that every instruction appears once in this bundle.
3984     DenseMap<Value *, unsigned> UniquePositions;
3985     for (Value *V : VL) {
3986       if (isConstant(V)) {
3987         ReuseShuffleIndicies.emplace_back(
3988             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3989         UniqueValues.emplace_back(V);
3990         continue;
3991       }
3992       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3993       ReuseShuffleIndicies.emplace_back(Res.first->second);
3994       if (Res.second)
3995         UniqueValues.emplace_back(V);
3996     }
3997     size_t NumUniqueScalarValues = UniqueValues.size();
3998     if (NumUniqueScalarValues == VL.size()) {
3999       ReuseShuffleIndicies.clear();
4000     } else {
4001       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4002       if (NumUniqueScalarValues <= 1 ||
4003           (UniquePositions.size() == 1 && all_of(UniqueValues,
4004                                                  [](Value *V) {
4005                                                    return isa<UndefValue>(V) ||
4006                                                           !isConstant(V);
4007                                                  })) ||
4008           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4009         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4010         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4011         return false;
4012       }
4013       VL = UniqueValues;
4014     }
4015     return true;
4016   };
4017 
4018   InstructionsState S = getSameOpcode(VL);
4019   if (Depth == RecursionMaxDepth) {
4020     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4021     if (TryToFindDuplicates(S))
4022       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4023                    ReuseShuffleIndicies);
4024     return;
4025   }
4026 
4027   // Don't handle scalable vectors
4028   if (S.getOpcode() == Instruction::ExtractElement &&
4029       isa<ScalableVectorType>(
4030           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4031     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4032     if (TryToFindDuplicates(S))
4033       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4034                    ReuseShuffleIndicies);
4035     return;
4036   }
4037 
4038   // Don't handle vectors.
4039   if (S.OpValue->getType()->isVectorTy() &&
4040       !isa<InsertElementInst>(S.OpValue)) {
4041     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4042     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4043     return;
4044   }
4045 
4046   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4047     if (SI->getValueOperand()->getType()->isVectorTy()) {
4048       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4049       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4050       return;
4051     }
4052 
4053   // If all of the operands are identical or constant we have a simple solution.
4054   // If we deal with insert/extract instructions, they all must have constant
4055   // indices, otherwise we should gather them, not try to vectorize.
4056   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4057       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4058        !all_of(VL, isVectorLikeInstWithConstOps))) {
4059     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4060     if (TryToFindDuplicates(S))
4061       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4062                    ReuseShuffleIndicies);
4063     return;
4064   }
4065 
4066   // We now know that this is a vector of instructions of the same type from
4067   // the same block.
4068 
4069   // Don't vectorize ephemeral values.
4070   for (Value *V : VL) {
4071     if (EphValues.count(V)) {
4072       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4073                         << ") is ephemeral.\n");
4074       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4075       return;
4076     }
4077   }
4078 
4079   // Check if this is a duplicate of another entry.
4080   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4081     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4082     if (!E->isSame(VL)) {
4083       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4084       if (TryToFindDuplicates(S))
4085         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4086                      ReuseShuffleIndicies);
4087       return;
4088     }
4089     // Record the reuse of the tree node.  FIXME, currently this is only used to
4090     // properly draw the graph rather than for the actual vectorization.
4091     E->UserTreeIndices.push_back(UserTreeIdx);
4092     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4093                       << ".\n");
4094     return;
4095   }
4096 
4097   // Check that none of the instructions in the bundle are already in the tree.
4098   for (Value *V : VL) {
4099     auto *I = dyn_cast<Instruction>(V);
4100     if (!I)
4101       continue;
4102     if (getTreeEntry(I)) {
4103       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4104                         << ") is already in tree.\n");
4105       if (TryToFindDuplicates(S))
4106         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4107                      ReuseShuffleIndicies);
4108       return;
4109     }
4110   }
4111 
4112   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4113   for (Value *V : VL) {
4114     if (is_contained(UserIgnoreList, V)) {
4115       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4116       if (TryToFindDuplicates(S))
4117         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4118                      ReuseShuffleIndicies);
4119       return;
4120     }
4121   }
4122 
4123   // Check that all of the users of the scalars that we want to vectorize are
4124   // schedulable.
4125   auto *VL0 = cast<Instruction>(S.OpValue);
4126   BasicBlock *BB = VL0->getParent();
4127 
4128   if (!DT->isReachableFromEntry(BB)) {
4129     // Don't go into unreachable blocks. They may contain instructions with
4130     // dependency cycles which confuse the final scheduling.
4131     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4132     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4133     return;
4134   }
4135 
4136   // Check that every instruction appears once in this bundle.
4137   if (!TryToFindDuplicates(S))
4138     return;
4139 
4140   auto &BSRef = BlocksSchedules[BB];
4141   if (!BSRef)
4142     BSRef = std::make_unique<BlockScheduling>(BB);
4143 
4144   BlockScheduling &BS = *BSRef;
4145 
4146   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4147 #ifdef EXPENSIVE_CHECKS
4148   // Make sure we didn't break any internal invariants
4149   BS.verify();
4150 #endif
4151   if (!Bundle) {
4152     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4153     assert((!BS.getScheduleData(VL0) ||
4154             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4155            "tryScheduleBundle should cancelScheduling on failure");
4156     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4157                  ReuseShuffleIndicies);
4158     return;
4159   }
4160   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4161 
4162   unsigned ShuffleOrOp = S.isAltShuffle() ?
4163                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4164   switch (ShuffleOrOp) {
4165     case Instruction::PHI: {
4166       auto *PH = cast<PHINode>(VL0);
4167 
4168       // Check for terminator values (e.g. invoke).
4169       for (Value *V : VL)
4170         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4171           Instruction *Term = dyn_cast<Instruction>(Incoming);
4172           if (Term && Term->isTerminator()) {
4173             LLVM_DEBUG(dbgs()
4174                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4175             BS.cancelScheduling(VL, VL0);
4176             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4177                          ReuseShuffleIndicies);
4178             return;
4179           }
4180         }
4181 
4182       TreeEntry *TE =
4183           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4184       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4185 
4186       // Keeps the reordered operands to avoid code duplication.
4187       SmallVector<ValueList, 2> OperandsVec;
4188       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4189         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4190           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4191           TE->setOperand(I, Operands);
4192           OperandsVec.push_back(Operands);
4193           continue;
4194         }
4195         ValueList Operands;
4196         // Prepare the operand vector.
4197         for (Value *V : VL)
4198           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4199               PH->getIncomingBlock(I)));
4200         TE->setOperand(I, Operands);
4201         OperandsVec.push_back(Operands);
4202       }
4203       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4204         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4205       return;
4206     }
4207     case Instruction::ExtractValue:
4208     case Instruction::ExtractElement: {
4209       OrdersType CurrentOrder;
4210       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4211       if (Reuse) {
4212         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4213         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4214                      ReuseShuffleIndicies);
4215         // This is a special case, as it does not gather, but at the same time
4216         // we are not extending buildTree_rec() towards the operands.
4217         ValueList Op0;
4218         Op0.assign(VL.size(), VL0->getOperand(0));
4219         VectorizableTree.back()->setOperand(0, Op0);
4220         return;
4221       }
4222       if (!CurrentOrder.empty()) {
4223         LLVM_DEBUG({
4224           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4225                     "with order";
4226           for (unsigned Idx : CurrentOrder)
4227             dbgs() << " " << Idx;
4228           dbgs() << "\n";
4229         });
4230         fixupOrderingIndices(CurrentOrder);
4231         // Insert new order with initial value 0, if it does not exist,
4232         // otherwise return the iterator to the existing one.
4233         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4234                      ReuseShuffleIndicies, CurrentOrder);
4235         // This is a special case, as it does not gather, but at the same time
4236         // we are not extending buildTree_rec() towards the operands.
4237         ValueList Op0;
4238         Op0.assign(VL.size(), VL0->getOperand(0));
4239         VectorizableTree.back()->setOperand(0, Op0);
4240         return;
4241       }
4242       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4243       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4244                    ReuseShuffleIndicies);
4245       BS.cancelScheduling(VL, VL0);
4246       return;
4247     }
4248     case Instruction::InsertElement: {
4249       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4250 
4251       // Check that we have a buildvector and not a shuffle of 2 or more
4252       // different vectors.
4253       ValueSet SourceVectors;
4254       for (Value *V : VL) {
4255         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4256         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4257       }
4258 
4259       if (count_if(VL, [&SourceVectors](Value *V) {
4260             return !SourceVectors.contains(V);
4261           }) >= 2) {
4262         // Found 2nd source vector - cancel.
4263         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4264                              "different source vectors.\n");
4265         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4266         BS.cancelScheduling(VL, VL0);
4267         return;
4268       }
4269 
4270       auto OrdCompare = [](const std::pair<int, int> &P1,
4271                            const std::pair<int, int> &P2) {
4272         return P1.first > P2.first;
4273       };
4274       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4275                     decltype(OrdCompare)>
4276           Indices(OrdCompare);
4277       for (int I = 0, E = VL.size(); I < E; ++I) {
4278         unsigned Idx = *getInsertIndex(VL[I]);
4279         Indices.emplace(Idx, I);
4280       }
4281       OrdersType CurrentOrder(VL.size(), VL.size());
4282       bool IsIdentity = true;
4283       for (int I = 0, E = VL.size(); I < E; ++I) {
4284         CurrentOrder[Indices.top().second] = I;
4285         IsIdentity &= Indices.top().second == I;
4286         Indices.pop();
4287       }
4288       if (IsIdentity)
4289         CurrentOrder.clear();
4290       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4291                                    None, CurrentOrder);
4292       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4293 
4294       constexpr int NumOps = 2;
4295       ValueList VectorOperands[NumOps];
4296       for (int I = 0; I < NumOps; ++I) {
4297         for (Value *V : VL)
4298           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4299 
4300         TE->setOperand(I, VectorOperands[I]);
4301       }
4302       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4303       return;
4304     }
4305     case Instruction::Load: {
4306       // Check that a vectorized load would load the same memory as a scalar
4307       // load. For example, we don't want to vectorize loads that are smaller
4308       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4309       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4310       // from such a struct, we read/write packed bits disagreeing with the
4311       // unvectorized version.
4312       SmallVector<Value *> PointerOps;
4313       OrdersType CurrentOrder;
4314       TreeEntry *TE = nullptr;
4315       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4316                                 PointerOps)) {
4317       case LoadsState::Vectorize:
4318         if (CurrentOrder.empty()) {
4319           // Original loads are consecutive and does not require reordering.
4320           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4321                             ReuseShuffleIndicies);
4322           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4323         } else {
4324           fixupOrderingIndices(CurrentOrder);
4325           // Need to reorder.
4326           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4327                             ReuseShuffleIndicies, CurrentOrder);
4328           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4329         }
4330         TE->setOperandsInOrder();
4331         break;
4332       case LoadsState::ScatterVectorize:
4333         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4334         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4335                           UserTreeIdx, ReuseShuffleIndicies);
4336         TE->setOperandsInOrder();
4337         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4338         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4339         break;
4340       case LoadsState::Gather:
4341         BS.cancelScheduling(VL, VL0);
4342         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4343                      ReuseShuffleIndicies);
4344 #ifndef NDEBUG
4345         Type *ScalarTy = VL0->getType();
4346         if (DL->getTypeSizeInBits(ScalarTy) !=
4347             DL->getTypeAllocSizeInBits(ScalarTy))
4348           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4349         else if (any_of(VL, [](Value *V) {
4350                    return !cast<LoadInst>(V)->isSimple();
4351                  }))
4352           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4353         else
4354           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4355 #endif // NDEBUG
4356         break;
4357       }
4358       return;
4359     }
4360     case Instruction::ZExt:
4361     case Instruction::SExt:
4362     case Instruction::FPToUI:
4363     case Instruction::FPToSI:
4364     case Instruction::FPExt:
4365     case Instruction::PtrToInt:
4366     case Instruction::IntToPtr:
4367     case Instruction::SIToFP:
4368     case Instruction::UIToFP:
4369     case Instruction::Trunc:
4370     case Instruction::FPTrunc:
4371     case Instruction::BitCast: {
4372       Type *SrcTy = VL0->getOperand(0)->getType();
4373       for (Value *V : VL) {
4374         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4375         if (Ty != SrcTy || !isValidElementType(Ty)) {
4376           BS.cancelScheduling(VL, VL0);
4377           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4378                        ReuseShuffleIndicies);
4379           LLVM_DEBUG(dbgs()
4380                      << "SLP: Gathering casts with different src types.\n");
4381           return;
4382         }
4383       }
4384       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4385                                    ReuseShuffleIndicies);
4386       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4387 
4388       TE->setOperandsInOrder();
4389       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4390         ValueList Operands;
4391         // Prepare the operand vector.
4392         for (Value *V : VL)
4393           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4394 
4395         buildTree_rec(Operands, Depth + 1, {TE, i});
4396       }
4397       return;
4398     }
4399     case Instruction::ICmp:
4400     case Instruction::FCmp: {
4401       // Check that all of the compares have the same predicate.
4402       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4403       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4404       Type *ComparedTy = VL0->getOperand(0)->getType();
4405       for (Value *V : VL) {
4406         CmpInst *Cmp = cast<CmpInst>(V);
4407         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4408             Cmp->getOperand(0)->getType() != ComparedTy) {
4409           BS.cancelScheduling(VL, VL0);
4410           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4411                        ReuseShuffleIndicies);
4412           LLVM_DEBUG(dbgs()
4413                      << "SLP: Gathering cmp with different predicate.\n");
4414           return;
4415         }
4416       }
4417 
4418       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4419                                    ReuseShuffleIndicies);
4420       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4421 
4422       ValueList Left, Right;
4423       if (cast<CmpInst>(VL0)->isCommutative()) {
4424         // Commutative predicate - collect + sort operands of the instructions
4425         // so that each side is more likely to have the same opcode.
4426         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4427         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4428       } else {
4429         // Collect operands - commute if it uses the swapped predicate.
4430         for (Value *V : VL) {
4431           auto *Cmp = cast<CmpInst>(V);
4432           Value *LHS = Cmp->getOperand(0);
4433           Value *RHS = Cmp->getOperand(1);
4434           if (Cmp->getPredicate() != P0)
4435             std::swap(LHS, RHS);
4436           Left.push_back(LHS);
4437           Right.push_back(RHS);
4438         }
4439       }
4440       TE->setOperand(0, Left);
4441       TE->setOperand(1, Right);
4442       buildTree_rec(Left, Depth + 1, {TE, 0});
4443       buildTree_rec(Right, Depth + 1, {TE, 1});
4444       return;
4445     }
4446     case Instruction::Select:
4447     case Instruction::FNeg:
4448     case Instruction::Add:
4449     case Instruction::FAdd:
4450     case Instruction::Sub:
4451     case Instruction::FSub:
4452     case Instruction::Mul:
4453     case Instruction::FMul:
4454     case Instruction::UDiv:
4455     case Instruction::SDiv:
4456     case Instruction::FDiv:
4457     case Instruction::URem:
4458     case Instruction::SRem:
4459     case Instruction::FRem:
4460     case Instruction::Shl:
4461     case Instruction::LShr:
4462     case Instruction::AShr:
4463     case Instruction::And:
4464     case Instruction::Or:
4465     case Instruction::Xor: {
4466       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4467                                    ReuseShuffleIndicies);
4468       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4469 
4470       // Sort operands of the instructions so that each side is more likely to
4471       // have the same opcode.
4472       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4473         ValueList Left, Right;
4474         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4475         TE->setOperand(0, Left);
4476         TE->setOperand(1, Right);
4477         buildTree_rec(Left, Depth + 1, {TE, 0});
4478         buildTree_rec(Right, Depth + 1, {TE, 1});
4479         return;
4480       }
4481 
4482       TE->setOperandsInOrder();
4483       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4484         ValueList Operands;
4485         // Prepare the operand vector.
4486         for (Value *V : VL)
4487           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4488 
4489         buildTree_rec(Operands, Depth + 1, {TE, i});
4490       }
4491       return;
4492     }
4493     case Instruction::GetElementPtr: {
4494       // We don't combine GEPs with complicated (nested) indexing.
4495       for (Value *V : VL) {
4496         if (cast<Instruction>(V)->getNumOperands() != 2) {
4497           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4498           BS.cancelScheduling(VL, VL0);
4499           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4500                        ReuseShuffleIndicies);
4501           return;
4502         }
4503       }
4504 
4505       // We can't combine several GEPs into one vector if they operate on
4506       // different types.
4507       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4508       for (Value *V : VL) {
4509         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4510         if (Ty0 != CurTy) {
4511           LLVM_DEBUG(dbgs()
4512                      << "SLP: not-vectorizable GEP (different types).\n");
4513           BS.cancelScheduling(VL, VL0);
4514           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4515                        ReuseShuffleIndicies);
4516           return;
4517         }
4518       }
4519 
4520       // We don't combine GEPs with non-constant indexes.
4521       Type *Ty1 = VL0->getOperand(1)->getType();
4522       for (Value *V : VL) {
4523         auto Op = cast<Instruction>(V)->getOperand(1);
4524         if (!isa<ConstantInt>(Op) ||
4525             (Op->getType() != Ty1 &&
4526              Op->getType()->getScalarSizeInBits() >
4527                  DL->getIndexSizeInBits(
4528                      V->getType()->getPointerAddressSpace()))) {
4529           LLVM_DEBUG(dbgs()
4530                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4531           BS.cancelScheduling(VL, VL0);
4532           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4533                        ReuseShuffleIndicies);
4534           return;
4535         }
4536       }
4537 
4538       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4539                                    ReuseShuffleIndicies);
4540       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4541       SmallVector<ValueList, 2> Operands(2);
4542       // Prepare the operand vector for pointer operands.
4543       for (Value *V : VL)
4544         Operands.front().push_back(
4545             cast<GetElementPtrInst>(V)->getPointerOperand());
4546       TE->setOperand(0, Operands.front());
4547       // Need to cast all indices to the same type before vectorization to
4548       // avoid crash.
4549       // Required to be able to find correct matches between different gather
4550       // nodes and reuse the vectorized values rather than trying to gather them
4551       // again.
4552       int IndexIdx = 1;
4553       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4554       Type *Ty = all_of(VL,
4555                         [VL0Ty, IndexIdx](Value *V) {
4556                           return VL0Ty == cast<GetElementPtrInst>(V)
4557                                               ->getOperand(IndexIdx)
4558                                               ->getType();
4559                         })
4560                      ? VL0Ty
4561                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4562                                             ->getPointerOperandType()
4563                                             ->getScalarType());
4564       // Prepare the operand vector.
4565       for (Value *V : VL) {
4566         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4567         auto *CI = cast<ConstantInt>(Op);
4568         Operands.back().push_back(ConstantExpr::getIntegerCast(
4569             CI, Ty, CI->getValue().isSignBitSet()));
4570       }
4571       TE->setOperand(IndexIdx, Operands.back());
4572 
4573       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4574         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4575       return;
4576     }
4577     case Instruction::Store: {
4578       // Check if the stores are consecutive or if we need to swizzle them.
4579       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4580       // Avoid types that are padded when being allocated as scalars, while
4581       // being packed together in a vector (such as i1).
4582       if (DL->getTypeSizeInBits(ScalarTy) !=
4583           DL->getTypeAllocSizeInBits(ScalarTy)) {
4584         BS.cancelScheduling(VL, VL0);
4585         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4586                      ReuseShuffleIndicies);
4587         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4588         return;
4589       }
4590       // Make sure all stores in the bundle are simple - we can't vectorize
4591       // atomic or volatile stores.
4592       SmallVector<Value *, 4> PointerOps(VL.size());
4593       ValueList Operands(VL.size());
4594       auto POIter = PointerOps.begin();
4595       auto OIter = Operands.begin();
4596       for (Value *V : VL) {
4597         auto *SI = cast<StoreInst>(V);
4598         if (!SI->isSimple()) {
4599           BS.cancelScheduling(VL, VL0);
4600           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4601                        ReuseShuffleIndicies);
4602           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4603           return;
4604         }
4605         *POIter = SI->getPointerOperand();
4606         *OIter = SI->getValueOperand();
4607         ++POIter;
4608         ++OIter;
4609       }
4610 
4611       OrdersType CurrentOrder;
4612       // Check the order of pointer operands.
4613       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4614         Value *Ptr0;
4615         Value *PtrN;
4616         if (CurrentOrder.empty()) {
4617           Ptr0 = PointerOps.front();
4618           PtrN = PointerOps.back();
4619         } else {
4620           Ptr0 = PointerOps[CurrentOrder.front()];
4621           PtrN = PointerOps[CurrentOrder.back()];
4622         }
4623         Optional<int> Dist =
4624             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4625         // Check that the sorted pointer operands are consecutive.
4626         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4627           if (CurrentOrder.empty()) {
4628             // Original stores are consecutive and does not require reordering.
4629             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4630                                          UserTreeIdx, ReuseShuffleIndicies);
4631             TE->setOperandsInOrder();
4632             buildTree_rec(Operands, Depth + 1, {TE, 0});
4633             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4634           } else {
4635             fixupOrderingIndices(CurrentOrder);
4636             TreeEntry *TE =
4637                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4638                              ReuseShuffleIndicies, CurrentOrder);
4639             TE->setOperandsInOrder();
4640             buildTree_rec(Operands, Depth + 1, {TE, 0});
4641             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4642           }
4643           return;
4644         }
4645       }
4646 
4647       BS.cancelScheduling(VL, VL0);
4648       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4649                    ReuseShuffleIndicies);
4650       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4651       return;
4652     }
4653     case Instruction::Call: {
4654       // Check if the calls are all to the same vectorizable intrinsic or
4655       // library function.
4656       CallInst *CI = cast<CallInst>(VL0);
4657       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4658 
4659       VFShape Shape = VFShape::get(
4660           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4661           false /*HasGlobalPred*/);
4662       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4663 
4664       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4665         BS.cancelScheduling(VL, VL0);
4666         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4667                      ReuseShuffleIndicies);
4668         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4669         return;
4670       }
4671       Function *F = CI->getCalledFunction();
4672       unsigned NumArgs = CI->arg_size();
4673       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4674       for (unsigned j = 0; j != NumArgs; ++j)
4675         if (hasVectorInstrinsicScalarOpd(ID, j))
4676           ScalarArgs[j] = CI->getArgOperand(j);
4677       for (Value *V : VL) {
4678         CallInst *CI2 = dyn_cast<CallInst>(V);
4679         if (!CI2 || CI2->getCalledFunction() != F ||
4680             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4681             (VecFunc &&
4682              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4683             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4684           BS.cancelScheduling(VL, VL0);
4685           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4686                        ReuseShuffleIndicies);
4687           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4688                             << "\n");
4689           return;
4690         }
4691         // Some intrinsics have scalar arguments and should be same in order for
4692         // them to be vectorized.
4693         for (unsigned j = 0; j != NumArgs; ++j) {
4694           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4695             Value *A1J = CI2->getArgOperand(j);
4696             if (ScalarArgs[j] != A1J) {
4697               BS.cancelScheduling(VL, VL0);
4698               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4699                            ReuseShuffleIndicies);
4700               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4701                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4702                                 << "\n");
4703               return;
4704             }
4705           }
4706         }
4707         // Verify that the bundle operands are identical between the two calls.
4708         if (CI->hasOperandBundles() &&
4709             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4710                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4711                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4712           BS.cancelScheduling(VL, VL0);
4713           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4714                        ReuseShuffleIndicies);
4715           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4716                             << *CI << "!=" << *V << '\n');
4717           return;
4718         }
4719       }
4720 
4721       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4722                                    ReuseShuffleIndicies);
4723       TE->setOperandsInOrder();
4724       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4725         // For scalar operands no need to to create an entry since no need to
4726         // vectorize it.
4727         if (hasVectorInstrinsicScalarOpd(ID, i))
4728           continue;
4729         ValueList Operands;
4730         // Prepare the operand vector.
4731         for (Value *V : VL) {
4732           auto *CI2 = cast<CallInst>(V);
4733           Operands.push_back(CI2->getArgOperand(i));
4734         }
4735         buildTree_rec(Operands, Depth + 1, {TE, i});
4736       }
4737       return;
4738     }
4739     case Instruction::ShuffleVector: {
4740       // If this is not an alternate sequence of opcode like add-sub
4741       // then do not vectorize this instruction.
4742       if (!S.isAltShuffle()) {
4743         BS.cancelScheduling(VL, VL0);
4744         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4745                      ReuseShuffleIndicies);
4746         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4747         return;
4748       }
4749       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4750                                    ReuseShuffleIndicies);
4751       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4752 
4753       // Reorder operands if reordering would enable vectorization.
4754       auto *CI = dyn_cast<CmpInst>(VL0);
4755       if (isa<BinaryOperator>(VL0) || CI) {
4756         ValueList Left, Right;
4757         if (!CI || all_of(VL, [](Value *V) {
4758               return cast<CmpInst>(V)->isCommutative();
4759             })) {
4760           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4761         } else {
4762           CmpInst::Predicate P0 = CI->getPredicate();
4763           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4764           assert(P0 != AltP0 &&
4765                  "Expected different main/alternate predicates.");
4766           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4767           Value *BaseOp0 = VL0->getOperand(0);
4768           Value *BaseOp1 = VL0->getOperand(1);
4769           // Collect operands - commute if it uses the swapped predicate or
4770           // alternate operation.
4771           for (Value *V : VL) {
4772             auto *Cmp = cast<CmpInst>(V);
4773             Value *LHS = Cmp->getOperand(0);
4774             Value *RHS = Cmp->getOperand(1);
4775             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4776             if (P0 == AltP0Swapped) {
4777               if (CI != Cmp && S.AltOp != Cmp &&
4778                   ((P0 == CurrentPred &&
4779                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4780                    (AltP0 == CurrentPred &&
4781                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4782                 std::swap(LHS, RHS);
4783             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4784               std::swap(LHS, RHS);
4785             }
4786             Left.push_back(LHS);
4787             Right.push_back(RHS);
4788           }
4789         }
4790         TE->setOperand(0, Left);
4791         TE->setOperand(1, Right);
4792         buildTree_rec(Left, Depth + 1, {TE, 0});
4793         buildTree_rec(Right, Depth + 1, {TE, 1});
4794         return;
4795       }
4796 
4797       TE->setOperandsInOrder();
4798       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4799         ValueList Operands;
4800         // Prepare the operand vector.
4801         for (Value *V : VL)
4802           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4803 
4804         buildTree_rec(Operands, Depth + 1, {TE, i});
4805       }
4806       return;
4807     }
4808     default:
4809       BS.cancelScheduling(VL, VL0);
4810       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4811                    ReuseShuffleIndicies);
4812       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4813       return;
4814   }
4815 }
4816 
4817 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4818   unsigned N = 1;
4819   Type *EltTy = T;
4820 
4821   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4822          isa<VectorType>(EltTy)) {
4823     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4824       // Check that struct is homogeneous.
4825       for (const auto *Ty : ST->elements())
4826         if (Ty != *ST->element_begin())
4827           return 0;
4828       N *= ST->getNumElements();
4829       EltTy = *ST->element_begin();
4830     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4831       N *= AT->getNumElements();
4832       EltTy = AT->getElementType();
4833     } else {
4834       auto *VT = cast<FixedVectorType>(EltTy);
4835       N *= VT->getNumElements();
4836       EltTy = VT->getElementType();
4837     }
4838   }
4839 
4840   if (!isValidElementType(EltTy))
4841     return 0;
4842   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4843   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4844     return 0;
4845   return N;
4846 }
4847 
4848 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4849                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4850   const auto *It = find_if(VL, [](Value *V) {
4851     return isa<ExtractElementInst, ExtractValueInst>(V);
4852   });
4853   assert(It != VL.end() && "Expected at least one extract instruction.");
4854   auto *E0 = cast<Instruction>(*It);
4855   assert(all_of(VL,
4856                 [](Value *V) {
4857                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4858                       V);
4859                 }) &&
4860          "Invalid opcode");
4861   // Check if all of the extracts come from the same vector and from the
4862   // correct offset.
4863   Value *Vec = E0->getOperand(0);
4864 
4865   CurrentOrder.clear();
4866 
4867   // We have to extract from a vector/aggregate with the same number of elements.
4868   unsigned NElts;
4869   if (E0->getOpcode() == Instruction::ExtractValue) {
4870     const DataLayout &DL = E0->getModule()->getDataLayout();
4871     NElts = canMapToVector(Vec->getType(), DL);
4872     if (!NElts)
4873       return false;
4874     // Check if load can be rewritten as load of vector.
4875     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4876     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4877       return false;
4878   } else {
4879     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4880   }
4881 
4882   if (NElts != VL.size())
4883     return false;
4884 
4885   // Check that all of the indices extract from the correct offset.
4886   bool ShouldKeepOrder = true;
4887   unsigned E = VL.size();
4888   // Assign to all items the initial value E + 1 so we can check if the extract
4889   // instruction index was used already.
4890   // Also, later we can check that all the indices are used and we have a
4891   // consecutive access in the extract instructions, by checking that no
4892   // element of CurrentOrder still has value E + 1.
4893   CurrentOrder.assign(E, E);
4894   unsigned I = 0;
4895   for (; I < E; ++I) {
4896     auto *Inst = dyn_cast<Instruction>(VL[I]);
4897     if (!Inst)
4898       continue;
4899     if (Inst->getOperand(0) != Vec)
4900       break;
4901     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4902       if (isa<UndefValue>(EE->getIndexOperand()))
4903         continue;
4904     Optional<unsigned> Idx = getExtractIndex(Inst);
4905     if (!Idx)
4906       break;
4907     const unsigned ExtIdx = *Idx;
4908     if (ExtIdx != I) {
4909       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4910         break;
4911       ShouldKeepOrder = false;
4912       CurrentOrder[ExtIdx] = I;
4913     } else {
4914       if (CurrentOrder[I] != E)
4915         break;
4916       CurrentOrder[I] = I;
4917     }
4918   }
4919   if (I < E) {
4920     CurrentOrder.clear();
4921     return false;
4922   }
4923   if (ShouldKeepOrder)
4924     CurrentOrder.clear();
4925 
4926   return ShouldKeepOrder;
4927 }
4928 
4929 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4930                                     ArrayRef<Value *> VectorizedVals) const {
4931   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4932          all_of(I->users(), [this](User *U) {
4933            return ScalarToTreeEntry.count(U) > 0 ||
4934                   isVectorLikeInstWithConstOps(U) ||
4935                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4936          });
4937 }
4938 
4939 static std::pair<InstructionCost, InstructionCost>
4940 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4941                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4942   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4943 
4944   // Calculate the cost of the scalar and vector calls.
4945   SmallVector<Type *, 4> VecTys;
4946   for (Use &Arg : CI->args())
4947     VecTys.push_back(
4948         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4949   FastMathFlags FMF;
4950   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4951     FMF = FPCI->getFastMathFlags();
4952   SmallVector<const Value *> Arguments(CI->args());
4953   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4954                                     dyn_cast<IntrinsicInst>(CI));
4955   auto IntrinsicCost =
4956     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4957 
4958   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4959                                      VecTy->getNumElements())),
4960                             false /*HasGlobalPred*/);
4961   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4962   auto LibCost = IntrinsicCost;
4963   if (!CI->isNoBuiltin() && VecFunc) {
4964     // Calculate the cost of the vector library call.
4965     // If the corresponding vector call is cheaper, return its cost.
4966     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4967                                     TTI::TCK_RecipThroughput);
4968   }
4969   return {IntrinsicCost, LibCost};
4970 }
4971 
4972 /// Compute the cost of creating a vector of type \p VecTy containing the
4973 /// extracted values from \p VL.
4974 static InstructionCost
4975 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4976                    TargetTransformInfo::ShuffleKind ShuffleKind,
4977                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4978   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4979 
4980   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4981       VecTy->getNumElements() < NumOfParts)
4982     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4983 
4984   bool AllConsecutive = true;
4985   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4986   unsigned Idx = -1;
4987   InstructionCost Cost = 0;
4988 
4989   // Process extracts in blocks of EltsPerVector to check if the source vector
4990   // operand can be re-used directly. If not, add the cost of creating a shuffle
4991   // to extract the values into a vector register.
4992   for (auto *V : VL) {
4993     ++Idx;
4994 
4995     // Need to exclude undefs from analysis.
4996     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4997       continue;
4998 
4999     // Reached the start of a new vector registers.
5000     if (Idx % EltsPerVector == 0) {
5001       AllConsecutive = true;
5002       continue;
5003     }
5004 
5005     // Check all extracts for a vector register on the target directly
5006     // extract values in order.
5007     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5008     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5009       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5010       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5011                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5012     }
5013 
5014     if (AllConsecutive)
5015       continue;
5016 
5017     // Skip all indices, except for the last index per vector block.
5018     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5019       continue;
5020 
5021     // If we have a series of extracts which are not consecutive and hence
5022     // cannot re-use the source vector register directly, compute the shuffle
5023     // cost to extract the a vector with EltsPerVector elements.
5024     Cost += TTI.getShuffleCost(
5025         TargetTransformInfo::SK_PermuteSingleSrc,
5026         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5027   }
5028   return Cost;
5029 }
5030 
5031 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5032 /// operations operands.
5033 static void
5034 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5035                       ArrayRef<int> ReusesIndices,
5036                       const function_ref<bool(Instruction *)> IsAltOp,
5037                       SmallVectorImpl<int> &Mask,
5038                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5039                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5040   unsigned Sz = VL.size();
5041   Mask.assign(Sz, UndefMaskElem);
5042   SmallVector<int> OrderMask;
5043   if (!ReorderIndices.empty())
5044     inversePermutation(ReorderIndices, OrderMask);
5045   for (unsigned I = 0; I < Sz; ++I) {
5046     unsigned Idx = I;
5047     if (!ReorderIndices.empty())
5048       Idx = OrderMask[I];
5049     auto *OpInst = cast<Instruction>(VL[Idx]);
5050     if (IsAltOp(OpInst)) {
5051       Mask[I] = Sz + Idx;
5052       if (AltScalars)
5053         AltScalars->push_back(OpInst);
5054     } else {
5055       Mask[I] = Idx;
5056       if (OpScalars)
5057         OpScalars->push_back(OpInst);
5058     }
5059   }
5060   if (!ReusesIndices.empty()) {
5061     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5062     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5063       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5064     });
5065     Mask.swap(NewMask);
5066   }
5067 }
5068 
5069 /// Checks if the specified instruction \p I is an alternate operation for the
5070 /// given \p MainOp and \p AltOp instructions.
5071 static bool isAlternateInstruction(const Instruction *I,
5072                                    const Instruction *MainOp,
5073                                    const Instruction *AltOp) {
5074   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5075     auto *AltCI0 = cast<CmpInst>(AltOp);
5076     auto *CI = cast<CmpInst>(I);
5077     CmpInst::Predicate P0 = CI0->getPredicate();
5078     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5079     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5080     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5081     CmpInst::Predicate CurrentPred = CI->getPredicate();
5082     if (P0 == AltP0Swapped)
5083       return I == AltCI0 ||
5084              (I != MainOp &&
5085               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5086                                    CI->getOperand(0), CI->getOperand(1)));
5087     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5088   }
5089   return I->getOpcode() == AltOp->getOpcode();
5090 }
5091 
5092 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5093                                       ArrayRef<Value *> VectorizedVals) {
5094   ArrayRef<Value*> VL = E->Scalars;
5095 
5096   Type *ScalarTy = VL[0]->getType();
5097   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5098     ScalarTy = SI->getValueOperand()->getType();
5099   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5100     ScalarTy = CI->getOperand(0)->getType();
5101   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5102     ScalarTy = IE->getOperand(1)->getType();
5103   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5104   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5105 
5106   // If we have computed a smaller type for the expression, update VecTy so
5107   // that the costs will be accurate.
5108   if (MinBWs.count(VL[0]))
5109     VecTy = FixedVectorType::get(
5110         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5111   unsigned EntryVF = E->getVectorFactor();
5112   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5113 
5114   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5115   // FIXME: it tries to fix a problem with MSVC buildbots.
5116   TargetTransformInfo &TTIRef = *TTI;
5117   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5118                                VectorizedVals, E](InstructionCost &Cost) {
5119     DenseMap<Value *, int> ExtractVectorsTys;
5120     SmallPtrSet<Value *, 4> CheckedExtracts;
5121     for (auto *V : VL) {
5122       if (isa<UndefValue>(V))
5123         continue;
5124       // If all users of instruction are going to be vectorized and this
5125       // instruction itself is not going to be vectorized, consider this
5126       // instruction as dead and remove its cost from the final cost of the
5127       // vectorized tree.
5128       // Also, avoid adjusting the cost for extractelements with multiple uses
5129       // in different graph entries.
5130       const TreeEntry *VE = getTreeEntry(V);
5131       if (!CheckedExtracts.insert(V).second ||
5132           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5133           (VE && VE != E))
5134         continue;
5135       auto *EE = cast<ExtractElementInst>(V);
5136       Optional<unsigned> EEIdx = getExtractIndex(EE);
5137       if (!EEIdx)
5138         continue;
5139       unsigned Idx = *EEIdx;
5140       if (TTIRef.getNumberOfParts(VecTy) !=
5141           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5142         auto It =
5143             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5144         It->getSecond() = std::min<int>(It->second, Idx);
5145       }
5146       // Take credit for instruction that will become dead.
5147       if (EE->hasOneUse()) {
5148         Instruction *Ext = EE->user_back();
5149         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5150             all_of(Ext->users(),
5151                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5152           // Use getExtractWithExtendCost() to calculate the cost of
5153           // extractelement/ext pair.
5154           Cost -=
5155               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5156                                               EE->getVectorOperandType(), Idx);
5157           // Add back the cost of s|zext which is subtracted separately.
5158           Cost += TTIRef.getCastInstrCost(
5159               Ext->getOpcode(), Ext->getType(), EE->getType(),
5160               TTI::getCastContextHint(Ext), CostKind, Ext);
5161           continue;
5162         }
5163       }
5164       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5165                                         EE->getVectorOperandType(), Idx);
5166     }
5167     // Add a cost for subvector extracts/inserts if required.
5168     for (const auto &Data : ExtractVectorsTys) {
5169       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5170       unsigned NumElts = VecTy->getNumElements();
5171       if (Data.second % NumElts == 0)
5172         continue;
5173       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5174         unsigned Idx = (Data.second / NumElts) * NumElts;
5175         unsigned EENumElts = EEVTy->getNumElements();
5176         if (Idx + NumElts <= EENumElts) {
5177           Cost +=
5178               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5179                                     EEVTy, None, Idx, VecTy);
5180         } else {
5181           // Need to round up the subvector type vectorization factor to avoid a
5182           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5183           // <= EENumElts.
5184           auto *SubVT =
5185               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5186           Cost +=
5187               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5188                                     EEVTy, None, Idx, SubVT);
5189         }
5190       } else {
5191         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5192                                       VecTy, None, 0, EEVTy);
5193       }
5194     }
5195   };
5196   if (E->State == TreeEntry::NeedToGather) {
5197     if (allConstant(VL))
5198       return 0;
5199     if (isa<InsertElementInst>(VL[0]))
5200       return InstructionCost::getInvalid();
5201     SmallVector<int> Mask;
5202     SmallVector<const TreeEntry *> Entries;
5203     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5204         isGatherShuffledEntry(E, Mask, Entries);
5205     if (Shuffle.hasValue()) {
5206       InstructionCost GatherCost = 0;
5207       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5208         // Perfect match in the graph, will reuse the previously vectorized
5209         // node. Cost is 0.
5210         LLVM_DEBUG(
5211             dbgs()
5212             << "SLP: perfect diamond match for gather bundle that starts with "
5213             << *VL.front() << ".\n");
5214         if (NeedToShuffleReuses)
5215           GatherCost =
5216               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5217                                   FinalVecTy, E->ReuseShuffleIndices);
5218       } else {
5219         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5220                           << " entries for bundle that starts with "
5221                           << *VL.front() << ".\n");
5222         // Detected that instead of gather we can emit a shuffle of single/two
5223         // previously vectorized nodes. Add the cost of the permutation rather
5224         // than gather.
5225         ::addMask(Mask, E->ReuseShuffleIndices);
5226         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5227       }
5228       return GatherCost;
5229     }
5230     if ((E->getOpcode() == Instruction::ExtractElement ||
5231          all_of(E->Scalars,
5232                 [](Value *V) {
5233                   return isa<ExtractElementInst, UndefValue>(V);
5234                 })) &&
5235         allSameType(VL)) {
5236       // Check that gather of extractelements can be represented as just a
5237       // shuffle of a single/two vectors the scalars are extracted from.
5238       SmallVector<int> Mask;
5239       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5240           isFixedVectorShuffle(VL, Mask);
5241       if (ShuffleKind.hasValue()) {
5242         // Found the bunch of extractelement instructions that must be gathered
5243         // into a vector and can be represented as a permutation elements in a
5244         // single input vector or of 2 input vectors.
5245         InstructionCost Cost =
5246             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5247         AdjustExtractsCost(Cost);
5248         if (NeedToShuffleReuses)
5249           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5250                                       FinalVecTy, E->ReuseShuffleIndices);
5251         return Cost;
5252       }
5253     }
5254     if (isSplat(VL)) {
5255       // Found the broadcasting of the single scalar, calculate the cost as the
5256       // broadcast.
5257       assert(VecTy == FinalVecTy &&
5258              "No reused scalars expected for broadcast.");
5259       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5260                                  /*Mask=*/None, /*Index=*/0,
5261                                  /*SubTp=*/nullptr, /*Args=*/VL);
5262     }
5263     InstructionCost ReuseShuffleCost = 0;
5264     if (NeedToShuffleReuses)
5265       ReuseShuffleCost = TTI->getShuffleCost(
5266           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5267     // Improve gather cost for gather of loads, if we can group some of the
5268     // loads into vector loads.
5269     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5270         !E->isAltShuffle()) {
5271       BoUpSLP::ValueSet VectorizedLoads;
5272       unsigned StartIdx = 0;
5273       unsigned VF = VL.size() / 2;
5274       unsigned VectorizedCnt = 0;
5275       unsigned ScatterVectorizeCnt = 0;
5276       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5277       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5278         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5279              Cnt += VF) {
5280           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5281           if (!VectorizedLoads.count(Slice.front()) &&
5282               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5283             SmallVector<Value *> PointerOps;
5284             OrdersType CurrentOrder;
5285             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5286                                               *SE, CurrentOrder, PointerOps);
5287             switch (LS) {
5288             case LoadsState::Vectorize:
5289             case LoadsState::ScatterVectorize:
5290               // Mark the vectorized loads so that we don't vectorize them
5291               // again.
5292               if (LS == LoadsState::Vectorize)
5293                 ++VectorizedCnt;
5294               else
5295                 ++ScatterVectorizeCnt;
5296               VectorizedLoads.insert(Slice.begin(), Slice.end());
5297               // If we vectorized initial block, no need to try to vectorize it
5298               // again.
5299               if (Cnt == StartIdx)
5300                 StartIdx += VF;
5301               break;
5302             case LoadsState::Gather:
5303               break;
5304             }
5305           }
5306         }
5307         // Check if the whole array was vectorized already - exit.
5308         if (StartIdx >= VL.size())
5309           break;
5310         // Found vectorizable parts - exit.
5311         if (!VectorizedLoads.empty())
5312           break;
5313       }
5314       if (!VectorizedLoads.empty()) {
5315         InstructionCost GatherCost = 0;
5316         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5317         bool NeedInsertSubvectorAnalysis =
5318             !NumParts || (VL.size() / VF) > NumParts;
5319         // Get the cost for gathered loads.
5320         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5321           if (VectorizedLoads.contains(VL[I]))
5322             continue;
5323           GatherCost += getGatherCost(VL.slice(I, VF));
5324         }
5325         // The cost for vectorized loads.
5326         InstructionCost ScalarsCost = 0;
5327         for (Value *V : VectorizedLoads) {
5328           auto *LI = cast<LoadInst>(V);
5329           ScalarsCost += TTI->getMemoryOpCost(
5330               Instruction::Load, LI->getType(), LI->getAlign(),
5331               LI->getPointerAddressSpace(), CostKind, LI);
5332         }
5333         auto *LI = cast<LoadInst>(E->getMainOp());
5334         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5335         Align Alignment = LI->getAlign();
5336         GatherCost +=
5337             VectorizedCnt *
5338             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5339                                  LI->getPointerAddressSpace(), CostKind, LI);
5340         GatherCost += ScatterVectorizeCnt *
5341                       TTI->getGatherScatterOpCost(
5342                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5343                           /*VariableMask=*/false, Alignment, CostKind, LI);
5344         if (NeedInsertSubvectorAnalysis) {
5345           // Add the cost for the subvectors insert.
5346           for (int I = VF, E = VL.size(); I < E; I += VF)
5347             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5348                                               None, I, LoadTy);
5349         }
5350         return ReuseShuffleCost + GatherCost - ScalarsCost;
5351       }
5352     }
5353     return ReuseShuffleCost + getGatherCost(VL);
5354   }
5355   InstructionCost CommonCost = 0;
5356   SmallVector<int> Mask;
5357   if (!E->ReorderIndices.empty()) {
5358     SmallVector<int> NewMask;
5359     if (E->getOpcode() == Instruction::Store) {
5360       // For stores the order is actually a mask.
5361       NewMask.resize(E->ReorderIndices.size());
5362       copy(E->ReorderIndices, NewMask.begin());
5363     } else {
5364       inversePermutation(E->ReorderIndices, NewMask);
5365     }
5366     ::addMask(Mask, NewMask);
5367   }
5368   if (NeedToShuffleReuses)
5369     ::addMask(Mask, E->ReuseShuffleIndices);
5370   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5371     CommonCost =
5372         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5373   assert((E->State == TreeEntry::Vectorize ||
5374           E->State == TreeEntry::ScatterVectorize) &&
5375          "Unhandled state");
5376   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5377   Instruction *VL0 = E->getMainOp();
5378   unsigned ShuffleOrOp =
5379       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5380   switch (ShuffleOrOp) {
5381     case Instruction::PHI:
5382       return 0;
5383 
5384     case Instruction::ExtractValue:
5385     case Instruction::ExtractElement: {
5386       // The common cost of removal ExtractElement/ExtractValue instructions +
5387       // the cost of shuffles, if required to resuffle the original vector.
5388       if (NeedToShuffleReuses) {
5389         unsigned Idx = 0;
5390         for (unsigned I : E->ReuseShuffleIndices) {
5391           if (ShuffleOrOp == Instruction::ExtractElement) {
5392             auto *EE = cast<ExtractElementInst>(VL[I]);
5393             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5394                                                   EE->getVectorOperandType(),
5395                                                   *getExtractIndex(EE));
5396           } else {
5397             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5398                                                   VecTy, Idx);
5399             ++Idx;
5400           }
5401         }
5402         Idx = EntryVF;
5403         for (Value *V : VL) {
5404           if (ShuffleOrOp == Instruction::ExtractElement) {
5405             auto *EE = cast<ExtractElementInst>(V);
5406             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5407                                                   EE->getVectorOperandType(),
5408                                                   *getExtractIndex(EE));
5409           } else {
5410             --Idx;
5411             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5412                                                   VecTy, Idx);
5413           }
5414         }
5415       }
5416       if (ShuffleOrOp == Instruction::ExtractValue) {
5417         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5418           auto *EI = cast<Instruction>(VL[I]);
5419           // Take credit for instruction that will become dead.
5420           if (EI->hasOneUse()) {
5421             Instruction *Ext = EI->user_back();
5422             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5423                 all_of(Ext->users(),
5424                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5425               // Use getExtractWithExtendCost() to calculate the cost of
5426               // extractelement/ext pair.
5427               CommonCost -= TTI->getExtractWithExtendCost(
5428                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5429               // Add back the cost of s|zext which is subtracted separately.
5430               CommonCost += TTI->getCastInstrCost(
5431                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5432                   TTI::getCastContextHint(Ext), CostKind, Ext);
5433               continue;
5434             }
5435           }
5436           CommonCost -=
5437               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5438         }
5439       } else {
5440         AdjustExtractsCost(CommonCost);
5441       }
5442       return CommonCost;
5443     }
5444     case Instruction::InsertElement: {
5445       assert(E->ReuseShuffleIndices.empty() &&
5446              "Unique insertelements only are expected.");
5447       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5448 
5449       unsigned const NumElts = SrcVecTy->getNumElements();
5450       unsigned const NumScalars = VL.size();
5451       APInt DemandedElts = APInt::getZero(NumElts);
5452       // TODO: Add support for Instruction::InsertValue.
5453       SmallVector<int> Mask;
5454       if (!E->ReorderIndices.empty()) {
5455         inversePermutation(E->ReorderIndices, Mask);
5456         Mask.append(NumElts - NumScalars, UndefMaskElem);
5457       } else {
5458         Mask.assign(NumElts, UndefMaskElem);
5459         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5460       }
5461       unsigned Offset = *getInsertIndex(VL0);
5462       bool IsIdentity = true;
5463       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5464       Mask.swap(PrevMask);
5465       for (unsigned I = 0; I < NumScalars; ++I) {
5466         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5467         DemandedElts.setBit(InsertIdx);
5468         IsIdentity &= InsertIdx - Offset == I;
5469         Mask[InsertIdx - Offset] = I;
5470       }
5471       assert(Offset < NumElts && "Failed to find vector index offset");
5472 
5473       InstructionCost Cost = 0;
5474       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5475                                             /*Insert*/ true, /*Extract*/ false);
5476 
5477       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5478         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5479         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5480         Cost += TTI->getShuffleCost(
5481             TargetTransformInfo::SK_PermuteSingleSrc,
5482             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5483       } else if (!IsIdentity) {
5484         auto *FirstInsert =
5485             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5486               return !is_contained(E->Scalars,
5487                                    cast<Instruction>(V)->getOperand(0));
5488             }));
5489         if (isUndefVector(FirstInsert->getOperand(0))) {
5490           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5491         } else {
5492           SmallVector<int> InsertMask(NumElts);
5493           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5494           for (unsigned I = 0; I < NumElts; I++) {
5495             if (Mask[I] != UndefMaskElem)
5496               InsertMask[Offset + I] = NumElts + I;
5497           }
5498           Cost +=
5499               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5500         }
5501       }
5502 
5503       return Cost;
5504     }
5505     case Instruction::ZExt:
5506     case Instruction::SExt:
5507     case Instruction::FPToUI:
5508     case Instruction::FPToSI:
5509     case Instruction::FPExt:
5510     case Instruction::PtrToInt:
5511     case Instruction::IntToPtr:
5512     case Instruction::SIToFP:
5513     case Instruction::UIToFP:
5514     case Instruction::Trunc:
5515     case Instruction::FPTrunc:
5516     case Instruction::BitCast: {
5517       Type *SrcTy = VL0->getOperand(0)->getType();
5518       InstructionCost ScalarEltCost =
5519           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5520                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5521       if (NeedToShuffleReuses) {
5522         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5523       }
5524 
5525       // Calculate the cost of this instruction.
5526       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5527 
5528       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5529       InstructionCost VecCost = 0;
5530       // Check if the values are candidates to demote.
5531       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5532         VecCost = CommonCost + TTI->getCastInstrCost(
5533                                    E->getOpcode(), VecTy, SrcVecTy,
5534                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5535       }
5536       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5537       return VecCost - ScalarCost;
5538     }
5539     case Instruction::FCmp:
5540     case Instruction::ICmp:
5541     case Instruction::Select: {
5542       // Calculate the cost of this instruction.
5543       InstructionCost ScalarEltCost =
5544           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5545                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5546       if (NeedToShuffleReuses) {
5547         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5548       }
5549       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5550       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5551 
5552       // Check if all entries in VL are either compares or selects with compares
5553       // as condition that have the same predicates.
5554       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5555       bool First = true;
5556       for (auto *V : VL) {
5557         CmpInst::Predicate CurrentPred;
5558         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5559         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5560              !match(V, MatchCmp)) ||
5561             (!First && VecPred != CurrentPred)) {
5562           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5563           break;
5564         }
5565         First = false;
5566         VecPred = CurrentPred;
5567       }
5568 
5569       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5570           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5571       // Check if it is possible and profitable to use min/max for selects in
5572       // VL.
5573       //
5574       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5575       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5576         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5577                                           {VecTy, VecTy});
5578         InstructionCost IntrinsicCost =
5579             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5580         // If the selects are the only uses of the compares, they will be dead
5581         // and we can adjust the cost by removing their cost.
5582         if (IntrinsicAndUse.second)
5583           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5584                                                    MaskTy, VecPred, CostKind);
5585         VecCost = std::min(VecCost, IntrinsicCost);
5586       }
5587       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5588       return CommonCost + VecCost - ScalarCost;
5589     }
5590     case Instruction::FNeg:
5591     case Instruction::Add:
5592     case Instruction::FAdd:
5593     case Instruction::Sub:
5594     case Instruction::FSub:
5595     case Instruction::Mul:
5596     case Instruction::FMul:
5597     case Instruction::UDiv:
5598     case Instruction::SDiv:
5599     case Instruction::FDiv:
5600     case Instruction::URem:
5601     case Instruction::SRem:
5602     case Instruction::FRem:
5603     case Instruction::Shl:
5604     case Instruction::LShr:
5605     case Instruction::AShr:
5606     case Instruction::And:
5607     case Instruction::Or:
5608     case Instruction::Xor: {
5609       // Certain instructions can be cheaper to vectorize if they have a
5610       // constant second vector operand.
5611       TargetTransformInfo::OperandValueKind Op1VK =
5612           TargetTransformInfo::OK_AnyValue;
5613       TargetTransformInfo::OperandValueKind Op2VK =
5614           TargetTransformInfo::OK_UniformConstantValue;
5615       TargetTransformInfo::OperandValueProperties Op1VP =
5616           TargetTransformInfo::OP_None;
5617       TargetTransformInfo::OperandValueProperties Op2VP =
5618           TargetTransformInfo::OP_PowerOf2;
5619 
5620       // If all operands are exactly the same ConstantInt then set the
5621       // operand kind to OK_UniformConstantValue.
5622       // If instead not all operands are constants, then set the operand kind
5623       // to OK_AnyValue. If all operands are constants but not the same,
5624       // then set the operand kind to OK_NonUniformConstantValue.
5625       ConstantInt *CInt0 = nullptr;
5626       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5627         const Instruction *I = cast<Instruction>(VL[i]);
5628         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5629         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5630         if (!CInt) {
5631           Op2VK = TargetTransformInfo::OK_AnyValue;
5632           Op2VP = TargetTransformInfo::OP_None;
5633           break;
5634         }
5635         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5636             !CInt->getValue().isPowerOf2())
5637           Op2VP = TargetTransformInfo::OP_None;
5638         if (i == 0) {
5639           CInt0 = CInt;
5640           continue;
5641         }
5642         if (CInt0 != CInt)
5643           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5644       }
5645 
5646       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5647       InstructionCost ScalarEltCost =
5648           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5649                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5650       if (NeedToShuffleReuses) {
5651         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5652       }
5653       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5654       InstructionCost VecCost =
5655           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5656                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5657       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5658       return CommonCost + VecCost - ScalarCost;
5659     }
5660     case Instruction::GetElementPtr: {
5661       TargetTransformInfo::OperandValueKind Op1VK =
5662           TargetTransformInfo::OK_AnyValue;
5663       TargetTransformInfo::OperandValueKind Op2VK =
5664           TargetTransformInfo::OK_UniformConstantValue;
5665 
5666       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5667           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5668       if (NeedToShuffleReuses) {
5669         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5670       }
5671       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5672       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5673           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5674       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5675       return CommonCost + VecCost - ScalarCost;
5676     }
5677     case Instruction::Load: {
5678       // Cost of wide load - cost of scalar loads.
5679       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5680       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5681           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5682       if (NeedToShuffleReuses) {
5683         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5684       }
5685       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5686       InstructionCost VecLdCost;
5687       if (E->State == TreeEntry::Vectorize) {
5688         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5689                                          CostKind, VL0);
5690       } else {
5691         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5692         Align CommonAlignment = Alignment;
5693         for (Value *V : VL)
5694           CommonAlignment =
5695               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5696         VecLdCost = TTI->getGatherScatterOpCost(
5697             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5698             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5699       }
5700       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5701       return CommonCost + VecLdCost - ScalarLdCost;
5702     }
5703     case Instruction::Store: {
5704       // We know that we can merge the stores. Calculate the cost.
5705       bool IsReorder = !E->ReorderIndices.empty();
5706       auto *SI =
5707           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5708       Align Alignment = SI->getAlign();
5709       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5710           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5711       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5712       InstructionCost VecStCost = TTI->getMemoryOpCost(
5713           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5714       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5715       return CommonCost + VecStCost - ScalarStCost;
5716     }
5717     case Instruction::Call: {
5718       CallInst *CI = cast<CallInst>(VL0);
5719       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5720 
5721       // Calculate the cost of the scalar and vector calls.
5722       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5723       InstructionCost ScalarEltCost =
5724           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5725       if (NeedToShuffleReuses) {
5726         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5727       }
5728       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5729 
5730       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5731       InstructionCost VecCallCost =
5732           std::min(VecCallCosts.first, VecCallCosts.second);
5733 
5734       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5735                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5736                         << " for " << *CI << "\n");
5737 
5738       return CommonCost + VecCallCost - ScalarCallCost;
5739     }
5740     case Instruction::ShuffleVector: {
5741       assert(E->isAltShuffle() &&
5742              ((Instruction::isBinaryOp(E->getOpcode()) &&
5743                Instruction::isBinaryOp(E->getAltOpcode())) ||
5744               (Instruction::isCast(E->getOpcode()) &&
5745                Instruction::isCast(E->getAltOpcode())) ||
5746               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5747              "Invalid Shuffle Vector Operand");
5748       InstructionCost ScalarCost = 0;
5749       if (NeedToShuffleReuses) {
5750         for (unsigned Idx : E->ReuseShuffleIndices) {
5751           Instruction *I = cast<Instruction>(VL[Idx]);
5752           CommonCost -= TTI->getInstructionCost(I, CostKind);
5753         }
5754         for (Value *V : VL) {
5755           Instruction *I = cast<Instruction>(V);
5756           CommonCost += TTI->getInstructionCost(I, CostKind);
5757         }
5758       }
5759       for (Value *V : VL) {
5760         Instruction *I = cast<Instruction>(V);
5761         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5762         ScalarCost += TTI->getInstructionCost(I, CostKind);
5763       }
5764       // VecCost is equal to sum of the cost of creating 2 vectors
5765       // and the cost of creating shuffle.
5766       InstructionCost VecCost = 0;
5767       // Try to find the previous shuffle node with the same operands and same
5768       // main/alternate ops.
5769       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5770         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5771           if (TE.get() == E)
5772             break;
5773           if (TE->isAltShuffle() &&
5774               ((TE->getOpcode() == E->getOpcode() &&
5775                 TE->getAltOpcode() == E->getAltOpcode()) ||
5776                (TE->getOpcode() == E->getAltOpcode() &&
5777                 TE->getAltOpcode() == E->getOpcode())) &&
5778               TE->hasEqualOperands(*E))
5779             return true;
5780         }
5781         return false;
5782       };
5783       if (TryFindNodeWithEqualOperands()) {
5784         LLVM_DEBUG({
5785           dbgs() << "SLP: diamond match for alternate node found.\n";
5786           E->dump();
5787         });
5788         // No need to add new vector costs here since we're going to reuse
5789         // same main/alternate vector ops, just do different shuffling.
5790       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5791         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5792         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5793                                                CostKind);
5794       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5795         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5796                                           Builder.getInt1Ty(),
5797                                           CI0->getPredicate(), CostKind, VL0);
5798         VecCost += TTI->getCmpSelInstrCost(
5799             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5800             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5801             E->getAltOp());
5802       } else {
5803         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5804         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5805         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5806         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5807         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5808                                         TTI::CastContextHint::None, CostKind);
5809         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5810                                          TTI::CastContextHint::None, CostKind);
5811       }
5812 
5813       SmallVector<int> Mask;
5814       buildShuffleEntryMask(
5815           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5816           [E](Instruction *I) {
5817             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5818             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5819           },
5820           Mask);
5821       CommonCost =
5822           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5823       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5824       return CommonCost + VecCost - ScalarCost;
5825     }
5826     default:
5827       llvm_unreachable("Unknown instruction");
5828   }
5829 }
5830 
5831 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5832   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5833                     << VectorizableTree.size() << " is fully vectorizable .\n");
5834 
5835   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5836     SmallVector<int> Mask;
5837     return TE->State == TreeEntry::NeedToGather &&
5838            !any_of(TE->Scalars,
5839                    [this](Value *V) { return EphValues.contains(V); }) &&
5840            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5841             TE->Scalars.size() < Limit ||
5842             ((TE->getOpcode() == Instruction::ExtractElement ||
5843               all_of(TE->Scalars,
5844                      [](Value *V) {
5845                        return isa<ExtractElementInst, UndefValue>(V);
5846                      })) &&
5847              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5848             (TE->State == TreeEntry::NeedToGather &&
5849              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5850   };
5851 
5852   // We only handle trees of heights 1 and 2.
5853   if (VectorizableTree.size() == 1 &&
5854       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5855        (ForReduction &&
5856         AreVectorizableGathers(VectorizableTree[0].get(),
5857                                VectorizableTree[0]->Scalars.size()) &&
5858         VectorizableTree[0]->getVectorFactor() > 2)))
5859     return true;
5860 
5861   if (VectorizableTree.size() != 2)
5862     return false;
5863 
5864   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5865   // with the second gather nodes if they have less scalar operands rather than
5866   // the initial tree element (may be profitable to shuffle the second gather)
5867   // or they are extractelements, which form shuffle.
5868   SmallVector<int> Mask;
5869   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5870       AreVectorizableGathers(VectorizableTree[1].get(),
5871                              VectorizableTree[0]->Scalars.size()))
5872     return true;
5873 
5874   // Gathering cost would be too much for tiny trees.
5875   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5876       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5877        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5878     return false;
5879 
5880   return true;
5881 }
5882 
5883 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5884                                        TargetTransformInfo *TTI,
5885                                        bool MustMatchOrInst) {
5886   // Look past the root to find a source value. Arbitrarily follow the
5887   // path through operand 0 of any 'or'. Also, peek through optional
5888   // shift-left-by-multiple-of-8-bits.
5889   Value *ZextLoad = Root;
5890   const APInt *ShAmtC;
5891   bool FoundOr = false;
5892   while (!isa<ConstantExpr>(ZextLoad) &&
5893          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5894           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5895            ShAmtC->urem(8) == 0))) {
5896     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5897     ZextLoad = BinOp->getOperand(0);
5898     if (BinOp->getOpcode() == Instruction::Or)
5899       FoundOr = true;
5900   }
5901   // Check if the input is an extended load of the required or/shift expression.
5902   Value *Load;
5903   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5904       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5905     return false;
5906 
5907   // Require that the total load bit width is a legal integer type.
5908   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5909   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5910   Type *SrcTy = Load->getType();
5911   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5912   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5913     return false;
5914 
5915   // Everything matched - assume that we can fold the whole sequence using
5916   // load combining.
5917   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5918              << *(cast<Instruction>(Root)) << "\n");
5919 
5920   return true;
5921 }
5922 
5923 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5924   if (RdxKind != RecurKind::Or)
5925     return false;
5926 
5927   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5928   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5929   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5930                                     /* MatchOr */ false);
5931 }
5932 
5933 bool BoUpSLP::isLoadCombineCandidate() const {
5934   // Peek through a final sequence of stores and check if all operations are
5935   // likely to be load-combined.
5936   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5937   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5938     Value *X;
5939     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5940         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5941       return false;
5942   }
5943   return true;
5944 }
5945 
5946 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5947   // No need to vectorize inserts of gathered values.
5948   if (VectorizableTree.size() == 2 &&
5949       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5950       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5951     return true;
5952 
5953   // We can vectorize the tree if its size is greater than or equal to the
5954   // minimum size specified by the MinTreeSize command line option.
5955   if (VectorizableTree.size() >= MinTreeSize)
5956     return false;
5957 
5958   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5959   // can vectorize it if we can prove it fully vectorizable.
5960   if (isFullyVectorizableTinyTree(ForReduction))
5961     return false;
5962 
5963   assert(VectorizableTree.empty()
5964              ? ExternalUses.empty()
5965              : true && "We shouldn't have any external users");
5966 
5967   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5968   // vectorizable.
5969   return true;
5970 }
5971 
5972 InstructionCost BoUpSLP::getSpillCost() const {
5973   // Walk from the bottom of the tree to the top, tracking which values are
5974   // live. When we see a call instruction that is not part of our tree,
5975   // query TTI to see if there is a cost to keeping values live over it
5976   // (for example, if spills and fills are required).
5977   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5978   InstructionCost Cost = 0;
5979 
5980   SmallPtrSet<Instruction*, 4> LiveValues;
5981   Instruction *PrevInst = nullptr;
5982 
5983   // The entries in VectorizableTree are not necessarily ordered by their
5984   // position in basic blocks. Collect them and order them by dominance so later
5985   // instructions are guaranteed to be visited first. For instructions in
5986   // different basic blocks, we only scan to the beginning of the block, so
5987   // their order does not matter, as long as all instructions in a basic block
5988   // are grouped together. Using dominance ensures a deterministic order.
5989   SmallVector<Instruction *, 16> OrderedScalars;
5990   for (const auto &TEPtr : VectorizableTree) {
5991     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5992     if (!Inst)
5993       continue;
5994     OrderedScalars.push_back(Inst);
5995   }
5996   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5997     auto *NodeA = DT->getNode(A->getParent());
5998     auto *NodeB = DT->getNode(B->getParent());
5999     assert(NodeA && "Should only process reachable instructions");
6000     assert(NodeB && "Should only process reachable instructions");
6001     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6002            "Different nodes should have different DFS numbers");
6003     if (NodeA != NodeB)
6004       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6005     return B->comesBefore(A);
6006   });
6007 
6008   for (Instruction *Inst : OrderedScalars) {
6009     if (!PrevInst) {
6010       PrevInst = Inst;
6011       continue;
6012     }
6013 
6014     // Update LiveValues.
6015     LiveValues.erase(PrevInst);
6016     for (auto &J : PrevInst->operands()) {
6017       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6018         LiveValues.insert(cast<Instruction>(&*J));
6019     }
6020 
6021     LLVM_DEBUG({
6022       dbgs() << "SLP: #LV: " << LiveValues.size();
6023       for (auto *X : LiveValues)
6024         dbgs() << " " << X->getName();
6025       dbgs() << ", Looking at ";
6026       Inst->dump();
6027     });
6028 
6029     // Now find the sequence of instructions between PrevInst and Inst.
6030     unsigned NumCalls = 0;
6031     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6032                                  PrevInstIt =
6033                                      PrevInst->getIterator().getReverse();
6034     while (InstIt != PrevInstIt) {
6035       if (PrevInstIt == PrevInst->getParent()->rend()) {
6036         PrevInstIt = Inst->getParent()->rbegin();
6037         continue;
6038       }
6039 
6040       // Debug information does not impact spill cost.
6041       if ((isa<CallInst>(&*PrevInstIt) &&
6042            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6043           &*PrevInstIt != PrevInst)
6044         NumCalls++;
6045 
6046       ++PrevInstIt;
6047     }
6048 
6049     if (NumCalls) {
6050       SmallVector<Type*, 4> V;
6051       for (auto *II : LiveValues) {
6052         auto *ScalarTy = II->getType();
6053         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6054           ScalarTy = VectorTy->getElementType();
6055         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6056       }
6057       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6058     }
6059 
6060     PrevInst = Inst;
6061   }
6062 
6063   return Cost;
6064 }
6065 
6066 /// Check if two insertelement instructions are from the same buildvector.
6067 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6068                                             InsertElementInst *V) {
6069   // Instructions must be from the same basic blocks.
6070   if (VU->getParent() != V->getParent())
6071     return false;
6072   // Checks if 2 insertelements are from the same buildvector.
6073   if (VU->getType() != V->getType())
6074     return false;
6075   // Multiple used inserts are separate nodes.
6076   if (!VU->hasOneUse() && !V->hasOneUse())
6077     return false;
6078   auto *IE1 = VU;
6079   auto *IE2 = V;
6080   // Go through the vector operand of insertelement instructions trying to find
6081   // either VU as the original vector for IE2 or V as the original vector for
6082   // IE1.
6083   do {
6084     if (IE2 == VU || IE1 == V)
6085       return true;
6086     if (IE1) {
6087       if (IE1 != VU && !IE1->hasOneUse())
6088         IE1 = nullptr;
6089       else
6090         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6091     }
6092     if (IE2) {
6093       if (IE2 != V && !IE2->hasOneUse())
6094         IE2 = nullptr;
6095       else
6096         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6097     }
6098   } while (IE1 || IE2);
6099   return false;
6100 }
6101 
6102 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6103   InstructionCost Cost = 0;
6104   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6105                     << VectorizableTree.size() << ".\n");
6106 
6107   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6108 
6109   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6110     TreeEntry &TE = *VectorizableTree[I];
6111 
6112     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6113     Cost += C;
6114     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6115                       << " for bundle that starts with " << *TE.Scalars[0]
6116                       << ".\n"
6117                       << "SLP: Current total cost = " << Cost << "\n");
6118   }
6119 
6120   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6121   InstructionCost ExtractCost = 0;
6122   SmallVector<unsigned> VF;
6123   SmallVector<SmallVector<int>> ShuffleMask;
6124   SmallVector<Value *> FirstUsers;
6125   SmallVector<APInt> DemandedElts;
6126   for (ExternalUser &EU : ExternalUses) {
6127     // We only add extract cost once for the same scalar.
6128     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6129         !ExtractCostCalculated.insert(EU.Scalar).second)
6130       continue;
6131 
6132     // Uses by ephemeral values are free (because the ephemeral value will be
6133     // removed prior to code generation, and so the extraction will be
6134     // removed as well).
6135     if (EphValues.count(EU.User))
6136       continue;
6137 
6138     // No extract cost for vector "scalar"
6139     if (isa<FixedVectorType>(EU.Scalar->getType()))
6140       continue;
6141 
6142     // Already counted the cost for external uses when tried to adjust the cost
6143     // for extractelements, no need to add it again.
6144     if (isa<ExtractElementInst>(EU.Scalar))
6145       continue;
6146 
6147     // If found user is an insertelement, do not calculate extract cost but try
6148     // to detect it as a final shuffled/identity match.
6149     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6150       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6151         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6152         if (InsertIdx) {
6153           auto *It = find_if(FirstUsers, [VU](Value *V) {
6154             return areTwoInsertFromSameBuildVector(VU,
6155                                                    cast<InsertElementInst>(V));
6156           });
6157           int VecId = -1;
6158           if (It == FirstUsers.end()) {
6159             VF.push_back(FTy->getNumElements());
6160             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6161             // Find the insertvector, vectorized in tree, if any.
6162             Value *Base = VU;
6163             while (isa<InsertElementInst>(Base)) {
6164               // Build the mask for the vectorized insertelement instructions.
6165               if (const TreeEntry *E = getTreeEntry(Base)) {
6166                 VU = cast<InsertElementInst>(Base);
6167                 do {
6168                   int Idx = E->findLaneForValue(Base);
6169                   ShuffleMask.back()[Idx] = Idx;
6170                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6171                 } while (E == getTreeEntry(Base));
6172                 break;
6173               }
6174               Base = cast<InsertElementInst>(Base)->getOperand(0);
6175             }
6176             FirstUsers.push_back(VU);
6177             DemandedElts.push_back(APInt::getZero(VF.back()));
6178             VecId = FirstUsers.size() - 1;
6179           } else {
6180             VecId = std::distance(FirstUsers.begin(), It);
6181           }
6182           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6183           DemandedElts[VecId].setBit(*InsertIdx);
6184           continue;
6185         }
6186       }
6187     }
6188 
6189     // If we plan to rewrite the tree in a smaller type, we will need to sign
6190     // extend the extracted value back to the original type. Here, we account
6191     // for the extract and the added cost of the sign extend if needed.
6192     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6193     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6194     if (MinBWs.count(ScalarRoot)) {
6195       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6196       auto Extend =
6197           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6198       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6199       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6200                                                    VecTy, EU.Lane);
6201     } else {
6202       ExtractCost +=
6203           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6204     }
6205   }
6206 
6207   InstructionCost SpillCost = getSpillCost();
6208   Cost += SpillCost + ExtractCost;
6209   if (FirstUsers.size() == 1) {
6210     int Limit = ShuffleMask.front().size() * 2;
6211     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6212         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6213       InstructionCost C = TTI->getShuffleCost(
6214           TTI::SK_PermuteSingleSrc,
6215           cast<FixedVectorType>(FirstUsers.front()->getType()),
6216           ShuffleMask.front());
6217       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6218                         << " for final shuffle of insertelement external users "
6219                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6220                         << "SLP: Current total cost = " << Cost << "\n");
6221       Cost += C;
6222     }
6223     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6224         cast<FixedVectorType>(FirstUsers.front()->getType()),
6225         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6226     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6227                       << " for insertelements gather.\n"
6228                       << "SLP: Current total cost = " << Cost << "\n");
6229     Cost -= InsertCost;
6230   } else if (FirstUsers.size() >= 2) {
6231     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6232     // Combined masks of the first 2 vectors.
6233     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6234     copy(ShuffleMask.front(), CombinedMask.begin());
6235     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6236     auto *VecTy = FixedVectorType::get(
6237         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6238         MaxVF);
6239     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6240       if (ShuffleMask[1][I] != UndefMaskElem) {
6241         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6242         CombinedDemandedElts.setBit(I);
6243       }
6244     }
6245     InstructionCost C =
6246         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6247     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6248                       << " for final shuffle of vector node and external "
6249                          "insertelement users "
6250                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6251                       << "SLP: Current total cost = " << Cost << "\n");
6252     Cost += C;
6253     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6254         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6255     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6256                       << " for insertelements gather.\n"
6257                       << "SLP: Current total cost = " << Cost << "\n");
6258     Cost -= InsertCost;
6259     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6260       // Other elements - permutation of 2 vectors (the initial one and the
6261       // next Ith incoming vector).
6262       unsigned VF = ShuffleMask[I].size();
6263       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6264         int Mask = ShuffleMask[I][Idx];
6265         if (Mask != UndefMaskElem)
6266           CombinedMask[Idx] = MaxVF + Mask;
6267         else if (CombinedMask[Idx] != UndefMaskElem)
6268           CombinedMask[Idx] = Idx;
6269       }
6270       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6271         if (CombinedMask[Idx] != UndefMaskElem)
6272           CombinedMask[Idx] = Idx;
6273       InstructionCost C =
6274           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6275       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6276                         << " for final shuffle of vector node and external "
6277                            "insertelement users "
6278                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6279                         << "SLP: Current total cost = " << Cost << "\n");
6280       Cost += C;
6281       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6282           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6283           /*Insert*/ true, /*Extract*/ false);
6284       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6285                         << " for insertelements gather.\n"
6286                         << "SLP: Current total cost = " << Cost << "\n");
6287       Cost -= InsertCost;
6288     }
6289   }
6290 
6291 #ifndef NDEBUG
6292   SmallString<256> Str;
6293   {
6294     raw_svector_ostream OS(Str);
6295     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6296        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6297        << "SLP: Total Cost = " << Cost << ".\n";
6298   }
6299   LLVM_DEBUG(dbgs() << Str);
6300   if (ViewSLPTree)
6301     ViewGraph(this, "SLP" + F->getName(), false, Str);
6302 #endif
6303 
6304   return Cost;
6305 }
6306 
6307 Optional<TargetTransformInfo::ShuffleKind>
6308 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6309                                SmallVectorImpl<const TreeEntry *> &Entries) {
6310   // TODO: currently checking only for Scalars in the tree entry, need to count
6311   // reused elements too for better cost estimation.
6312   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6313   Entries.clear();
6314   // Build a lists of values to tree entries.
6315   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6316   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6317     if (EntryPtr.get() == TE)
6318       break;
6319     if (EntryPtr->State != TreeEntry::NeedToGather)
6320       continue;
6321     for (Value *V : EntryPtr->Scalars)
6322       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6323   }
6324   // Find all tree entries used by the gathered values. If no common entries
6325   // found - not a shuffle.
6326   // Here we build a set of tree nodes for each gathered value and trying to
6327   // find the intersection between these sets. If we have at least one common
6328   // tree node for each gathered value - we have just a permutation of the
6329   // single vector. If we have 2 different sets, we're in situation where we
6330   // have a permutation of 2 input vectors.
6331   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6332   DenseMap<Value *, int> UsedValuesEntry;
6333   for (Value *V : TE->Scalars) {
6334     if (isa<UndefValue>(V))
6335       continue;
6336     // Build a list of tree entries where V is used.
6337     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6338     auto It = ValueToTEs.find(V);
6339     if (It != ValueToTEs.end())
6340       VToTEs = It->second;
6341     if (const TreeEntry *VTE = getTreeEntry(V))
6342       VToTEs.insert(VTE);
6343     if (VToTEs.empty())
6344       return None;
6345     if (UsedTEs.empty()) {
6346       // The first iteration, just insert the list of nodes to vector.
6347       UsedTEs.push_back(VToTEs);
6348     } else {
6349       // Need to check if there are any previously used tree nodes which use V.
6350       // If there are no such nodes, consider that we have another one input
6351       // vector.
6352       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6353       unsigned Idx = 0;
6354       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6355         // Do we have a non-empty intersection of previously listed tree entries
6356         // and tree entries using current V?
6357         set_intersect(VToTEs, Set);
6358         if (!VToTEs.empty()) {
6359           // Yes, write the new subset and continue analysis for the next
6360           // scalar.
6361           Set.swap(VToTEs);
6362           break;
6363         }
6364         VToTEs = SavedVToTEs;
6365         ++Idx;
6366       }
6367       // No non-empty intersection found - need to add a second set of possible
6368       // source vectors.
6369       if (Idx == UsedTEs.size()) {
6370         // If the number of input vectors is greater than 2 - not a permutation,
6371         // fallback to the regular gather.
6372         if (UsedTEs.size() == 2)
6373           return None;
6374         UsedTEs.push_back(SavedVToTEs);
6375         Idx = UsedTEs.size() - 1;
6376       }
6377       UsedValuesEntry.try_emplace(V, Idx);
6378     }
6379   }
6380 
6381   unsigned VF = 0;
6382   if (UsedTEs.size() == 1) {
6383     // Try to find the perfect match in another gather node at first.
6384     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6385       return EntryPtr->isSame(TE->Scalars);
6386     });
6387     if (It != UsedTEs.front().end()) {
6388       Entries.push_back(*It);
6389       std::iota(Mask.begin(), Mask.end(), 0);
6390       return TargetTransformInfo::SK_PermuteSingleSrc;
6391     }
6392     // No perfect match, just shuffle, so choose the first tree node.
6393     Entries.push_back(*UsedTEs.front().begin());
6394   } else {
6395     // Try to find nodes with the same vector factor.
6396     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6397     DenseMap<int, const TreeEntry *> VFToTE;
6398     for (const TreeEntry *TE : UsedTEs.front())
6399       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6400     for (const TreeEntry *TE : UsedTEs.back()) {
6401       auto It = VFToTE.find(TE->getVectorFactor());
6402       if (It != VFToTE.end()) {
6403         VF = It->first;
6404         Entries.push_back(It->second);
6405         Entries.push_back(TE);
6406         break;
6407       }
6408     }
6409     // No 2 source vectors with the same vector factor - give up and do regular
6410     // gather.
6411     if (Entries.empty())
6412       return None;
6413   }
6414 
6415   // Build a shuffle mask for better cost estimation and vector emission.
6416   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6417     Value *V = TE->Scalars[I];
6418     if (isa<UndefValue>(V))
6419       continue;
6420     unsigned Idx = UsedValuesEntry.lookup(V);
6421     const TreeEntry *VTE = Entries[Idx];
6422     int FoundLane = VTE->findLaneForValue(V);
6423     Mask[I] = Idx * VF + FoundLane;
6424     // Extra check required by isSingleSourceMaskImpl function (called by
6425     // ShuffleVectorInst::isSingleSourceMask).
6426     if (Mask[I] >= 2 * E)
6427       return None;
6428   }
6429   switch (Entries.size()) {
6430   case 1:
6431     return TargetTransformInfo::SK_PermuteSingleSrc;
6432   case 2:
6433     return TargetTransformInfo::SK_PermuteTwoSrc;
6434   default:
6435     break;
6436   }
6437   return None;
6438 }
6439 
6440 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6441                                        const APInt &ShuffledIndices,
6442                                        bool NeedToShuffle) const {
6443   InstructionCost Cost =
6444       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6445                                     /*Extract*/ false);
6446   if (NeedToShuffle)
6447     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6448   return Cost;
6449 }
6450 
6451 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6452   // Find the type of the operands in VL.
6453   Type *ScalarTy = VL[0]->getType();
6454   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6455     ScalarTy = SI->getValueOperand()->getType();
6456   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6457   bool DuplicateNonConst = false;
6458   // Find the cost of inserting/extracting values from the vector.
6459   // Check if the same elements are inserted several times and count them as
6460   // shuffle candidates.
6461   APInt ShuffledElements = APInt::getZero(VL.size());
6462   DenseSet<Value *> UniqueElements;
6463   // Iterate in reverse order to consider insert elements with the high cost.
6464   for (unsigned I = VL.size(); I > 0; --I) {
6465     unsigned Idx = I - 1;
6466     // No need to shuffle duplicates for constants.
6467     if (isConstant(VL[Idx])) {
6468       ShuffledElements.setBit(Idx);
6469       continue;
6470     }
6471     if (!UniqueElements.insert(VL[Idx]).second) {
6472       DuplicateNonConst = true;
6473       ShuffledElements.setBit(Idx);
6474     }
6475   }
6476   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6477 }
6478 
6479 // Perform operand reordering on the instructions in VL and return the reordered
6480 // operands in Left and Right.
6481 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6482                                              SmallVectorImpl<Value *> &Left,
6483                                              SmallVectorImpl<Value *> &Right,
6484                                              const DataLayout &DL,
6485                                              ScalarEvolution &SE,
6486                                              const BoUpSLP &R) {
6487   if (VL.empty())
6488     return;
6489   VLOperands Ops(VL, DL, SE, R);
6490   // Reorder the operands in place.
6491   Ops.reorder();
6492   Left = Ops.getVL(0);
6493   Right = Ops.getVL(1);
6494 }
6495 
6496 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6497   // Get the basic block this bundle is in. All instructions in the bundle
6498   // should be in this block.
6499   auto *Front = E->getMainOp();
6500   auto *BB = Front->getParent();
6501   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6502     auto *I = cast<Instruction>(V);
6503     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6504   }));
6505 
6506   auto &&FindLastInst = [E, Front]() {
6507     Instruction *LastInst = Front;
6508     for (Value *V : E->Scalars) {
6509       auto *I = dyn_cast<Instruction>(V);
6510       if (!I)
6511         continue;
6512       if (LastInst->comesBefore(I))
6513         LastInst = I;
6514     }
6515     return LastInst;
6516   };
6517 
6518   auto &&FindFirstInst = [E, Front]() {
6519     Instruction *FirstInst = Front;
6520     for (Value *V : E->Scalars) {
6521       auto *I = dyn_cast<Instruction>(V);
6522       if (!I)
6523         continue;
6524       if (I->comesBefore(FirstInst))
6525         FirstInst = I;
6526     }
6527     return FirstInst;
6528   };
6529 
6530   // Set the insert point to the beginning of the basic block if the entry
6531   // should not be scheduled.
6532   if (E->State != TreeEntry::NeedToGather &&
6533       doesNotNeedToSchedule(E->Scalars)) {
6534     BasicBlock::iterator InsertPt;
6535     if (all_of(E->Scalars, isUsedOutsideBlock))
6536       InsertPt = FindLastInst()->getIterator();
6537     else
6538       InsertPt = FindFirstInst()->getIterator();
6539     Builder.SetInsertPoint(BB, InsertPt);
6540     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6541     return;
6542   }
6543 
6544   // The last instruction in the bundle in program order.
6545   Instruction *LastInst = nullptr;
6546 
6547   // Find the last instruction. The common case should be that BB has been
6548   // scheduled, and the last instruction is VL.back(). So we start with
6549   // VL.back() and iterate over schedule data until we reach the end of the
6550   // bundle. The end of the bundle is marked by null ScheduleData.
6551   if (BlocksSchedules.count(BB)) {
6552     Value *V = E->isOneOf(E->Scalars.back());
6553     if (doesNotNeedToBeScheduled(V))
6554       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6555     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6556     if (Bundle && Bundle->isPartOfBundle())
6557       for (; Bundle; Bundle = Bundle->NextInBundle)
6558         if (Bundle->OpValue == Bundle->Inst)
6559           LastInst = Bundle->Inst;
6560   }
6561 
6562   // LastInst can still be null at this point if there's either not an entry
6563   // for BB in BlocksSchedules or there's no ScheduleData available for
6564   // VL.back(). This can be the case if buildTree_rec aborts for various
6565   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6566   // size is reached, etc.). ScheduleData is initialized in the scheduling
6567   // "dry-run".
6568   //
6569   // If this happens, we can still find the last instruction by brute force. We
6570   // iterate forwards from Front (inclusive) until we either see all
6571   // instructions in the bundle or reach the end of the block. If Front is the
6572   // last instruction in program order, LastInst will be set to Front, and we
6573   // will visit all the remaining instructions in the block.
6574   //
6575   // One of the reasons we exit early from buildTree_rec is to place an upper
6576   // bound on compile-time. Thus, taking an additional compile-time hit here is
6577   // not ideal. However, this should be exceedingly rare since it requires that
6578   // we both exit early from buildTree_rec and that the bundle be out-of-order
6579   // (causing us to iterate all the way to the end of the block).
6580   if (!LastInst)
6581     LastInst = FindLastInst();
6582   assert(LastInst && "Failed to find last instruction in bundle");
6583 
6584   // Set the insertion point after the last instruction in the bundle. Set the
6585   // debug location to Front.
6586   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6587   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6588 }
6589 
6590 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6591   // List of instructions/lanes from current block and/or the blocks which are
6592   // part of the current loop. These instructions will be inserted at the end to
6593   // make it possible to optimize loops and hoist invariant instructions out of
6594   // the loops body with better chances for success.
6595   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6596   SmallSet<int, 4> PostponedIndices;
6597   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6598   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6599     SmallPtrSet<BasicBlock *, 4> Visited;
6600     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6601       InsertBB = InsertBB->getSinglePredecessor();
6602     return InsertBB && InsertBB == InstBB;
6603   };
6604   for (int I = 0, E = VL.size(); I < E; ++I) {
6605     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6606       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6607            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6608           PostponedIndices.insert(I).second)
6609         PostponedInsts.emplace_back(Inst, I);
6610   }
6611 
6612   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6613     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6614     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6615     if (!InsElt)
6616       return Vec;
6617     GatherShuffleSeq.insert(InsElt);
6618     CSEBlocks.insert(InsElt->getParent());
6619     // Add to our 'need-to-extract' list.
6620     if (TreeEntry *Entry = getTreeEntry(V)) {
6621       // Find which lane we need to extract.
6622       unsigned FoundLane = Entry->findLaneForValue(V);
6623       ExternalUses.emplace_back(V, InsElt, FoundLane);
6624     }
6625     return Vec;
6626   };
6627   Value *Val0 =
6628       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6629   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6630   Value *Vec = PoisonValue::get(VecTy);
6631   SmallVector<int> NonConsts;
6632   // Insert constant values at first.
6633   for (int I = 0, E = VL.size(); I < E; ++I) {
6634     if (PostponedIndices.contains(I))
6635       continue;
6636     if (!isConstant(VL[I])) {
6637       NonConsts.push_back(I);
6638       continue;
6639     }
6640     Vec = CreateInsertElement(Vec, VL[I], I);
6641   }
6642   // Insert non-constant values.
6643   for (int I : NonConsts)
6644     Vec = CreateInsertElement(Vec, VL[I], I);
6645   // Append instructions, which are/may be part of the loop, in the end to make
6646   // it possible to hoist non-loop-based instructions.
6647   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6648     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6649 
6650   return Vec;
6651 }
6652 
6653 namespace {
6654 /// Merges shuffle masks and emits final shuffle instruction, if required.
6655 class ShuffleInstructionBuilder {
6656   IRBuilderBase &Builder;
6657   const unsigned VF = 0;
6658   bool IsFinalized = false;
6659   SmallVector<int, 4> Mask;
6660   /// Holds all of the instructions that we gathered.
6661   SetVector<Instruction *> &GatherShuffleSeq;
6662   /// A list of blocks that we are going to CSE.
6663   SetVector<BasicBlock *> &CSEBlocks;
6664 
6665 public:
6666   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6667                             SetVector<Instruction *> &GatherShuffleSeq,
6668                             SetVector<BasicBlock *> &CSEBlocks)
6669       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6670         CSEBlocks(CSEBlocks) {}
6671 
6672   /// Adds a mask, inverting it before applying.
6673   void addInversedMask(ArrayRef<unsigned> SubMask) {
6674     if (SubMask.empty())
6675       return;
6676     SmallVector<int, 4> NewMask;
6677     inversePermutation(SubMask, NewMask);
6678     addMask(NewMask);
6679   }
6680 
6681   /// Functions adds masks, merging them into  single one.
6682   void addMask(ArrayRef<unsigned> SubMask) {
6683     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6684     addMask(NewMask);
6685   }
6686 
6687   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6688 
6689   Value *finalize(Value *V) {
6690     IsFinalized = true;
6691     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6692     if (VF == ValueVF && Mask.empty())
6693       return V;
6694     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6695     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6696     addMask(NormalizedMask);
6697 
6698     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6699       return V;
6700     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6701     if (auto *I = dyn_cast<Instruction>(Vec)) {
6702       GatherShuffleSeq.insert(I);
6703       CSEBlocks.insert(I->getParent());
6704     }
6705     return Vec;
6706   }
6707 
6708   ~ShuffleInstructionBuilder() {
6709     assert((IsFinalized || Mask.empty()) &&
6710            "Shuffle construction must be finalized.");
6711   }
6712 };
6713 } // namespace
6714 
6715 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6716   const unsigned VF = VL.size();
6717   InstructionsState S = getSameOpcode(VL);
6718   if (S.getOpcode()) {
6719     if (TreeEntry *E = getTreeEntry(S.OpValue))
6720       if (E->isSame(VL)) {
6721         Value *V = vectorizeTree(E);
6722         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6723           if (!E->ReuseShuffleIndices.empty()) {
6724             // Reshuffle to get only unique values.
6725             // If some of the scalars are duplicated in the vectorization tree
6726             // entry, we do not vectorize them but instead generate a mask for
6727             // the reuses. But if there are several users of the same entry,
6728             // they may have different vectorization factors. This is especially
6729             // important for PHI nodes. In this case, we need to adapt the
6730             // resulting instruction for the user vectorization factor and have
6731             // to reshuffle it again to take only unique elements of the vector.
6732             // Without this code the function incorrectly returns reduced vector
6733             // instruction with the same elements, not with the unique ones.
6734 
6735             // block:
6736             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6737             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6738             // ... (use %2)
6739             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6740             // br %block
6741             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6742             SmallSet<int, 4> UsedIdxs;
6743             int Pos = 0;
6744             int Sz = VL.size();
6745             for (int Idx : E->ReuseShuffleIndices) {
6746               if (Idx != Sz && Idx != UndefMaskElem &&
6747                   UsedIdxs.insert(Idx).second)
6748                 UniqueIdxs[Idx] = Pos;
6749               ++Pos;
6750             }
6751             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6752                                             "less than original vector size.");
6753             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6754             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6755           } else {
6756             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6757                    "Expected vectorization factor less "
6758                    "than original vector size.");
6759             SmallVector<int> UniformMask(VF, 0);
6760             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6761             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6762           }
6763           if (auto *I = dyn_cast<Instruction>(V)) {
6764             GatherShuffleSeq.insert(I);
6765             CSEBlocks.insert(I->getParent());
6766           }
6767         }
6768         return V;
6769       }
6770   }
6771 
6772   // Can't vectorize this, so simply build a new vector with each lane
6773   // corresponding to the requested value.
6774   return createBuildVector(VL);
6775 }
6776 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6777   unsigned VF = VL.size();
6778   // Exploit possible reuse of values across lanes.
6779   SmallVector<int> ReuseShuffleIndicies;
6780   SmallVector<Value *> UniqueValues;
6781   if (VL.size() > 2) {
6782     DenseMap<Value *, unsigned> UniquePositions;
6783     unsigned NumValues =
6784         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6785                                     return !isa<UndefValue>(V);
6786                                   }).base());
6787     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6788     int UniqueVals = 0;
6789     for (Value *V : VL.drop_back(VL.size() - VF)) {
6790       if (isa<UndefValue>(V)) {
6791         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6792         continue;
6793       }
6794       if (isConstant(V)) {
6795         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6796         UniqueValues.emplace_back(V);
6797         continue;
6798       }
6799       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6800       ReuseShuffleIndicies.emplace_back(Res.first->second);
6801       if (Res.second) {
6802         UniqueValues.emplace_back(V);
6803         ++UniqueVals;
6804       }
6805     }
6806     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6807       // Emit pure splat vector.
6808       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6809                                   UndefMaskElem);
6810     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6811       ReuseShuffleIndicies.clear();
6812       UniqueValues.clear();
6813       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6814     }
6815     UniqueValues.append(VF - UniqueValues.size(),
6816                         PoisonValue::get(VL[0]->getType()));
6817     VL = UniqueValues;
6818   }
6819 
6820   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6821                                            CSEBlocks);
6822   Value *Vec = gather(VL);
6823   if (!ReuseShuffleIndicies.empty()) {
6824     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6825     Vec = ShuffleBuilder.finalize(Vec);
6826   }
6827   return Vec;
6828 }
6829 
6830 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6831   IRBuilder<>::InsertPointGuard Guard(Builder);
6832 
6833   if (E->VectorizedValue) {
6834     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6835     return E->VectorizedValue;
6836   }
6837 
6838   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6839   unsigned VF = E->getVectorFactor();
6840   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6841                                            CSEBlocks);
6842   if (E->State == TreeEntry::NeedToGather) {
6843     if (E->getMainOp())
6844       setInsertPointAfterBundle(E);
6845     Value *Vec;
6846     SmallVector<int> Mask;
6847     SmallVector<const TreeEntry *> Entries;
6848     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6849         isGatherShuffledEntry(E, Mask, Entries);
6850     if (Shuffle.hasValue()) {
6851       assert((Entries.size() == 1 || Entries.size() == 2) &&
6852              "Expected shuffle of 1 or 2 entries.");
6853       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6854                                         Entries.back()->VectorizedValue, Mask);
6855       if (auto *I = dyn_cast<Instruction>(Vec)) {
6856         GatherShuffleSeq.insert(I);
6857         CSEBlocks.insert(I->getParent());
6858       }
6859     } else {
6860       Vec = gather(E->Scalars);
6861     }
6862     if (NeedToShuffleReuses) {
6863       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6864       Vec = ShuffleBuilder.finalize(Vec);
6865     }
6866     E->VectorizedValue = Vec;
6867     return Vec;
6868   }
6869 
6870   assert((E->State == TreeEntry::Vectorize ||
6871           E->State == TreeEntry::ScatterVectorize) &&
6872          "Unhandled state");
6873   unsigned ShuffleOrOp =
6874       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6875   Instruction *VL0 = E->getMainOp();
6876   Type *ScalarTy = VL0->getType();
6877   if (auto *Store = dyn_cast<StoreInst>(VL0))
6878     ScalarTy = Store->getValueOperand()->getType();
6879   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6880     ScalarTy = IE->getOperand(1)->getType();
6881   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6882   switch (ShuffleOrOp) {
6883     case Instruction::PHI: {
6884       assert(
6885           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6886           "PHI reordering is free.");
6887       auto *PH = cast<PHINode>(VL0);
6888       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6889       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6890       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6891       Value *V = NewPhi;
6892 
6893       // Adjust insertion point once all PHI's have been generated.
6894       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6895       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6896 
6897       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6898       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6899       V = ShuffleBuilder.finalize(V);
6900 
6901       E->VectorizedValue = V;
6902 
6903       // PHINodes may have multiple entries from the same block. We want to
6904       // visit every block once.
6905       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6906 
6907       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6908         ValueList Operands;
6909         BasicBlock *IBB = PH->getIncomingBlock(i);
6910 
6911         if (!VisitedBBs.insert(IBB).second) {
6912           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6913           continue;
6914         }
6915 
6916         Builder.SetInsertPoint(IBB->getTerminator());
6917         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6918         Value *Vec = vectorizeTree(E->getOperand(i));
6919         NewPhi->addIncoming(Vec, IBB);
6920       }
6921 
6922       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6923              "Invalid number of incoming values");
6924       return V;
6925     }
6926 
6927     case Instruction::ExtractElement: {
6928       Value *V = E->getSingleOperand(0);
6929       Builder.SetInsertPoint(VL0);
6930       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6931       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6932       V = ShuffleBuilder.finalize(V);
6933       E->VectorizedValue = V;
6934       return V;
6935     }
6936     case Instruction::ExtractValue: {
6937       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6938       Builder.SetInsertPoint(LI);
6939       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6940       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6941       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6942       Value *NewV = propagateMetadata(V, E->Scalars);
6943       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6944       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6945       NewV = ShuffleBuilder.finalize(NewV);
6946       E->VectorizedValue = NewV;
6947       return NewV;
6948     }
6949     case Instruction::InsertElement: {
6950       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6951       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6952       Value *V = vectorizeTree(E->getOperand(1));
6953 
6954       // Create InsertVector shuffle if necessary
6955       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6956         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6957       }));
6958       const unsigned NumElts =
6959           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6960       const unsigned NumScalars = E->Scalars.size();
6961 
6962       unsigned Offset = *getInsertIndex(VL0);
6963       assert(Offset < NumElts && "Failed to find vector index offset");
6964 
6965       // Create shuffle to resize vector
6966       SmallVector<int> Mask;
6967       if (!E->ReorderIndices.empty()) {
6968         inversePermutation(E->ReorderIndices, Mask);
6969         Mask.append(NumElts - NumScalars, UndefMaskElem);
6970       } else {
6971         Mask.assign(NumElts, UndefMaskElem);
6972         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6973       }
6974       // Create InsertVector shuffle if necessary
6975       bool IsIdentity = true;
6976       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6977       Mask.swap(PrevMask);
6978       for (unsigned I = 0; I < NumScalars; ++I) {
6979         Value *Scalar = E->Scalars[PrevMask[I]];
6980         unsigned InsertIdx = *getInsertIndex(Scalar);
6981         IsIdentity &= InsertIdx - Offset == I;
6982         Mask[InsertIdx - Offset] = I;
6983       }
6984       if (!IsIdentity || NumElts != NumScalars) {
6985         V = Builder.CreateShuffleVector(V, Mask);
6986         if (auto *I = dyn_cast<Instruction>(V)) {
6987           GatherShuffleSeq.insert(I);
6988           CSEBlocks.insert(I->getParent());
6989         }
6990       }
6991 
6992       if ((!IsIdentity || Offset != 0 ||
6993            !isUndefVector(FirstInsert->getOperand(0))) &&
6994           NumElts != NumScalars) {
6995         SmallVector<int> InsertMask(NumElts);
6996         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6997         for (unsigned I = 0; I < NumElts; I++) {
6998           if (Mask[I] != UndefMaskElem)
6999             InsertMask[Offset + I] = NumElts + I;
7000         }
7001 
7002         V = Builder.CreateShuffleVector(
7003             FirstInsert->getOperand(0), V, InsertMask,
7004             cast<Instruction>(E->Scalars.back())->getName());
7005         if (auto *I = dyn_cast<Instruction>(V)) {
7006           GatherShuffleSeq.insert(I);
7007           CSEBlocks.insert(I->getParent());
7008         }
7009       }
7010 
7011       ++NumVectorInstructions;
7012       E->VectorizedValue = V;
7013       return V;
7014     }
7015     case Instruction::ZExt:
7016     case Instruction::SExt:
7017     case Instruction::FPToUI:
7018     case Instruction::FPToSI:
7019     case Instruction::FPExt:
7020     case Instruction::PtrToInt:
7021     case Instruction::IntToPtr:
7022     case Instruction::SIToFP:
7023     case Instruction::UIToFP:
7024     case Instruction::Trunc:
7025     case Instruction::FPTrunc:
7026     case Instruction::BitCast: {
7027       setInsertPointAfterBundle(E);
7028 
7029       Value *InVec = vectorizeTree(E->getOperand(0));
7030 
7031       if (E->VectorizedValue) {
7032         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7033         return E->VectorizedValue;
7034       }
7035 
7036       auto *CI = cast<CastInst>(VL0);
7037       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7038       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7039       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7040       V = ShuffleBuilder.finalize(V);
7041 
7042       E->VectorizedValue = V;
7043       ++NumVectorInstructions;
7044       return V;
7045     }
7046     case Instruction::FCmp:
7047     case Instruction::ICmp: {
7048       setInsertPointAfterBundle(E);
7049 
7050       Value *L = vectorizeTree(E->getOperand(0));
7051       Value *R = vectorizeTree(E->getOperand(1));
7052 
7053       if (E->VectorizedValue) {
7054         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7055         return E->VectorizedValue;
7056       }
7057 
7058       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7059       Value *V = Builder.CreateCmp(P0, L, R);
7060       propagateIRFlags(V, E->Scalars, VL0);
7061       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7062       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7063       V = ShuffleBuilder.finalize(V);
7064 
7065       E->VectorizedValue = V;
7066       ++NumVectorInstructions;
7067       return V;
7068     }
7069     case Instruction::Select: {
7070       setInsertPointAfterBundle(E);
7071 
7072       Value *Cond = vectorizeTree(E->getOperand(0));
7073       Value *True = vectorizeTree(E->getOperand(1));
7074       Value *False = vectorizeTree(E->getOperand(2));
7075 
7076       if (E->VectorizedValue) {
7077         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7078         return E->VectorizedValue;
7079       }
7080 
7081       Value *V = Builder.CreateSelect(Cond, True, False);
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::FNeg: {
7091       setInsertPointAfterBundle(E);
7092 
7093       Value *Op = vectorizeTree(E->getOperand(0));
7094 
7095       if (E->VectorizedValue) {
7096         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7097         return E->VectorizedValue;
7098       }
7099 
7100       Value *V = Builder.CreateUnOp(
7101           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7102       propagateIRFlags(V, E->Scalars, VL0);
7103       if (auto *I = dyn_cast<Instruction>(V))
7104         V = propagateMetadata(I, E->Scalars);
7105 
7106       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7107       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7108       V = ShuffleBuilder.finalize(V);
7109 
7110       E->VectorizedValue = V;
7111       ++NumVectorInstructions;
7112 
7113       return V;
7114     }
7115     case Instruction::Add:
7116     case Instruction::FAdd:
7117     case Instruction::Sub:
7118     case Instruction::FSub:
7119     case Instruction::Mul:
7120     case Instruction::FMul:
7121     case Instruction::UDiv:
7122     case Instruction::SDiv:
7123     case Instruction::FDiv:
7124     case Instruction::URem:
7125     case Instruction::SRem:
7126     case Instruction::FRem:
7127     case Instruction::Shl:
7128     case Instruction::LShr:
7129     case Instruction::AShr:
7130     case Instruction::And:
7131     case Instruction::Or:
7132     case Instruction::Xor: {
7133       setInsertPointAfterBundle(E);
7134 
7135       Value *LHS = vectorizeTree(E->getOperand(0));
7136       Value *RHS = vectorizeTree(E->getOperand(1));
7137 
7138       if (E->VectorizedValue) {
7139         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7140         return E->VectorizedValue;
7141       }
7142 
7143       Value *V = Builder.CreateBinOp(
7144           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7145           RHS);
7146       propagateIRFlags(V, E->Scalars, VL0);
7147       if (auto *I = dyn_cast<Instruction>(V))
7148         V = propagateMetadata(I, E->Scalars);
7149 
7150       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7151       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7152       V = ShuffleBuilder.finalize(V);
7153 
7154       E->VectorizedValue = V;
7155       ++NumVectorInstructions;
7156 
7157       return V;
7158     }
7159     case Instruction::Load: {
7160       // Loads are inserted at the head of the tree because we don't want to
7161       // sink them all the way down past store instructions.
7162       setInsertPointAfterBundle(E);
7163 
7164       LoadInst *LI = cast<LoadInst>(VL0);
7165       Instruction *NewLI;
7166       unsigned AS = LI->getPointerAddressSpace();
7167       Value *PO = LI->getPointerOperand();
7168       if (E->State == TreeEntry::Vectorize) {
7169         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7170         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7171 
7172         // The pointer operand uses an in-tree scalar so we add the new BitCast
7173         // or LoadInst to ExternalUses list to make sure that an extract will
7174         // be generated in the future.
7175         if (TreeEntry *Entry = getTreeEntry(PO)) {
7176           // Find which lane we need to extract.
7177           unsigned FoundLane = Entry->findLaneForValue(PO);
7178           ExternalUses.emplace_back(
7179               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7180         }
7181       } else {
7182         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7183         Value *VecPtr = vectorizeTree(E->getOperand(0));
7184         // Use the minimum alignment of the gathered loads.
7185         Align CommonAlignment = LI->getAlign();
7186         for (Value *V : E->Scalars)
7187           CommonAlignment =
7188               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7189         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7190       }
7191       Value *V = propagateMetadata(NewLI, E->Scalars);
7192 
7193       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7194       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7195       V = ShuffleBuilder.finalize(V);
7196       E->VectorizedValue = V;
7197       ++NumVectorInstructions;
7198       return V;
7199     }
7200     case Instruction::Store: {
7201       auto *SI = cast<StoreInst>(VL0);
7202       unsigned AS = SI->getPointerAddressSpace();
7203 
7204       setInsertPointAfterBundle(E);
7205 
7206       Value *VecValue = vectorizeTree(E->getOperand(0));
7207       ShuffleBuilder.addMask(E->ReorderIndices);
7208       VecValue = ShuffleBuilder.finalize(VecValue);
7209 
7210       Value *ScalarPtr = SI->getPointerOperand();
7211       Value *VecPtr = Builder.CreateBitCast(
7212           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7213       StoreInst *ST =
7214           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7215 
7216       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7217       // StoreInst to ExternalUses to make sure that an extract will be
7218       // generated in the future.
7219       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7220         // Find which lane we need to extract.
7221         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7222         ExternalUses.push_back(ExternalUser(
7223             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7224             FoundLane));
7225       }
7226 
7227       Value *V = propagateMetadata(ST, E->Scalars);
7228 
7229       E->VectorizedValue = V;
7230       ++NumVectorInstructions;
7231       return V;
7232     }
7233     case Instruction::GetElementPtr: {
7234       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7235       setInsertPointAfterBundle(E);
7236 
7237       Value *Op0 = vectorizeTree(E->getOperand(0));
7238 
7239       SmallVector<Value *> OpVecs;
7240       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7241         Value *OpVec = vectorizeTree(E->getOperand(J));
7242         OpVecs.push_back(OpVec);
7243       }
7244 
7245       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7246       if (Instruction *I = dyn_cast<Instruction>(V))
7247         V = propagateMetadata(I, E->Scalars);
7248 
7249       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7250       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7251       V = ShuffleBuilder.finalize(V);
7252 
7253       E->VectorizedValue = V;
7254       ++NumVectorInstructions;
7255 
7256       return V;
7257     }
7258     case Instruction::Call: {
7259       CallInst *CI = cast<CallInst>(VL0);
7260       setInsertPointAfterBundle(E);
7261 
7262       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7263       if (Function *FI = CI->getCalledFunction())
7264         IID = FI->getIntrinsicID();
7265 
7266       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7267 
7268       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7269       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7270                           VecCallCosts.first <= VecCallCosts.second;
7271 
7272       Value *ScalarArg = nullptr;
7273       std::vector<Value *> OpVecs;
7274       SmallVector<Type *, 2> TysForDecl =
7275           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7276       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7277         ValueList OpVL;
7278         // Some intrinsics have scalar arguments. This argument should not be
7279         // vectorized.
7280         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7281           CallInst *CEI = cast<CallInst>(VL0);
7282           ScalarArg = CEI->getArgOperand(j);
7283           OpVecs.push_back(CEI->getArgOperand(j));
7284           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7285             TysForDecl.push_back(ScalarArg->getType());
7286           continue;
7287         }
7288 
7289         Value *OpVec = vectorizeTree(E->getOperand(j));
7290         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7291         OpVecs.push_back(OpVec);
7292       }
7293 
7294       Function *CF;
7295       if (!UseIntrinsic) {
7296         VFShape Shape =
7297             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7298                                   VecTy->getNumElements())),
7299                          false /*HasGlobalPred*/);
7300         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7301       } else {
7302         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7303       }
7304 
7305       SmallVector<OperandBundleDef, 1> OpBundles;
7306       CI->getOperandBundlesAsDefs(OpBundles);
7307       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7308 
7309       // The scalar argument uses an in-tree scalar so we add the new vectorized
7310       // call to ExternalUses list to make sure that an extract will be
7311       // generated in the future.
7312       if (ScalarArg) {
7313         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7314           // Find which lane we need to extract.
7315           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7316           ExternalUses.push_back(
7317               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7318         }
7319       }
7320 
7321       propagateIRFlags(V, E->Scalars, VL0);
7322       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7323       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7324       V = ShuffleBuilder.finalize(V);
7325 
7326       E->VectorizedValue = V;
7327       ++NumVectorInstructions;
7328       return V;
7329     }
7330     case Instruction::ShuffleVector: {
7331       assert(E->isAltShuffle() &&
7332              ((Instruction::isBinaryOp(E->getOpcode()) &&
7333                Instruction::isBinaryOp(E->getAltOpcode())) ||
7334               (Instruction::isCast(E->getOpcode()) &&
7335                Instruction::isCast(E->getAltOpcode())) ||
7336               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7337              "Invalid Shuffle Vector Operand");
7338 
7339       Value *LHS = nullptr, *RHS = nullptr;
7340       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7341         setInsertPointAfterBundle(E);
7342         LHS = vectorizeTree(E->getOperand(0));
7343         RHS = vectorizeTree(E->getOperand(1));
7344       } else {
7345         setInsertPointAfterBundle(E);
7346         LHS = vectorizeTree(E->getOperand(0));
7347       }
7348 
7349       if (E->VectorizedValue) {
7350         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7351         return E->VectorizedValue;
7352       }
7353 
7354       Value *V0, *V1;
7355       if (Instruction::isBinaryOp(E->getOpcode())) {
7356         V0 = Builder.CreateBinOp(
7357             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7358         V1 = Builder.CreateBinOp(
7359             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7360       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7361         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7362         auto *AltCI = cast<CmpInst>(E->getAltOp());
7363         CmpInst::Predicate AltPred = AltCI->getPredicate();
7364         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7365       } else {
7366         V0 = Builder.CreateCast(
7367             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7368         V1 = Builder.CreateCast(
7369             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7370       }
7371       // Add V0 and V1 to later analysis to try to find and remove matching
7372       // instruction, if any.
7373       for (Value *V : {V0, V1}) {
7374         if (auto *I = dyn_cast<Instruction>(V)) {
7375           GatherShuffleSeq.insert(I);
7376           CSEBlocks.insert(I->getParent());
7377         }
7378       }
7379 
7380       // Create shuffle to take alternate operations from the vector.
7381       // Also, gather up main and alt scalar ops to propagate IR flags to
7382       // each vector operation.
7383       ValueList OpScalars, AltScalars;
7384       SmallVector<int> Mask;
7385       buildShuffleEntryMask(
7386           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7387           [E](Instruction *I) {
7388             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7389             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7390           },
7391           Mask, &OpScalars, &AltScalars);
7392 
7393       propagateIRFlags(V0, OpScalars);
7394       propagateIRFlags(V1, AltScalars);
7395 
7396       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7397       if (auto *I = dyn_cast<Instruction>(V)) {
7398         V = propagateMetadata(I, E->Scalars);
7399         GatherShuffleSeq.insert(I);
7400         CSEBlocks.insert(I->getParent());
7401       }
7402       V = ShuffleBuilder.finalize(V);
7403 
7404       E->VectorizedValue = V;
7405       ++NumVectorInstructions;
7406 
7407       return V;
7408     }
7409     default:
7410     llvm_unreachable("unknown inst");
7411   }
7412   return nullptr;
7413 }
7414 
7415 Value *BoUpSLP::vectorizeTree() {
7416   ExtraValueToDebugLocsMap ExternallyUsedValues;
7417   return vectorizeTree(ExternallyUsedValues);
7418 }
7419 
7420 Value *
7421 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7422   // All blocks must be scheduled before any instructions are inserted.
7423   for (auto &BSIter : BlocksSchedules) {
7424     scheduleBlock(BSIter.second.get());
7425   }
7426 
7427   Builder.SetInsertPoint(&F->getEntryBlock().front());
7428   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7429 
7430   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7431   // vectorized root. InstCombine will then rewrite the entire expression. We
7432   // sign extend the extracted values below.
7433   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7434   if (MinBWs.count(ScalarRoot)) {
7435     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7436       // If current instr is a phi and not the last phi, insert it after the
7437       // last phi node.
7438       if (isa<PHINode>(I))
7439         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7440       else
7441         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7442     }
7443     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7444     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7445     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7446     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7447     VectorizableTree[0]->VectorizedValue = Trunc;
7448   }
7449 
7450   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7451                     << " values .\n");
7452 
7453   // Extract all of the elements with the external uses.
7454   for (const auto &ExternalUse : ExternalUses) {
7455     Value *Scalar = ExternalUse.Scalar;
7456     llvm::User *User = ExternalUse.User;
7457 
7458     // Skip users that we already RAUW. This happens when one instruction
7459     // has multiple uses of the same value.
7460     if (User && !is_contained(Scalar->users(), User))
7461       continue;
7462     TreeEntry *E = getTreeEntry(Scalar);
7463     assert(E && "Invalid scalar");
7464     assert(E->State != TreeEntry::NeedToGather &&
7465            "Extracting from a gather list");
7466 
7467     Value *Vec = E->VectorizedValue;
7468     assert(Vec && "Can't find vectorizable value");
7469 
7470     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7471     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7472       if (Scalar->getType() != Vec->getType()) {
7473         Value *Ex;
7474         // "Reuse" the existing extract to improve final codegen.
7475         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7476           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7477                                             ES->getOperand(1));
7478         } else {
7479           Ex = Builder.CreateExtractElement(Vec, Lane);
7480         }
7481         // If necessary, sign-extend or zero-extend ScalarRoot
7482         // to the larger type.
7483         if (!MinBWs.count(ScalarRoot))
7484           return Ex;
7485         if (MinBWs[ScalarRoot].second)
7486           return Builder.CreateSExt(Ex, Scalar->getType());
7487         return Builder.CreateZExt(Ex, Scalar->getType());
7488       }
7489       assert(isa<FixedVectorType>(Scalar->getType()) &&
7490              isa<InsertElementInst>(Scalar) &&
7491              "In-tree scalar of vector type is not insertelement?");
7492       return Vec;
7493     };
7494     // If User == nullptr, the Scalar is used as extra arg. Generate
7495     // ExtractElement instruction and update the record for this scalar in
7496     // ExternallyUsedValues.
7497     if (!User) {
7498       assert(ExternallyUsedValues.count(Scalar) &&
7499              "Scalar with nullptr as an external user must be registered in "
7500              "ExternallyUsedValues map");
7501       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7502         Builder.SetInsertPoint(VecI->getParent(),
7503                                std::next(VecI->getIterator()));
7504       } else {
7505         Builder.SetInsertPoint(&F->getEntryBlock().front());
7506       }
7507       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7508       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7509       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7510       auto It = ExternallyUsedValues.find(Scalar);
7511       assert(It != ExternallyUsedValues.end() &&
7512              "Externally used scalar is not found in ExternallyUsedValues");
7513       NewInstLocs.append(It->second);
7514       ExternallyUsedValues.erase(Scalar);
7515       // Required to update internally referenced instructions.
7516       Scalar->replaceAllUsesWith(NewInst);
7517       continue;
7518     }
7519 
7520     // Generate extracts for out-of-tree users.
7521     // Find the insertion point for the extractelement lane.
7522     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7523       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7524         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7525           if (PH->getIncomingValue(i) == Scalar) {
7526             Instruction *IncomingTerminator =
7527                 PH->getIncomingBlock(i)->getTerminator();
7528             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7529               Builder.SetInsertPoint(VecI->getParent(),
7530                                      std::next(VecI->getIterator()));
7531             } else {
7532               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7533             }
7534             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7535             CSEBlocks.insert(PH->getIncomingBlock(i));
7536             PH->setOperand(i, NewInst);
7537           }
7538         }
7539       } else {
7540         Builder.SetInsertPoint(cast<Instruction>(User));
7541         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7542         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7543         User->replaceUsesOfWith(Scalar, NewInst);
7544       }
7545     } else {
7546       Builder.SetInsertPoint(&F->getEntryBlock().front());
7547       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7548       CSEBlocks.insert(&F->getEntryBlock());
7549       User->replaceUsesOfWith(Scalar, NewInst);
7550     }
7551 
7552     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7553   }
7554 
7555   // For each vectorized value:
7556   for (auto &TEPtr : VectorizableTree) {
7557     TreeEntry *Entry = TEPtr.get();
7558 
7559     // No need to handle users of gathered values.
7560     if (Entry->State == TreeEntry::NeedToGather)
7561       continue;
7562 
7563     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7564 
7565     // For each lane:
7566     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7567       Value *Scalar = Entry->Scalars[Lane];
7568 
7569 #ifndef NDEBUG
7570       Type *Ty = Scalar->getType();
7571       if (!Ty->isVoidTy()) {
7572         for (User *U : Scalar->users()) {
7573           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7574 
7575           // It is legal to delete users in the ignorelist.
7576           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7577                   (isa_and_nonnull<Instruction>(U) &&
7578                    isDeleted(cast<Instruction>(U)))) &&
7579                  "Deleting out-of-tree value");
7580         }
7581       }
7582 #endif
7583       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7584       eraseInstruction(cast<Instruction>(Scalar));
7585     }
7586   }
7587 
7588   Builder.ClearInsertionPoint();
7589   InstrElementSize.clear();
7590 
7591   return VectorizableTree[0]->VectorizedValue;
7592 }
7593 
7594 void BoUpSLP::optimizeGatherSequence() {
7595   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7596                     << " gather sequences instructions.\n");
7597   // LICM InsertElementInst sequences.
7598   for (Instruction *I : GatherShuffleSeq) {
7599     if (isDeleted(I))
7600       continue;
7601 
7602     // Check if this block is inside a loop.
7603     Loop *L = LI->getLoopFor(I->getParent());
7604     if (!L)
7605       continue;
7606 
7607     // Check if it has a preheader.
7608     BasicBlock *PreHeader = L->getLoopPreheader();
7609     if (!PreHeader)
7610       continue;
7611 
7612     // If the vector or the element that we insert into it are
7613     // instructions that are defined in this basic block then we can't
7614     // hoist this instruction.
7615     if (any_of(I->operands(), [L](Value *V) {
7616           auto *OpI = dyn_cast<Instruction>(V);
7617           return OpI && L->contains(OpI);
7618         }))
7619       continue;
7620 
7621     // We can hoist this instruction. Move it to the pre-header.
7622     I->moveBefore(PreHeader->getTerminator());
7623   }
7624 
7625   // Make a list of all reachable blocks in our CSE queue.
7626   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7627   CSEWorkList.reserve(CSEBlocks.size());
7628   for (BasicBlock *BB : CSEBlocks)
7629     if (DomTreeNode *N = DT->getNode(BB)) {
7630       assert(DT->isReachableFromEntry(N));
7631       CSEWorkList.push_back(N);
7632     }
7633 
7634   // Sort blocks by domination. This ensures we visit a block after all blocks
7635   // dominating it are visited.
7636   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7637     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7638            "Different nodes should have different DFS numbers");
7639     return A->getDFSNumIn() < B->getDFSNumIn();
7640   });
7641 
7642   // Less defined shuffles can be replaced by the more defined copies.
7643   // Between two shuffles one is less defined if it has the same vector operands
7644   // and its mask indeces are the same as in the first one or undefs. E.g.
7645   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7646   // poison, <0, 0, 0, 0>.
7647   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7648                                            SmallVectorImpl<int> &NewMask) {
7649     if (I1->getType() != I2->getType())
7650       return false;
7651     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7652     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7653     if (!SI1 || !SI2)
7654       return I1->isIdenticalTo(I2);
7655     if (SI1->isIdenticalTo(SI2))
7656       return true;
7657     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7658       if (SI1->getOperand(I) != SI2->getOperand(I))
7659         return false;
7660     // Check if the second instruction is more defined than the first one.
7661     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7662     ArrayRef<int> SM1 = SI1->getShuffleMask();
7663     // Count trailing undefs in the mask to check the final number of used
7664     // registers.
7665     unsigned LastUndefsCnt = 0;
7666     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7667       if (SM1[I] == UndefMaskElem)
7668         ++LastUndefsCnt;
7669       else
7670         LastUndefsCnt = 0;
7671       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7672           NewMask[I] != SM1[I])
7673         return false;
7674       if (NewMask[I] == UndefMaskElem)
7675         NewMask[I] = SM1[I];
7676     }
7677     // Check if the last undefs actually change the final number of used vector
7678     // registers.
7679     return SM1.size() - LastUndefsCnt > 1 &&
7680            TTI->getNumberOfParts(SI1->getType()) ==
7681                TTI->getNumberOfParts(
7682                    FixedVectorType::get(SI1->getType()->getElementType(),
7683                                         SM1.size() - LastUndefsCnt));
7684   };
7685   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7686   // instructions. TODO: We can further optimize this scan if we split the
7687   // instructions into different buckets based on the insert lane.
7688   SmallVector<Instruction *, 16> Visited;
7689   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7690     assert(*I &&
7691            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7692            "Worklist not sorted properly!");
7693     BasicBlock *BB = (*I)->getBlock();
7694     // For all instructions in blocks containing gather sequences:
7695     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7696       if (isDeleted(&In))
7697         continue;
7698       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7699           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7700         continue;
7701 
7702       // Check if we can replace this instruction with any of the
7703       // visited instructions.
7704       bool Replaced = false;
7705       for (Instruction *&V : Visited) {
7706         SmallVector<int> NewMask;
7707         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7708             DT->dominates(V->getParent(), In.getParent())) {
7709           In.replaceAllUsesWith(V);
7710           eraseInstruction(&In);
7711           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7712             if (!NewMask.empty())
7713               SI->setShuffleMask(NewMask);
7714           Replaced = true;
7715           break;
7716         }
7717         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7718             GatherShuffleSeq.contains(V) &&
7719             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7720             DT->dominates(In.getParent(), V->getParent())) {
7721           In.moveAfter(V);
7722           V->replaceAllUsesWith(&In);
7723           eraseInstruction(V);
7724           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7725             if (!NewMask.empty())
7726               SI->setShuffleMask(NewMask);
7727           V = &In;
7728           Replaced = true;
7729           break;
7730         }
7731       }
7732       if (!Replaced) {
7733         assert(!is_contained(Visited, &In));
7734         Visited.push_back(&In);
7735       }
7736     }
7737   }
7738   CSEBlocks.clear();
7739   GatherShuffleSeq.clear();
7740 }
7741 
7742 BoUpSLP::ScheduleData *
7743 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7744   ScheduleData *Bundle = nullptr;
7745   ScheduleData *PrevInBundle = nullptr;
7746   for (Value *V : VL) {
7747     if (doesNotNeedToBeScheduled(V))
7748       continue;
7749     ScheduleData *BundleMember = getScheduleData(V);
7750     assert(BundleMember &&
7751            "no ScheduleData for bundle member "
7752            "(maybe not in same basic block)");
7753     assert(BundleMember->isSchedulingEntity() &&
7754            "bundle member already part of other bundle");
7755     if (PrevInBundle) {
7756       PrevInBundle->NextInBundle = BundleMember;
7757     } else {
7758       Bundle = BundleMember;
7759     }
7760 
7761     // Group the instructions to a bundle.
7762     BundleMember->FirstInBundle = Bundle;
7763     PrevInBundle = BundleMember;
7764   }
7765   assert(Bundle && "Failed to find schedule bundle");
7766   return Bundle;
7767 }
7768 
7769 // Groups the instructions to a bundle (which is then a single scheduling entity)
7770 // and schedules instructions until the bundle gets ready.
7771 Optional<BoUpSLP::ScheduleData *>
7772 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7773                                             const InstructionsState &S) {
7774   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7775   // instructions.
7776   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7777       doesNotNeedToSchedule(VL))
7778     return nullptr;
7779 
7780   // Initialize the instruction bundle.
7781   Instruction *OldScheduleEnd = ScheduleEnd;
7782   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7783 
7784   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7785                                                          ScheduleData *Bundle) {
7786     // The scheduling region got new instructions at the lower end (or it is a
7787     // new region for the first bundle). This makes it necessary to
7788     // recalculate all dependencies.
7789     // It is seldom that this needs to be done a second time after adding the
7790     // initial bundle to the region.
7791     if (ScheduleEnd != OldScheduleEnd) {
7792       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7793         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7794       ReSchedule = true;
7795     }
7796     if (Bundle) {
7797       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7798                         << " in block " << BB->getName() << "\n");
7799       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7800     }
7801 
7802     if (ReSchedule) {
7803       resetSchedule();
7804       initialFillReadyList(ReadyInsts);
7805     }
7806 
7807     // Now try to schedule the new bundle or (if no bundle) just calculate
7808     // dependencies. As soon as the bundle is "ready" it means that there are no
7809     // cyclic dependencies and we can schedule it. Note that's important that we
7810     // don't "schedule" the bundle yet (see cancelScheduling).
7811     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7812            !ReadyInsts.empty()) {
7813       ScheduleData *Picked = ReadyInsts.pop_back_val();
7814       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7815              "must be ready to schedule");
7816       schedule(Picked, ReadyInsts);
7817     }
7818   };
7819 
7820   // Make sure that the scheduling region contains all
7821   // instructions of the bundle.
7822   for (Value *V : VL) {
7823     if (doesNotNeedToBeScheduled(V))
7824       continue;
7825     if (!extendSchedulingRegion(V, S)) {
7826       // If the scheduling region got new instructions at the lower end (or it
7827       // is a new region for the first bundle). This makes it necessary to
7828       // recalculate all dependencies.
7829       // Otherwise the compiler may crash trying to incorrectly calculate
7830       // dependencies and emit instruction in the wrong order at the actual
7831       // scheduling.
7832       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7833       return None;
7834     }
7835   }
7836 
7837   bool ReSchedule = false;
7838   for (Value *V : VL) {
7839     if (doesNotNeedToBeScheduled(V))
7840       continue;
7841     ScheduleData *BundleMember = getScheduleData(V);
7842     assert(BundleMember &&
7843            "no ScheduleData for bundle member (maybe not in same basic block)");
7844 
7845     // Make sure we don't leave the pieces of the bundle in the ready list when
7846     // whole bundle might not be ready.
7847     ReadyInsts.remove(BundleMember);
7848 
7849     if (!BundleMember->IsScheduled)
7850       continue;
7851     // A bundle member was scheduled as single instruction before and now
7852     // needs to be scheduled as part of the bundle. We just get rid of the
7853     // existing schedule.
7854     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7855                       << " was already scheduled\n");
7856     ReSchedule = true;
7857   }
7858 
7859   auto *Bundle = buildBundle(VL);
7860   TryScheduleBundleImpl(ReSchedule, Bundle);
7861   if (!Bundle->isReady()) {
7862     cancelScheduling(VL, S.OpValue);
7863     return None;
7864   }
7865   return Bundle;
7866 }
7867 
7868 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7869                                                 Value *OpValue) {
7870   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7871       doesNotNeedToSchedule(VL))
7872     return;
7873 
7874   if (doesNotNeedToBeScheduled(OpValue))
7875     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7876   ScheduleData *Bundle = getScheduleData(OpValue);
7877   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7878   assert(!Bundle->IsScheduled &&
7879          "Can't cancel bundle which is already scheduled");
7880   assert(Bundle->isSchedulingEntity() &&
7881          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7882          "tried to unbundle something which is not a bundle");
7883 
7884   // Remove the bundle from the ready list.
7885   if (Bundle->isReady())
7886     ReadyInsts.remove(Bundle);
7887 
7888   // Un-bundle: make single instructions out of the bundle.
7889   ScheduleData *BundleMember = Bundle;
7890   while (BundleMember) {
7891     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7892     BundleMember->FirstInBundle = BundleMember;
7893     ScheduleData *Next = BundleMember->NextInBundle;
7894     BundleMember->NextInBundle = nullptr;
7895     BundleMember->TE = nullptr;
7896     if (BundleMember->unscheduledDepsInBundle() == 0) {
7897       ReadyInsts.insert(BundleMember);
7898     }
7899     BundleMember = Next;
7900   }
7901 }
7902 
7903 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7904   // Allocate a new ScheduleData for the instruction.
7905   if (ChunkPos >= ChunkSize) {
7906     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7907     ChunkPos = 0;
7908   }
7909   return &(ScheduleDataChunks.back()[ChunkPos++]);
7910 }
7911 
7912 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7913                                                       const InstructionsState &S) {
7914   if (getScheduleData(V, isOneOf(S, V)))
7915     return true;
7916   Instruction *I = dyn_cast<Instruction>(V);
7917   assert(I && "bundle member must be an instruction");
7918   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7919          !doesNotNeedToBeScheduled(I) &&
7920          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7921          "be scheduled");
7922   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7923     ScheduleData *ISD = getScheduleData(I);
7924     if (!ISD)
7925       return false;
7926     assert(isInSchedulingRegion(ISD) &&
7927            "ScheduleData not in scheduling region");
7928     ScheduleData *SD = allocateScheduleDataChunks();
7929     SD->Inst = I;
7930     SD->init(SchedulingRegionID, S.OpValue);
7931     ExtraScheduleDataMap[I][S.OpValue] = SD;
7932     return true;
7933   };
7934   if (CheckScheduleForI(I))
7935     return true;
7936   if (!ScheduleStart) {
7937     // It's the first instruction in the new region.
7938     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7939     ScheduleStart = I;
7940     ScheduleEnd = I->getNextNode();
7941     if (isOneOf(S, I) != I)
7942       CheckScheduleForI(I);
7943     assert(ScheduleEnd && "tried to vectorize a terminator?");
7944     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7945     return true;
7946   }
7947   // Search up and down at the same time, because we don't know if the new
7948   // instruction is above or below the existing scheduling region.
7949   BasicBlock::reverse_iterator UpIter =
7950       ++ScheduleStart->getIterator().getReverse();
7951   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7952   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7953   BasicBlock::iterator LowerEnd = BB->end();
7954   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7955          &*DownIter != I) {
7956     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7957       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7958       return false;
7959     }
7960 
7961     ++UpIter;
7962     ++DownIter;
7963   }
7964   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7965     assert(I->getParent() == ScheduleStart->getParent() &&
7966            "Instruction is in wrong basic block.");
7967     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7968     ScheduleStart = I;
7969     if (isOneOf(S, I) != I)
7970       CheckScheduleForI(I);
7971     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7972                       << "\n");
7973     return true;
7974   }
7975   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7976          "Expected to reach top of the basic block or instruction down the "
7977          "lower end.");
7978   assert(I->getParent() == ScheduleEnd->getParent() &&
7979          "Instruction is in wrong basic block.");
7980   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7981                    nullptr);
7982   ScheduleEnd = I->getNextNode();
7983   if (isOneOf(S, I) != I)
7984     CheckScheduleForI(I);
7985   assert(ScheduleEnd && "tried to vectorize a terminator?");
7986   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7987   return true;
7988 }
7989 
7990 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7991                                                 Instruction *ToI,
7992                                                 ScheduleData *PrevLoadStore,
7993                                                 ScheduleData *NextLoadStore) {
7994   ScheduleData *CurrentLoadStore = PrevLoadStore;
7995   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7996     // No need to allocate data for non-schedulable instructions.
7997     if (doesNotNeedToBeScheduled(I))
7998       continue;
7999     ScheduleData *SD = ScheduleDataMap.lookup(I);
8000     if (!SD) {
8001       SD = allocateScheduleDataChunks();
8002       ScheduleDataMap[I] = SD;
8003       SD->Inst = I;
8004     }
8005     assert(!isInSchedulingRegion(SD) &&
8006            "new ScheduleData already in scheduling region");
8007     SD->init(SchedulingRegionID, I);
8008 
8009     if (I->mayReadOrWriteMemory() &&
8010         (!isa<IntrinsicInst>(I) ||
8011          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8012           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8013               Intrinsic::pseudoprobe))) {
8014       // Update the linked list of memory accessing instructions.
8015       if (CurrentLoadStore) {
8016         CurrentLoadStore->NextLoadStore = SD;
8017       } else {
8018         FirstLoadStoreInRegion = SD;
8019       }
8020       CurrentLoadStore = SD;
8021     }
8022 
8023     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8024         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8025       RegionHasStackSave = true;
8026   }
8027   if (NextLoadStore) {
8028     if (CurrentLoadStore)
8029       CurrentLoadStore->NextLoadStore = NextLoadStore;
8030   } else {
8031     LastLoadStoreInRegion = CurrentLoadStore;
8032   }
8033 }
8034 
8035 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8036                                                      bool InsertInReadyList,
8037                                                      BoUpSLP *SLP) {
8038   assert(SD->isSchedulingEntity());
8039 
8040   SmallVector<ScheduleData *, 10> WorkList;
8041   WorkList.push_back(SD);
8042 
8043   while (!WorkList.empty()) {
8044     ScheduleData *SD = WorkList.pop_back_val();
8045     for (ScheduleData *BundleMember = SD; BundleMember;
8046          BundleMember = BundleMember->NextInBundle) {
8047       assert(isInSchedulingRegion(BundleMember));
8048       if (BundleMember->hasValidDependencies())
8049         continue;
8050 
8051       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8052                  << "\n");
8053       BundleMember->Dependencies = 0;
8054       BundleMember->resetUnscheduledDeps();
8055 
8056       // Handle def-use chain dependencies.
8057       if (BundleMember->OpValue != BundleMember->Inst) {
8058         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8059           BundleMember->Dependencies++;
8060           ScheduleData *DestBundle = UseSD->FirstInBundle;
8061           if (!DestBundle->IsScheduled)
8062             BundleMember->incrementUnscheduledDeps(1);
8063           if (!DestBundle->hasValidDependencies())
8064             WorkList.push_back(DestBundle);
8065         }
8066       } else {
8067         for (User *U : BundleMember->Inst->users()) {
8068           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8069             BundleMember->Dependencies++;
8070             ScheduleData *DestBundle = UseSD->FirstInBundle;
8071             if (!DestBundle->IsScheduled)
8072               BundleMember->incrementUnscheduledDeps(1);
8073             if (!DestBundle->hasValidDependencies())
8074               WorkList.push_back(DestBundle);
8075           }
8076         }
8077       }
8078 
8079       auto makeControlDependent = [&](Instruction *I) {
8080         auto *DepDest = getScheduleData(I);
8081         assert(DepDest && "must be in schedule window");
8082         DepDest->ControlDependencies.push_back(BundleMember);
8083         BundleMember->Dependencies++;
8084         ScheduleData *DestBundle = DepDest->FirstInBundle;
8085         if (!DestBundle->IsScheduled)
8086           BundleMember->incrementUnscheduledDeps(1);
8087         if (!DestBundle->hasValidDependencies())
8088           WorkList.push_back(DestBundle);
8089       };
8090 
8091       // Any instruction which isn't safe to speculate at the begining of the
8092       // block is control dependend on any early exit or non-willreturn call
8093       // which proceeds it.
8094       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8095         for (Instruction *I = BundleMember->Inst->getNextNode();
8096              I != ScheduleEnd; I = I->getNextNode()) {
8097           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8098             continue;
8099 
8100           // Add the dependency
8101           makeControlDependent(I);
8102 
8103           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8104             // Everything past here must be control dependent on I.
8105             break;
8106         }
8107       }
8108 
8109       if (RegionHasStackSave) {
8110         // If we have an inalloc alloca instruction, it needs to be scheduled
8111         // after any preceeding stacksave.  We also need to prevent any alloca
8112         // from reordering above a preceeding stackrestore.
8113         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8114             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8115           for (Instruction *I = BundleMember->Inst->getNextNode();
8116                I != ScheduleEnd; I = I->getNextNode()) {
8117             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8118                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8119               // Any allocas past here must be control dependent on I, and I
8120               // must be memory dependend on BundleMember->Inst.
8121               break;
8122 
8123             if (!isa<AllocaInst>(I))
8124               continue;
8125 
8126             // Add the dependency
8127             makeControlDependent(I);
8128           }
8129         }
8130 
8131         // In addition to the cases handle just above, we need to prevent
8132         // allocas from moving below a stacksave.  The stackrestore case
8133         // is currently thought to be conservatism.
8134         if (isa<AllocaInst>(BundleMember->Inst)) {
8135           for (Instruction *I = BundleMember->Inst->getNextNode();
8136                I != ScheduleEnd; I = I->getNextNode()) {
8137             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8138                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8139               continue;
8140 
8141             // Add the dependency
8142             makeControlDependent(I);
8143             break;
8144           }
8145         }
8146       }
8147 
8148       // Handle the memory dependencies (if any).
8149       ScheduleData *DepDest = BundleMember->NextLoadStore;
8150       if (!DepDest)
8151         continue;
8152       Instruction *SrcInst = BundleMember->Inst;
8153       assert(SrcInst->mayReadOrWriteMemory() &&
8154              "NextLoadStore list for non memory effecting bundle?");
8155       MemoryLocation SrcLoc = getLocation(SrcInst);
8156       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8157       unsigned numAliased = 0;
8158       unsigned DistToSrc = 1;
8159 
8160       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8161         assert(isInSchedulingRegion(DepDest));
8162 
8163         // We have two limits to reduce the complexity:
8164         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8165         //    SLP->isAliased (which is the expensive part in this loop).
8166         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8167         //    the whole loop (even if the loop is fast, it's quadratic).
8168         //    It's important for the loop break condition (see below) to
8169         //    check this limit even between two read-only instructions.
8170         if (DistToSrc >= MaxMemDepDistance ||
8171             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8172              (numAliased >= AliasedCheckLimit ||
8173               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8174 
8175           // We increment the counter only if the locations are aliased
8176           // (instead of counting all alias checks). This gives a better
8177           // balance between reduced runtime and accurate dependencies.
8178           numAliased++;
8179 
8180           DepDest->MemoryDependencies.push_back(BundleMember);
8181           BundleMember->Dependencies++;
8182           ScheduleData *DestBundle = DepDest->FirstInBundle;
8183           if (!DestBundle->IsScheduled) {
8184             BundleMember->incrementUnscheduledDeps(1);
8185           }
8186           if (!DestBundle->hasValidDependencies()) {
8187             WorkList.push_back(DestBundle);
8188           }
8189         }
8190 
8191         // Example, explaining the loop break condition: Let's assume our
8192         // starting instruction is i0 and MaxMemDepDistance = 3.
8193         //
8194         //                      +--------v--v--v
8195         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8196         //             +--------^--^--^
8197         //
8198         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8199         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8200         // Previously we already added dependencies from i3 to i6,i7,i8
8201         // (because of MaxMemDepDistance). As we added a dependency from
8202         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8203         // and we can abort this loop at i6.
8204         if (DistToSrc >= 2 * MaxMemDepDistance)
8205           break;
8206         DistToSrc++;
8207       }
8208     }
8209     if (InsertInReadyList && SD->isReady()) {
8210       ReadyInsts.insert(SD);
8211       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8212                         << "\n");
8213     }
8214   }
8215 }
8216 
8217 void BoUpSLP::BlockScheduling::resetSchedule() {
8218   assert(ScheduleStart &&
8219          "tried to reset schedule on block which has not been scheduled");
8220   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8221     doForAllOpcodes(I, [&](ScheduleData *SD) {
8222       assert(isInSchedulingRegion(SD) &&
8223              "ScheduleData not in scheduling region");
8224       SD->IsScheduled = false;
8225       SD->resetUnscheduledDeps();
8226     });
8227   }
8228   ReadyInsts.clear();
8229 }
8230 
8231 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8232   if (!BS->ScheduleStart)
8233     return;
8234 
8235   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8236 
8237   // A key point - if we got here, pre-scheduling was able to find a valid
8238   // scheduling of the sub-graph of the scheduling window which consists
8239   // of all vector bundles and their transitive users.  As such, we do not
8240   // need to reschedule anything *outside of* that subgraph.
8241 
8242   BS->resetSchedule();
8243 
8244   // For the real scheduling we use a more sophisticated ready-list: it is
8245   // sorted by the original instruction location. This lets the final schedule
8246   // be as  close as possible to the original instruction order.
8247   // WARNING: If changing this order causes a correctness issue, that means
8248   // there is some missing dependence edge in the schedule data graph.
8249   struct ScheduleDataCompare {
8250     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8251       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8252     }
8253   };
8254   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8255 
8256   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8257   // and fill the ready-list with initial instructions.
8258   int Idx = 0;
8259   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8260        I = I->getNextNode()) {
8261     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8262       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8263       (void)SDTE;
8264       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8265               SD->isPartOfBundle() ==
8266                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8267              "scheduler and vectorizer bundle mismatch");
8268       SD->FirstInBundle->SchedulingPriority = Idx++;
8269 
8270       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8271         BS->calculateDependencies(SD, false, this);
8272     });
8273   }
8274   BS->initialFillReadyList(ReadyInsts);
8275 
8276   Instruction *LastScheduledInst = BS->ScheduleEnd;
8277 
8278   // Do the "real" scheduling.
8279   while (!ReadyInsts.empty()) {
8280     ScheduleData *picked = *ReadyInsts.begin();
8281     ReadyInsts.erase(ReadyInsts.begin());
8282 
8283     // Move the scheduled instruction(s) to their dedicated places, if not
8284     // there yet.
8285     for (ScheduleData *BundleMember = picked; BundleMember;
8286          BundleMember = BundleMember->NextInBundle) {
8287       Instruction *pickedInst = BundleMember->Inst;
8288       if (pickedInst->getNextNode() != LastScheduledInst)
8289         pickedInst->moveBefore(LastScheduledInst);
8290       LastScheduledInst = pickedInst;
8291     }
8292 
8293     BS->schedule(picked, ReadyInsts);
8294   }
8295 
8296   // Check that we didn't break any of our invariants.
8297 #ifdef EXPENSIVE_CHECKS
8298   BS->verify();
8299 #endif
8300 
8301 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8302   // Check that all schedulable entities got scheduled
8303   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8304     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8305       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8306         assert(SD->IsScheduled && "must be scheduled at this point");
8307       }
8308     });
8309   }
8310 #endif
8311 
8312   // Avoid duplicate scheduling of the block.
8313   BS->ScheduleStart = nullptr;
8314 }
8315 
8316 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8317   // If V is a store, just return the width of the stored value (or value
8318   // truncated just before storing) without traversing the expression tree.
8319   // This is the common case.
8320   if (auto *Store = dyn_cast<StoreInst>(V)) {
8321     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8322       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8323     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8324   }
8325 
8326   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8327     return getVectorElementSize(IEI->getOperand(1));
8328 
8329   auto E = InstrElementSize.find(V);
8330   if (E != InstrElementSize.end())
8331     return E->second;
8332 
8333   // If V is not a store, we can traverse the expression tree to find loads
8334   // that feed it. The type of the loaded value may indicate a more suitable
8335   // width than V's type. We want to base the vector element size on the width
8336   // of memory operations where possible.
8337   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8338   SmallPtrSet<Instruction *, 16> Visited;
8339   if (auto *I = dyn_cast<Instruction>(V)) {
8340     Worklist.emplace_back(I, I->getParent());
8341     Visited.insert(I);
8342   }
8343 
8344   // Traverse the expression tree in bottom-up order looking for loads. If we
8345   // encounter an instruction we don't yet handle, we give up.
8346   auto Width = 0u;
8347   while (!Worklist.empty()) {
8348     Instruction *I;
8349     BasicBlock *Parent;
8350     std::tie(I, Parent) = Worklist.pop_back_val();
8351 
8352     // We should only be looking at scalar instructions here. If the current
8353     // instruction has a vector type, skip.
8354     auto *Ty = I->getType();
8355     if (isa<VectorType>(Ty))
8356       continue;
8357 
8358     // If the current instruction is a load, update MaxWidth to reflect the
8359     // width of the loaded value.
8360     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8361         isa<ExtractValueInst>(I))
8362       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8363 
8364     // Otherwise, we need to visit the operands of the instruction. We only
8365     // handle the interesting cases from buildTree here. If an operand is an
8366     // instruction we haven't yet visited and from the same basic block as the
8367     // user or the use is a PHI node, we add it to the worklist.
8368     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8369              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8370              isa<UnaryOperator>(I)) {
8371       for (Use &U : I->operands())
8372         if (auto *J = dyn_cast<Instruction>(U.get()))
8373           if (Visited.insert(J).second &&
8374               (isa<PHINode>(I) || J->getParent() == Parent))
8375             Worklist.emplace_back(J, J->getParent());
8376     } else {
8377       break;
8378     }
8379   }
8380 
8381   // If we didn't encounter a memory access in the expression tree, or if we
8382   // gave up for some reason, just return the width of V. Otherwise, return the
8383   // maximum width we found.
8384   if (!Width) {
8385     if (auto *CI = dyn_cast<CmpInst>(V))
8386       V = CI->getOperand(0);
8387     Width = DL->getTypeSizeInBits(V->getType());
8388   }
8389 
8390   for (Instruction *I : Visited)
8391     InstrElementSize[I] = Width;
8392 
8393   return Width;
8394 }
8395 
8396 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8397 // smaller type with a truncation. We collect the values that will be demoted
8398 // in ToDemote and additional roots that require investigating in Roots.
8399 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8400                                   SmallVectorImpl<Value *> &ToDemote,
8401                                   SmallVectorImpl<Value *> &Roots) {
8402   // We can always demote constants.
8403   if (isa<Constant>(V)) {
8404     ToDemote.push_back(V);
8405     return true;
8406   }
8407 
8408   // If the value is not an instruction in the expression with only one use, it
8409   // cannot be demoted.
8410   auto *I = dyn_cast<Instruction>(V);
8411   if (!I || !I->hasOneUse() || !Expr.count(I))
8412     return false;
8413 
8414   switch (I->getOpcode()) {
8415 
8416   // We can always demote truncations and extensions. Since truncations can
8417   // seed additional demotion, we save the truncated value.
8418   case Instruction::Trunc:
8419     Roots.push_back(I->getOperand(0));
8420     break;
8421   case Instruction::ZExt:
8422   case Instruction::SExt:
8423     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8424         isa<InsertElementInst>(I->getOperand(0)))
8425       return false;
8426     break;
8427 
8428   // We can demote certain binary operations if we can demote both of their
8429   // operands.
8430   case Instruction::Add:
8431   case Instruction::Sub:
8432   case Instruction::Mul:
8433   case Instruction::And:
8434   case Instruction::Or:
8435   case Instruction::Xor:
8436     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8437         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8438       return false;
8439     break;
8440 
8441   // We can demote selects if we can demote their true and false values.
8442   case Instruction::Select: {
8443     SelectInst *SI = cast<SelectInst>(I);
8444     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8445         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8446       return false;
8447     break;
8448   }
8449 
8450   // We can demote phis if we can demote all their incoming operands. Note that
8451   // we don't need to worry about cycles since we ensure single use above.
8452   case Instruction::PHI: {
8453     PHINode *PN = cast<PHINode>(I);
8454     for (Value *IncValue : PN->incoming_values())
8455       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8456         return false;
8457     break;
8458   }
8459 
8460   // Otherwise, conservatively give up.
8461   default:
8462     return false;
8463   }
8464 
8465   // Record the value that we can demote.
8466   ToDemote.push_back(V);
8467   return true;
8468 }
8469 
8470 void BoUpSLP::computeMinimumValueSizes() {
8471   // If there are no external uses, the expression tree must be rooted by a
8472   // store. We can't demote in-memory values, so there is nothing to do here.
8473   if (ExternalUses.empty())
8474     return;
8475 
8476   // We only attempt to truncate integer expressions.
8477   auto &TreeRoot = VectorizableTree[0]->Scalars;
8478   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8479   if (!TreeRootIT)
8480     return;
8481 
8482   // If the expression is not rooted by a store, these roots should have
8483   // external uses. We will rely on InstCombine to rewrite the expression in
8484   // the narrower type. However, InstCombine only rewrites single-use values.
8485   // This means that if a tree entry other than a root is used externally, it
8486   // must have multiple uses and InstCombine will not rewrite it. The code
8487   // below ensures that only the roots are used externally.
8488   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8489   for (auto &EU : ExternalUses)
8490     if (!Expr.erase(EU.Scalar))
8491       return;
8492   if (!Expr.empty())
8493     return;
8494 
8495   // Collect the scalar values of the vectorizable expression. We will use this
8496   // context to determine which values can be demoted. If we see a truncation,
8497   // we mark it as seeding another demotion.
8498   for (auto &EntryPtr : VectorizableTree)
8499     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8500 
8501   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8502   // have a single external user that is not in the vectorizable tree.
8503   for (auto *Root : TreeRoot)
8504     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8505       return;
8506 
8507   // Conservatively determine if we can actually truncate the roots of the
8508   // expression. Collect the values that can be demoted in ToDemote and
8509   // additional roots that require investigating in Roots.
8510   SmallVector<Value *, 32> ToDemote;
8511   SmallVector<Value *, 4> Roots;
8512   for (auto *Root : TreeRoot)
8513     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8514       return;
8515 
8516   // The maximum bit width required to represent all the values that can be
8517   // demoted without loss of precision. It would be safe to truncate the roots
8518   // of the expression to this width.
8519   auto MaxBitWidth = 8u;
8520 
8521   // We first check if all the bits of the roots are demanded. If they're not,
8522   // we can truncate the roots to this narrower type.
8523   for (auto *Root : TreeRoot) {
8524     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8525     MaxBitWidth = std::max<unsigned>(
8526         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8527   }
8528 
8529   // True if the roots can be zero-extended back to their original type, rather
8530   // than sign-extended. We know that if the leading bits are not demanded, we
8531   // can safely zero-extend. So we initialize IsKnownPositive to True.
8532   bool IsKnownPositive = true;
8533 
8534   // If all the bits of the roots are demanded, we can try a little harder to
8535   // compute a narrower type. This can happen, for example, if the roots are
8536   // getelementptr indices. InstCombine promotes these indices to the pointer
8537   // width. Thus, all their bits are technically demanded even though the
8538   // address computation might be vectorized in a smaller type.
8539   //
8540   // We start by looking at each entry that can be demoted. We compute the
8541   // maximum bit width required to store the scalar by using ValueTracking to
8542   // compute the number of high-order bits we can truncate.
8543   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8544       llvm::all_of(TreeRoot, [](Value *R) {
8545         assert(R->hasOneUse() && "Root should have only one use!");
8546         return isa<GetElementPtrInst>(R->user_back());
8547       })) {
8548     MaxBitWidth = 8u;
8549 
8550     // Determine if the sign bit of all the roots is known to be zero. If not,
8551     // IsKnownPositive is set to False.
8552     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8553       KnownBits Known = computeKnownBits(R, *DL);
8554       return Known.isNonNegative();
8555     });
8556 
8557     // Determine the maximum number of bits required to store the scalar
8558     // values.
8559     for (auto *Scalar : ToDemote) {
8560       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8561       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8562       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8563     }
8564 
8565     // If we can't prove that the sign bit is zero, we must add one to the
8566     // maximum bit width to account for the unknown sign bit. This preserves
8567     // the existing sign bit so we can safely sign-extend the root back to the
8568     // original type. Otherwise, if we know the sign bit is zero, we will
8569     // zero-extend the root instead.
8570     //
8571     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8572     //        one to the maximum bit width will yield a larger-than-necessary
8573     //        type. In general, we need to add an extra bit only if we can't
8574     //        prove that the upper bit of the original type is equal to the
8575     //        upper bit of the proposed smaller type. If these two bits are the
8576     //        same (either zero or one) we know that sign-extending from the
8577     //        smaller type will result in the same value. Here, since we can't
8578     //        yet prove this, we are just making the proposed smaller type
8579     //        larger to ensure correctness.
8580     if (!IsKnownPositive)
8581       ++MaxBitWidth;
8582   }
8583 
8584   // Round MaxBitWidth up to the next power-of-two.
8585   if (!isPowerOf2_64(MaxBitWidth))
8586     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8587 
8588   // If the maximum bit width we compute is less than the with of the roots'
8589   // type, we can proceed with the narrowing. Otherwise, do nothing.
8590   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8591     return;
8592 
8593   // If we can truncate the root, we must collect additional values that might
8594   // be demoted as a result. That is, those seeded by truncations we will
8595   // modify.
8596   while (!Roots.empty())
8597     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8598 
8599   // Finally, map the values we can demote to the maximum bit with we computed.
8600   for (auto *Scalar : ToDemote)
8601     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8602 }
8603 
8604 namespace {
8605 
8606 /// The SLPVectorizer Pass.
8607 struct SLPVectorizer : public FunctionPass {
8608   SLPVectorizerPass Impl;
8609 
8610   /// Pass identification, replacement for typeid
8611   static char ID;
8612 
8613   explicit SLPVectorizer() : FunctionPass(ID) {
8614     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8615   }
8616 
8617   bool doInitialization(Module &M) override { return false; }
8618 
8619   bool runOnFunction(Function &F) override {
8620     if (skipFunction(F))
8621       return false;
8622 
8623     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8624     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8625     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8626     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8627     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8628     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8629     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8630     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8631     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8632     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8633 
8634     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8635   }
8636 
8637   void getAnalysisUsage(AnalysisUsage &AU) const override {
8638     FunctionPass::getAnalysisUsage(AU);
8639     AU.addRequired<AssumptionCacheTracker>();
8640     AU.addRequired<ScalarEvolutionWrapperPass>();
8641     AU.addRequired<AAResultsWrapperPass>();
8642     AU.addRequired<TargetTransformInfoWrapperPass>();
8643     AU.addRequired<LoopInfoWrapperPass>();
8644     AU.addRequired<DominatorTreeWrapperPass>();
8645     AU.addRequired<DemandedBitsWrapperPass>();
8646     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8647     AU.addRequired<InjectTLIMappingsLegacy>();
8648     AU.addPreserved<LoopInfoWrapperPass>();
8649     AU.addPreserved<DominatorTreeWrapperPass>();
8650     AU.addPreserved<AAResultsWrapperPass>();
8651     AU.addPreserved<GlobalsAAWrapperPass>();
8652     AU.setPreservesCFG();
8653   }
8654 };
8655 
8656 } // end anonymous namespace
8657 
8658 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8659   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8660   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8661   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8662   auto *AA = &AM.getResult<AAManager>(F);
8663   auto *LI = &AM.getResult<LoopAnalysis>(F);
8664   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8665   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8666   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8667   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8668 
8669   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8670   if (!Changed)
8671     return PreservedAnalyses::all();
8672 
8673   PreservedAnalyses PA;
8674   PA.preserveSet<CFGAnalyses>();
8675   return PA;
8676 }
8677 
8678 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8679                                 TargetTransformInfo *TTI_,
8680                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8681                                 LoopInfo *LI_, DominatorTree *DT_,
8682                                 AssumptionCache *AC_, DemandedBits *DB_,
8683                                 OptimizationRemarkEmitter *ORE_) {
8684   if (!RunSLPVectorization)
8685     return false;
8686   SE = SE_;
8687   TTI = TTI_;
8688   TLI = TLI_;
8689   AA = AA_;
8690   LI = LI_;
8691   DT = DT_;
8692   AC = AC_;
8693   DB = DB_;
8694   DL = &F.getParent()->getDataLayout();
8695 
8696   Stores.clear();
8697   GEPs.clear();
8698   bool Changed = false;
8699 
8700   // If the target claims to have no vector registers don't attempt
8701   // vectorization.
8702   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8703     LLVM_DEBUG(
8704         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8705     return false;
8706   }
8707 
8708   // Don't vectorize when the attribute NoImplicitFloat is used.
8709   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8710     return false;
8711 
8712   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8713 
8714   // Use the bottom up slp vectorizer to construct chains that start with
8715   // store instructions.
8716   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8717 
8718   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8719   // delete instructions.
8720 
8721   // Update DFS numbers now so that we can use them for ordering.
8722   DT->updateDFSNumbers();
8723 
8724   // Scan the blocks in the function in post order.
8725   for (auto BB : post_order(&F.getEntryBlock())) {
8726     collectSeedInstructions(BB);
8727 
8728     // Vectorize trees that end at stores.
8729     if (!Stores.empty()) {
8730       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8731                         << " underlying objects.\n");
8732       Changed |= vectorizeStoreChains(R);
8733     }
8734 
8735     // Vectorize trees that end at reductions.
8736     Changed |= vectorizeChainsInBlock(BB, R);
8737 
8738     // Vectorize the index computations of getelementptr instructions. This
8739     // is primarily intended to catch gather-like idioms ending at
8740     // non-consecutive loads.
8741     if (!GEPs.empty()) {
8742       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8743                         << " underlying objects.\n");
8744       Changed |= vectorizeGEPIndices(BB, R);
8745     }
8746   }
8747 
8748   if (Changed) {
8749     R.optimizeGatherSequence();
8750     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8751   }
8752   return Changed;
8753 }
8754 
8755 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8756                                             unsigned Idx) {
8757   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8758                     << "\n");
8759   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8760   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8761   unsigned VF = Chain.size();
8762 
8763   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8764     return false;
8765 
8766   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8767                     << "\n");
8768 
8769   R.buildTree(Chain);
8770   if (R.isTreeTinyAndNotFullyVectorizable())
8771     return false;
8772   if (R.isLoadCombineCandidate())
8773     return false;
8774   R.reorderTopToBottom();
8775   R.reorderBottomToTop();
8776   R.buildExternalUses();
8777 
8778   R.computeMinimumValueSizes();
8779 
8780   InstructionCost Cost = R.getTreeCost();
8781 
8782   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8783   if (Cost < -SLPCostThreshold) {
8784     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8785 
8786     using namespace ore;
8787 
8788     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8789                                         cast<StoreInst>(Chain[0]))
8790                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8791                      << " and with tree size "
8792                      << NV("TreeSize", R.getTreeSize()));
8793 
8794     R.vectorizeTree();
8795     return true;
8796   }
8797 
8798   return false;
8799 }
8800 
8801 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8802                                         BoUpSLP &R) {
8803   // We may run into multiple chains that merge into a single chain. We mark the
8804   // stores that we vectorized so that we don't visit the same store twice.
8805   BoUpSLP::ValueSet VectorizedStores;
8806   bool Changed = false;
8807 
8808   int E = Stores.size();
8809   SmallBitVector Tails(E, false);
8810   int MaxIter = MaxStoreLookup.getValue();
8811   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8812       E, std::make_pair(E, INT_MAX));
8813   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8814   int IterCnt;
8815   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8816                                   &CheckedPairs,
8817                                   &ConsecutiveChain](int K, int Idx) {
8818     if (IterCnt >= MaxIter)
8819       return true;
8820     if (CheckedPairs[Idx].test(K))
8821       return ConsecutiveChain[K].second == 1 &&
8822              ConsecutiveChain[K].first == Idx;
8823     ++IterCnt;
8824     CheckedPairs[Idx].set(K);
8825     CheckedPairs[K].set(Idx);
8826     Optional<int> Diff = getPointersDiff(
8827         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8828         Stores[Idx]->getValueOperand()->getType(),
8829         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8830     if (!Diff || *Diff == 0)
8831       return false;
8832     int Val = *Diff;
8833     if (Val < 0) {
8834       if (ConsecutiveChain[Idx].second > -Val) {
8835         Tails.set(K);
8836         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8837       }
8838       return false;
8839     }
8840     if (ConsecutiveChain[K].second <= Val)
8841       return false;
8842 
8843     Tails.set(Idx);
8844     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8845     return Val == 1;
8846   };
8847   // Do a quadratic search on all of the given stores in reverse order and find
8848   // all of the pairs of stores that follow each other.
8849   for (int Idx = E - 1; Idx >= 0; --Idx) {
8850     // If a store has multiple consecutive store candidates, search according
8851     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8852     // This is because usually pairing with immediate succeeding or preceding
8853     // candidate create the best chance to find slp vectorization opportunity.
8854     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8855     IterCnt = 0;
8856     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8857       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8858           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8859         break;
8860   }
8861 
8862   // Tracks if we tried to vectorize stores starting from the given tail
8863   // already.
8864   SmallBitVector TriedTails(E, false);
8865   // For stores that start but don't end a link in the chain:
8866   for (int Cnt = E; Cnt > 0; --Cnt) {
8867     int I = Cnt - 1;
8868     if (ConsecutiveChain[I].first == E || Tails.test(I))
8869       continue;
8870     // We found a store instr that starts a chain. Now follow the chain and try
8871     // to vectorize it.
8872     BoUpSLP::ValueList Operands;
8873     // Collect the chain into a list.
8874     while (I != E && !VectorizedStores.count(Stores[I])) {
8875       Operands.push_back(Stores[I]);
8876       Tails.set(I);
8877       if (ConsecutiveChain[I].second != 1) {
8878         // Mark the new end in the chain and go back, if required. It might be
8879         // required if the original stores come in reversed order, for example.
8880         if (ConsecutiveChain[I].first != E &&
8881             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8882             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8883           TriedTails.set(I);
8884           Tails.reset(ConsecutiveChain[I].first);
8885           if (Cnt < ConsecutiveChain[I].first + 2)
8886             Cnt = ConsecutiveChain[I].first + 2;
8887         }
8888         break;
8889       }
8890       // Move to the next value in the chain.
8891       I = ConsecutiveChain[I].first;
8892     }
8893     assert(!Operands.empty() && "Expected non-empty list of stores.");
8894 
8895     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8896     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8897     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8898 
8899     unsigned MinVF = R.getMinVF(EltSize);
8900     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8901                               MaxElts);
8902 
8903     // FIXME: Is division-by-2 the correct step? Should we assert that the
8904     // register size is a power-of-2?
8905     unsigned StartIdx = 0;
8906     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8907       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8908         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8909         if (!VectorizedStores.count(Slice.front()) &&
8910             !VectorizedStores.count(Slice.back()) &&
8911             vectorizeStoreChain(Slice, R, Cnt)) {
8912           // Mark the vectorized stores so that we don't vectorize them again.
8913           VectorizedStores.insert(Slice.begin(), Slice.end());
8914           Changed = true;
8915           // If we vectorized initial block, no need to try to vectorize it
8916           // again.
8917           if (Cnt == StartIdx)
8918             StartIdx += Size;
8919           Cnt += Size;
8920           continue;
8921         }
8922         ++Cnt;
8923       }
8924       // Check if the whole array was vectorized already - exit.
8925       if (StartIdx >= Operands.size())
8926         break;
8927     }
8928   }
8929 
8930   return Changed;
8931 }
8932 
8933 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8934   // Initialize the collections. We will make a single pass over the block.
8935   Stores.clear();
8936   GEPs.clear();
8937 
8938   // Visit the store and getelementptr instructions in BB and organize them in
8939   // Stores and GEPs according to the underlying objects of their pointer
8940   // operands.
8941   for (Instruction &I : *BB) {
8942     // Ignore store instructions that are volatile or have a pointer operand
8943     // that doesn't point to a scalar type.
8944     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8945       if (!SI->isSimple())
8946         continue;
8947       if (!isValidElementType(SI->getValueOperand()->getType()))
8948         continue;
8949       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8950     }
8951 
8952     // Ignore getelementptr instructions that have more than one index, a
8953     // constant index, or a pointer operand that doesn't point to a scalar
8954     // type.
8955     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8956       auto Idx = GEP->idx_begin()->get();
8957       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8958         continue;
8959       if (!isValidElementType(Idx->getType()))
8960         continue;
8961       if (GEP->getType()->isVectorTy())
8962         continue;
8963       GEPs[GEP->getPointerOperand()].push_back(GEP);
8964     }
8965   }
8966 }
8967 
8968 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8969   if (!A || !B)
8970     return false;
8971   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8972     return false;
8973   Value *VL[] = {A, B};
8974   return tryToVectorizeList(VL, R);
8975 }
8976 
8977 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8978                                            bool LimitForRegisterSize) {
8979   if (VL.size() < 2)
8980     return false;
8981 
8982   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8983                     << VL.size() << ".\n");
8984 
8985   // Check that all of the parts are instructions of the same type,
8986   // we permit an alternate opcode via InstructionsState.
8987   InstructionsState S = getSameOpcode(VL);
8988   if (!S.getOpcode())
8989     return false;
8990 
8991   Instruction *I0 = cast<Instruction>(S.OpValue);
8992   // Make sure invalid types (including vector type) are rejected before
8993   // determining vectorization factor for scalar instructions.
8994   for (Value *V : VL) {
8995     Type *Ty = V->getType();
8996     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8997       // NOTE: the following will give user internal llvm type name, which may
8998       // not be useful.
8999       R.getORE()->emit([&]() {
9000         std::string type_str;
9001         llvm::raw_string_ostream rso(type_str);
9002         Ty->print(rso);
9003         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9004                << "Cannot SLP vectorize list: type "
9005                << rso.str() + " is unsupported by vectorizer";
9006       });
9007       return false;
9008     }
9009   }
9010 
9011   unsigned Sz = R.getVectorElementSize(I0);
9012   unsigned MinVF = R.getMinVF(Sz);
9013   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9014   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9015   if (MaxVF < 2) {
9016     R.getORE()->emit([&]() {
9017       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9018              << "Cannot SLP vectorize list: vectorization factor "
9019              << "less than 2 is not supported";
9020     });
9021     return false;
9022   }
9023 
9024   bool Changed = false;
9025   bool CandidateFound = false;
9026   InstructionCost MinCost = SLPCostThreshold.getValue();
9027   Type *ScalarTy = VL[0]->getType();
9028   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9029     ScalarTy = IE->getOperand(1)->getType();
9030 
9031   unsigned NextInst = 0, MaxInst = VL.size();
9032   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9033     // No actual vectorization should happen, if number of parts is the same as
9034     // provided vectorization factor (i.e. the scalar type is used for vector
9035     // code during codegen).
9036     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9037     if (TTI->getNumberOfParts(VecTy) == VF)
9038       continue;
9039     for (unsigned I = NextInst; I < MaxInst; ++I) {
9040       unsigned OpsWidth = 0;
9041 
9042       if (I + VF > MaxInst)
9043         OpsWidth = MaxInst - I;
9044       else
9045         OpsWidth = VF;
9046 
9047       if (!isPowerOf2_32(OpsWidth))
9048         continue;
9049 
9050       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9051           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9052         break;
9053 
9054       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9055       // Check that a previous iteration of this loop did not delete the Value.
9056       if (llvm::any_of(Ops, [&R](Value *V) {
9057             auto *I = dyn_cast<Instruction>(V);
9058             return I && R.isDeleted(I);
9059           }))
9060         continue;
9061 
9062       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9063                         << "\n");
9064 
9065       R.buildTree(Ops);
9066       if (R.isTreeTinyAndNotFullyVectorizable())
9067         continue;
9068       R.reorderTopToBottom();
9069       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9070       R.buildExternalUses();
9071 
9072       R.computeMinimumValueSizes();
9073       InstructionCost Cost = R.getTreeCost();
9074       CandidateFound = true;
9075       MinCost = std::min(MinCost, Cost);
9076 
9077       if (Cost < -SLPCostThreshold) {
9078         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9079         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9080                                                     cast<Instruction>(Ops[0]))
9081                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9082                                  << " and with tree size "
9083                                  << ore::NV("TreeSize", R.getTreeSize()));
9084 
9085         R.vectorizeTree();
9086         // Move to the next bundle.
9087         I += VF - 1;
9088         NextInst = I + 1;
9089         Changed = true;
9090       }
9091     }
9092   }
9093 
9094   if (!Changed && CandidateFound) {
9095     R.getORE()->emit([&]() {
9096       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9097              << "List vectorization was possible but not beneficial with cost "
9098              << ore::NV("Cost", MinCost) << " >= "
9099              << ore::NV("Treshold", -SLPCostThreshold);
9100     });
9101   } else if (!Changed) {
9102     R.getORE()->emit([&]() {
9103       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9104              << "Cannot SLP vectorize list: vectorization was impossible"
9105              << " with available vectorization factors";
9106     });
9107   }
9108   return Changed;
9109 }
9110 
9111 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9112   if (!I)
9113     return false;
9114 
9115   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9116     return false;
9117 
9118   Value *P = I->getParent();
9119 
9120   // Vectorize in current basic block only.
9121   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9122   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9123   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9124     return false;
9125 
9126   // Try to vectorize V.
9127   if (tryToVectorizePair(Op0, Op1, R))
9128     return true;
9129 
9130   auto *A = dyn_cast<BinaryOperator>(Op0);
9131   auto *B = dyn_cast<BinaryOperator>(Op1);
9132   // Try to skip B.
9133   if (B && B->hasOneUse()) {
9134     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9135     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9136     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9137       return true;
9138     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9139       return true;
9140   }
9141 
9142   // Try to skip A.
9143   if (A && A->hasOneUse()) {
9144     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9145     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9146     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9147       return true;
9148     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9149       return true;
9150   }
9151   return false;
9152 }
9153 
9154 namespace {
9155 
9156 /// Model horizontal reductions.
9157 ///
9158 /// A horizontal reduction is a tree of reduction instructions that has values
9159 /// that can be put into a vector as its leaves. For example:
9160 ///
9161 /// mul mul mul mul
9162 ///  \  /    \  /
9163 ///   +       +
9164 ///    \     /
9165 ///       +
9166 /// This tree has "mul" as its leaf values and "+" as its reduction
9167 /// instructions. A reduction can feed into a store or a binary operation
9168 /// feeding a phi.
9169 ///    ...
9170 ///    \  /
9171 ///     +
9172 ///     |
9173 ///  phi +=
9174 ///
9175 ///  Or:
9176 ///    ...
9177 ///    \  /
9178 ///     +
9179 ///     |
9180 ///   *p =
9181 ///
9182 class HorizontalReduction {
9183   using ReductionOpsType = SmallVector<Value *, 16>;
9184   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9185   ReductionOpsListType ReductionOps;
9186   SmallVector<Value *, 32> ReducedVals;
9187   // Use map vector to make stable output.
9188   MapVector<Instruction *, Value *> ExtraArgs;
9189   WeakTrackingVH ReductionRoot;
9190   /// The type of reduction operation.
9191   RecurKind RdxKind;
9192 
9193   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9194 
9195   static bool isCmpSelMinMax(Instruction *I) {
9196     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9197            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9198   }
9199 
9200   // And/or are potentially poison-safe logical patterns like:
9201   // select x, y, false
9202   // select x, true, y
9203   static bool isBoolLogicOp(Instruction *I) {
9204     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9205            match(I, m_LogicalOr(m_Value(), m_Value()));
9206   }
9207 
9208   /// Checks if instruction is associative and can be vectorized.
9209   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9210     if (Kind == RecurKind::None)
9211       return false;
9212 
9213     // Integer ops that map to select instructions or intrinsics are fine.
9214     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9215         isBoolLogicOp(I))
9216       return true;
9217 
9218     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9219       // FP min/max are associative except for NaN and -0.0. We do not
9220       // have to rule out -0.0 here because the intrinsic semantics do not
9221       // specify a fixed result for it.
9222       return I->getFastMathFlags().noNaNs();
9223     }
9224 
9225     return I->isAssociative();
9226   }
9227 
9228   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9229     // Poison-safe 'or' takes the form: select X, true, Y
9230     // To make that work with the normal operand processing, we skip the
9231     // true value operand.
9232     // TODO: Change the code and data structures to handle this without a hack.
9233     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9234       return I->getOperand(2);
9235     return I->getOperand(Index);
9236   }
9237 
9238   /// Checks if the ParentStackElem.first should be marked as a reduction
9239   /// operation with an extra argument or as extra argument itself.
9240   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9241                     Value *ExtraArg) {
9242     if (ExtraArgs.count(ParentStackElem.first)) {
9243       ExtraArgs[ParentStackElem.first] = nullptr;
9244       // We ran into something like:
9245       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9246       // The whole ParentStackElem.first should be considered as an extra value
9247       // in this case.
9248       // Do not perform analysis of remaining operands of ParentStackElem.first
9249       // instruction, this whole instruction is an extra argument.
9250       ParentStackElem.second = INVALID_OPERAND_INDEX;
9251     } else {
9252       // We ran into something like:
9253       // ParentStackElem.first += ... + ExtraArg + ...
9254       ExtraArgs[ParentStackElem.first] = ExtraArg;
9255     }
9256   }
9257 
9258   /// Creates reduction operation with the current opcode.
9259   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9260                          Value *RHS, const Twine &Name, bool UseSelect) {
9261     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9262     switch (Kind) {
9263     case RecurKind::Or:
9264       if (UseSelect &&
9265           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9266         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9267       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9268                                  Name);
9269     case RecurKind::And:
9270       if (UseSelect &&
9271           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9272         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9273       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9274                                  Name);
9275     case RecurKind::Add:
9276     case RecurKind::Mul:
9277     case RecurKind::Xor:
9278     case RecurKind::FAdd:
9279     case RecurKind::FMul:
9280       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9281                                  Name);
9282     case RecurKind::FMax:
9283       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9284     case RecurKind::FMin:
9285       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9286     case RecurKind::SMax:
9287       if (UseSelect) {
9288         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9289         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9290       }
9291       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9292     case RecurKind::SMin:
9293       if (UseSelect) {
9294         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9295         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9296       }
9297       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9298     case RecurKind::UMax:
9299       if (UseSelect) {
9300         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9301         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9302       }
9303       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9304     case RecurKind::UMin:
9305       if (UseSelect) {
9306         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9307         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9308       }
9309       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9310     default:
9311       llvm_unreachable("Unknown reduction operation.");
9312     }
9313   }
9314 
9315   /// Creates reduction operation with the current opcode with the IR flags
9316   /// from \p ReductionOps.
9317   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9318                          Value *RHS, const Twine &Name,
9319                          const ReductionOpsListType &ReductionOps) {
9320     bool UseSelect = ReductionOps.size() == 2 ||
9321                      // Logical or/and.
9322                      (ReductionOps.size() == 1 &&
9323                       isa<SelectInst>(ReductionOps.front().front()));
9324     assert((!UseSelect || ReductionOps.size() != 2 ||
9325             isa<SelectInst>(ReductionOps[1][0])) &&
9326            "Expected cmp + select pairs for reduction");
9327     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9328     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9329       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9330         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9331         propagateIRFlags(Op, ReductionOps[1]);
9332         return Op;
9333       }
9334     }
9335     propagateIRFlags(Op, ReductionOps[0]);
9336     return Op;
9337   }
9338 
9339   /// Creates reduction operation with the current opcode with the IR flags
9340   /// from \p I.
9341   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9342                          Value *RHS, const Twine &Name, Instruction *I) {
9343     auto *SelI = dyn_cast<SelectInst>(I);
9344     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9345     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9346       if (auto *Sel = dyn_cast<SelectInst>(Op))
9347         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9348     }
9349     propagateIRFlags(Op, I);
9350     return Op;
9351   }
9352 
9353   static RecurKind getRdxKind(Instruction *I) {
9354     assert(I && "Expected instruction for reduction matching");
9355     if (match(I, m_Add(m_Value(), m_Value())))
9356       return RecurKind::Add;
9357     if (match(I, m_Mul(m_Value(), m_Value())))
9358       return RecurKind::Mul;
9359     if (match(I, m_And(m_Value(), m_Value())) ||
9360         match(I, m_LogicalAnd(m_Value(), m_Value())))
9361       return RecurKind::And;
9362     if (match(I, m_Or(m_Value(), m_Value())) ||
9363         match(I, m_LogicalOr(m_Value(), m_Value())))
9364       return RecurKind::Or;
9365     if (match(I, m_Xor(m_Value(), m_Value())))
9366       return RecurKind::Xor;
9367     if (match(I, m_FAdd(m_Value(), m_Value())))
9368       return RecurKind::FAdd;
9369     if (match(I, m_FMul(m_Value(), m_Value())))
9370       return RecurKind::FMul;
9371 
9372     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9373       return RecurKind::FMax;
9374     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9375       return RecurKind::FMin;
9376 
9377     // This matches either cmp+select or intrinsics. SLP is expected to handle
9378     // either form.
9379     // TODO: If we are canonicalizing to intrinsics, we can remove several
9380     //       special-case paths that deal with selects.
9381     if (match(I, m_SMax(m_Value(), m_Value())))
9382       return RecurKind::SMax;
9383     if (match(I, m_SMin(m_Value(), m_Value())))
9384       return RecurKind::SMin;
9385     if (match(I, m_UMax(m_Value(), m_Value())))
9386       return RecurKind::UMax;
9387     if (match(I, m_UMin(m_Value(), m_Value())))
9388       return RecurKind::UMin;
9389 
9390     if (auto *Select = dyn_cast<SelectInst>(I)) {
9391       // Try harder: look for min/max pattern based on instructions producing
9392       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9393       // During the intermediate stages of SLP, it's very common to have
9394       // pattern like this (since optimizeGatherSequence is run only once
9395       // at the end):
9396       // %1 = extractelement <2 x i32> %a, i32 0
9397       // %2 = extractelement <2 x i32> %a, i32 1
9398       // %cond = icmp sgt i32 %1, %2
9399       // %3 = extractelement <2 x i32> %a, i32 0
9400       // %4 = extractelement <2 x i32> %a, i32 1
9401       // %select = select i1 %cond, i32 %3, i32 %4
9402       CmpInst::Predicate Pred;
9403       Instruction *L1;
9404       Instruction *L2;
9405 
9406       Value *LHS = Select->getTrueValue();
9407       Value *RHS = Select->getFalseValue();
9408       Value *Cond = Select->getCondition();
9409 
9410       // TODO: Support inverse predicates.
9411       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9412         if (!isa<ExtractElementInst>(RHS) ||
9413             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9414           return RecurKind::None;
9415       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9416         if (!isa<ExtractElementInst>(LHS) ||
9417             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9418           return RecurKind::None;
9419       } else {
9420         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9421           return RecurKind::None;
9422         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9423             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9424             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9425           return RecurKind::None;
9426       }
9427 
9428       switch (Pred) {
9429       default:
9430         return RecurKind::None;
9431       case CmpInst::ICMP_SGT:
9432       case CmpInst::ICMP_SGE:
9433         return RecurKind::SMax;
9434       case CmpInst::ICMP_SLT:
9435       case CmpInst::ICMP_SLE:
9436         return RecurKind::SMin;
9437       case CmpInst::ICMP_UGT:
9438       case CmpInst::ICMP_UGE:
9439         return RecurKind::UMax;
9440       case CmpInst::ICMP_ULT:
9441       case CmpInst::ICMP_ULE:
9442         return RecurKind::UMin;
9443       }
9444     }
9445     return RecurKind::None;
9446   }
9447 
9448   /// Get the index of the first operand.
9449   static unsigned getFirstOperandIndex(Instruction *I) {
9450     return isCmpSelMinMax(I) ? 1 : 0;
9451   }
9452 
9453   /// Total number of operands in the reduction operation.
9454   static unsigned getNumberOfOperands(Instruction *I) {
9455     return isCmpSelMinMax(I) ? 3 : 2;
9456   }
9457 
9458   /// Checks if the instruction is in basic block \p BB.
9459   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9460   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9461     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9462       auto *Sel = cast<SelectInst>(I);
9463       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9464       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9465     }
9466     return I->getParent() == BB;
9467   }
9468 
9469   /// Expected number of uses for reduction operations/reduced values.
9470   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9471     if (IsCmpSelMinMax) {
9472       // SelectInst must be used twice while the condition op must have single
9473       // use only.
9474       if (auto *Sel = dyn_cast<SelectInst>(I))
9475         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9476       return I->hasNUses(2);
9477     }
9478 
9479     // Arithmetic reduction operation must be used once only.
9480     return I->hasOneUse();
9481   }
9482 
9483   /// Initializes the list of reduction operations.
9484   void initReductionOps(Instruction *I) {
9485     if (isCmpSelMinMax(I))
9486       ReductionOps.assign(2, ReductionOpsType());
9487     else
9488       ReductionOps.assign(1, ReductionOpsType());
9489   }
9490 
9491   /// Add all reduction operations for the reduction instruction \p I.
9492   void addReductionOps(Instruction *I) {
9493     if (isCmpSelMinMax(I)) {
9494       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9495       ReductionOps[1].emplace_back(I);
9496     } else {
9497       ReductionOps[0].emplace_back(I);
9498     }
9499   }
9500 
9501   static Value *getLHS(RecurKind Kind, Instruction *I) {
9502     if (Kind == RecurKind::None)
9503       return nullptr;
9504     return I->getOperand(getFirstOperandIndex(I));
9505   }
9506   static Value *getRHS(RecurKind Kind, Instruction *I) {
9507     if (Kind == RecurKind::None)
9508       return nullptr;
9509     return I->getOperand(getFirstOperandIndex(I) + 1);
9510   }
9511 
9512 public:
9513   HorizontalReduction() = default;
9514 
9515   /// Try to find a reduction tree.
9516   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9517     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9518            "Phi needs to use the binary operator");
9519     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9520             isa<IntrinsicInst>(Inst)) &&
9521            "Expected binop, select, or intrinsic for reduction matching");
9522     RdxKind = getRdxKind(Inst);
9523 
9524     // We could have a initial reductions that is not an add.
9525     //  r *= v1 + v2 + v3 + v4
9526     // In such a case start looking for a tree rooted in the first '+'.
9527     if (Phi) {
9528       if (getLHS(RdxKind, Inst) == Phi) {
9529         Phi = nullptr;
9530         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9531         if (!Inst)
9532           return false;
9533         RdxKind = getRdxKind(Inst);
9534       } else if (getRHS(RdxKind, Inst) == Phi) {
9535         Phi = nullptr;
9536         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9537         if (!Inst)
9538           return false;
9539         RdxKind = getRdxKind(Inst);
9540       }
9541     }
9542 
9543     if (!isVectorizable(RdxKind, Inst))
9544       return false;
9545 
9546     // Analyze "regular" integer/FP types for reductions - no target-specific
9547     // types or pointers.
9548     Type *Ty = Inst->getType();
9549     if (!isValidElementType(Ty) || Ty->isPointerTy())
9550       return false;
9551 
9552     // Though the ultimate reduction may have multiple uses, its condition must
9553     // have only single use.
9554     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9555       if (!Sel->getCondition()->hasOneUse())
9556         return false;
9557 
9558     ReductionRoot = Inst;
9559 
9560     // The opcode for leaf values that we perform a reduction on.
9561     // For example: load(x) + load(y) + load(z) + fptoui(w)
9562     // The leaf opcode for 'w' does not match, so we don't include it as a
9563     // potential candidate for the reduction.
9564     unsigned LeafOpcode = 0;
9565 
9566     // Post-order traverse the reduction tree starting at Inst. We only handle
9567     // true trees containing binary operators or selects.
9568     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9569     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9570     initReductionOps(Inst);
9571     while (!Stack.empty()) {
9572       Instruction *TreeN = Stack.back().first;
9573       unsigned EdgeToVisit = Stack.back().second++;
9574       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9575       bool IsReducedValue = TreeRdxKind != RdxKind;
9576 
9577       // Postorder visit.
9578       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9579         if (IsReducedValue)
9580           ReducedVals.push_back(TreeN);
9581         else {
9582           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9583           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9584             // Check if TreeN is an extra argument of its parent operation.
9585             if (Stack.size() <= 1) {
9586               // TreeN can't be an extra argument as it is a root reduction
9587               // operation.
9588               return false;
9589             }
9590             // Yes, TreeN is an extra argument, do not add it to a list of
9591             // reduction operations.
9592             // Stack[Stack.size() - 2] always points to the parent operation.
9593             markExtraArg(Stack[Stack.size() - 2], TreeN);
9594             ExtraArgs.erase(TreeN);
9595           } else
9596             addReductionOps(TreeN);
9597         }
9598         // Retract.
9599         Stack.pop_back();
9600         continue;
9601       }
9602 
9603       // Visit operands.
9604       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9605       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9606       if (!EdgeInst) {
9607         // Edge value is not a reduction instruction or a leaf instruction.
9608         // (It may be a constant, function argument, or something else.)
9609         markExtraArg(Stack.back(), EdgeVal);
9610         continue;
9611       }
9612       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9613       // Continue analysis if the next operand is a reduction operation or
9614       // (possibly) a leaf value. If the leaf value opcode is not set,
9615       // the first met operation != reduction operation is considered as the
9616       // leaf opcode.
9617       // Only handle trees in the current basic block.
9618       // Each tree node needs to have minimal number of users except for the
9619       // ultimate reduction.
9620       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9621       if (EdgeInst != Phi && EdgeInst != Inst &&
9622           hasSameParent(EdgeInst, Inst->getParent()) &&
9623           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9624           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9625         if (IsRdxInst) {
9626           // We need to be able to reassociate the reduction operations.
9627           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9628             // I is an extra argument for TreeN (its parent operation).
9629             markExtraArg(Stack.back(), EdgeInst);
9630             continue;
9631           }
9632         } else if (!LeafOpcode) {
9633           LeafOpcode = EdgeInst->getOpcode();
9634         }
9635         Stack.push_back(
9636             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9637         continue;
9638       }
9639       // I is an extra argument for TreeN (its parent operation).
9640       markExtraArg(Stack.back(), EdgeInst);
9641     }
9642     return true;
9643   }
9644 
9645   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9646   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9647     // If there are a sufficient number of reduction values, reduce
9648     // to a nearby power-of-2. We can safely generate oversized
9649     // vectors and rely on the backend to split them to legal sizes.
9650     unsigned NumReducedVals = ReducedVals.size();
9651     if (NumReducedVals < 4)
9652       return nullptr;
9653 
9654     // Intersect the fast-math-flags from all reduction operations.
9655     FastMathFlags RdxFMF;
9656     RdxFMF.set();
9657     for (ReductionOpsType &RdxOp : ReductionOps) {
9658       for (Value *RdxVal : RdxOp) {
9659         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9660           RdxFMF &= FPMO->getFastMathFlags();
9661       }
9662     }
9663 
9664     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9665     Builder.setFastMathFlags(RdxFMF);
9666 
9667     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9668     // The same extra argument may be used several times, so log each attempt
9669     // to use it.
9670     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9671       assert(Pair.first && "DebugLoc must be set.");
9672       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9673     }
9674 
9675     // The compare instruction of a min/max is the insertion point for new
9676     // instructions and may be replaced with a new compare instruction.
9677     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9678       assert(isa<SelectInst>(RdxRootInst) &&
9679              "Expected min/max reduction to have select root instruction");
9680       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9681       assert(isa<Instruction>(ScalarCond) &&
9682              "Expected min/max reduction to have compare condition");
9683       return cast<Instruction>(ScalarCond);
9684     };
9685 
9686     // The reduction root is used as the insertion point for new instructions,
9687     // so set it as externally used to prevent it from being deleted.
9688     ExternallyUsedValues[ReductionRoot];
9689     SmallVector<Value *, 16> IgnoreList;
9690     for (ReductionOpsType &RdxOp : ReductionOps)
9691       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9692 
9693     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9694     if (NumReducedVals > ReduxWidth) {
9695       // In the loop below, we are building a tree based on a window of
9696       // 'ReduxWidth' values.
9697       // If the operands of those values have common traits (compare predicate,
9698       // constant operand, etc), then we want to group those together to
9699       // minimize the cost of the reduction.
9700 
9701       // TODO: This should be extended to count common operands for
9702       //       compares and binops.
9703 
9704       // Step 1: Count the number of times each compare predicate occurs.
9705       SmallDenseMap<unsigned, unsigned> PredCountMap;
9706       for (Value *RdxVal : ReducedVals) {
9707         CmpInst::Predicate Pred;
9708         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9709           ++PredCountMap[Pred];
9710       }
9711       // Step 2: Sort the values so the most common predicates come first.
9712       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9713         CmpInst::Predicate PredA, PredB;
9714         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9715             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9716           return PredCountMap[PredA] > PredCountMap[PredB];
9717         }
9718         return false;
9719       });
9720     }
9721 
9722     Value *VectorizedTree = nullptr;
9723     unsigned i = 0;
9724     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9725       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9726       V.buildTree(VL, IgnoreList);
9727       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9728         break;
9729       if (V.isLoadCombineReductionCandidate(RdxKind))
9730         break;
9731       V.reorderTopToBottom();
9732       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9733       V.buildExternalUses(ExternallyUsedValues);
9734 
9735       // For a poison-safe boolean logic reduction, do not replace select
9736       // instructions with logic ops. All reduced values will be frozen (see
9737       // below) to prevent leaking poison.
9738       if (isa<SelectInst>(ReductionRoot) &&
9739           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9740           NumReducedVals != ReduxWidth)
9741         break;
9742 
9743       V.computeMinimumValueSizes();
9744 
9745       // Estimate cost.
9746       InstructionCost TreeCost =
9747           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9748       InstructionCost ReductionCost =
9749           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9750       InstructionCost Cost = TreeCost + ReductionCost;
9751       if (!Cost.isValid()) {
9752         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9753         return nullptr;
9754       }
9755       if (Cost >= -SLPCostThreshold) {
9756         V.getORE()->emit([&]() {
9757           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9758                                           cast<Instruction>(VL[0]))
9759                  << "Vectorizing horizontal reduction is possible"
9760                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9761                  << " and threshold "
9762                  << ore::NV("Threshold", -SLPCostThreshold);
9763         });
9764         break;
9765       }
9766 
9767       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9768                         << Cost << ". (HorRdx)\n");
9769       V.getORE()->emit([&]() {
9770         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9771                                   cast<Instruction>(VL[0]))
9772                << "Vectorized horizontal reduction with cost "
9773                << ore::NV("Cost", Cost) << " and with tree size "
9774                << ore::NV("TreeSize", V.getTreeSize());
9775       });
9776 
9777       // Vectorize a tree.
9778       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9779       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9780 
9781       // Emit a reduction. If the root is a select (min/max idiom), the insert
9782       // point is the compare condition of that select.
9783       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9784       if (isCmpSelMinMax(RdxRootInst))
9785         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9786       else
9787         Builder.SetInsertPoint(RdxRootInst);
9788 
9789       // To prevent poison from leaking across what used to be sequential, safe,
9790       // scalar boolean logic operations, the reduction operand must be frozen.
9791       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9792         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9793 
9794       Value *ReducedSubTree =
9795           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9796 
9797       if (!VectorizedTree) {
9798         // Initialize the final value in the reduction.
9799         VectorizedTree = ReducedSubTree;
9800       } else {
9801         // Update the final value in the reduction.
9802         Builder.SetCurrentDebugLocation(Loc);
9803         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9804                                   ReducedSubTree, "op.rdx", ReductionOps);
9805       }
9806       i += ReduxWidth;
9807       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9808     }
9809 
9810     if (VectorizedTree) {
9811       // Finish the reduction.
9812       for (; i < NumReducedVals; ++i) {
9813         auto *I = cast<Instruction>(ReducedVals[i]);
9814         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9815         VectorizedTree =
9816             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9817       }
9818       for (auto &Pair : ExternallyUsedValues) {
9819         // Add each externally used value to the final reduction.
9820         for (auto *I : Pair.second) {
9821           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9822           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9823                                     Pair.first, "op.extra", I);
9824         }
9825       }
9826 
9827       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9828 
9829       // The original scalar reduction is expected to have no remaining
9830       // uses outside the reduction tree itself.  Assert that we got this
9831       // correct, replace internal uses with undef, and mark for eventual
9832       // deletion.
9833 #ifndef NDEBUG
9834       SmallSet<Value *, 4> IgnoreSet;
9835       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
9836 #endif
9837       for (auto *Ignore : IgnoreList) {
9838 #ifndef NDEBUG
9839         for (auto *U : Ignore->users()) {
9840           assert(IgnoreSet.count(U));
9841         }
9842 #endif
9843         if (!Ignore->use_empty()) {
9844           Value *Undef = UndefValue::get(Ignore->getType());
9845           Ignore->replaceAllUsesWith(Undef);
9846         }
9847         V.eraseInstruction(cast<Instruction>(Ignore));
9848       }
9849     }
9850     return VectorizedTree;
9851   }
9852 
9853   unsigned numReductionValues() const { return ReducedVals.size(); }
9854 
9855 private:
9856   /// Calculate the cost of a reduction.
9857   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9858                                    Value *FirstReducedVal, unsigned ReduxWidth,
9859                                    FastMathFlags FMF) {
9860     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9861     Type *ScalarTy = FirstReducedVal->getType();
9862     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9863     InstructionCost VectorCost, ScalarCost;
9864     switch (RdxKind) {
9865     case RecurKind::Add:
9866     case RecurKind::Mul:
9867     case RecurKind::Or:
9868     case RecurKind::And:
9869     case RecurKind::Xor:
9870     case RecurKind::FAdd:
9871     case RecurKind::FMul: {
9872       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9873       VectorCost =
9874           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9875       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9876       break;
9877     }
9878     case RecurKind::FMax:
9879     case RecurKind::FMin: {
9880       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9881       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9882       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9883                                                /*IsUnsigned=*/false, CostKind);
9884       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9885       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9886                                            SclCondTy, RdxPred, CostKind) +
9887                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9888                                            SclCondTy, RdxPred, CostKind);
9889       break;
9890     }
9891     case RecurKind::SMax:
9892     case RecurKind::SMin:
9893     case RecurKind::UMax:
9894     case RecurKind::UMin: {
9895       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9896       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9897       bool IsUnsigned =
9898           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9899       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9900                                                CostKind);
9901       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9902       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9903                                            SclCondTy, RdxPred, CostKind) +
9904                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9905                                            SclCondTy, RdxPred, CostKind);
9906       break;
9907     }
9908     default:
9909       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9910     }
9911 
9912     // Scalar cost is repeated for N-1 elements.
9913     ScalarCost *= (ReduxWidth - 1);
9914     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9915                       << " for reduction that starts with " << *FirstReducedVal
9916                       << " (It is a splitting reduction)\n");
9917     return VectorCost - ScalarCost;
9918   }
9919 
9920   /// Emit a horizontal reduction of the vectorized value.
9921   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9922                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9923     assert(VectorizedValue && "Need to have a vectorized tree node");
9924     assert(isPowerOf2_32(ReduxWidth) &&
9925            "We only handle power-of-two reductions for now");
9926     assert(RdxKind != RecurKind::FMulAdd &&
9927            "A call to the llvm.fmuladd intrinsic is not handled yet");
9928 
9929     ++NumVectorInstructions;
9930     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9931   }
9932 };
9933 
9934 } // end anonymous namespace
9935 
9936 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9937   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9938     return cast<FixedVectorType>(IE->getType())->getNumElements();
9939 
9940   unsigned AggregateSize = 1;
9941   auto *IV = cast<InsertValueInst>(InsertInst);
9942   Type *CurrentType = IV->getType();
9943   do {
9944     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9945       for (auto *Elt : ST->elements())
9946         if (Elt != ST->getElementType(0)) // check homogeneity
9947           return None;
9948       AggregateSize *= ST->getNumElements();
9949       CurrentType = ST->getElementType(0);
9950     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9951       AggregateSize *= AT->getNumElements();
9952       CurrentType = AT->getElementType();
9953     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9954       AggregateSize *= VT->getNumElements();
9955       return AggregateSize;
9956     } else if (CurrentType->isSingleValueType()) {
9957       return AggregateSize;
9958     } else {
9959       return None;
9960     }
9961   } while (true);
9962 }
9963 
9964 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9965                                    TargetTransformInfo *TTI,
9966                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9967                                    SmallVectorImpl<Value *> &InsertElts,
9968                                    unsigned OperandOffset) {
9969   do {
9970     Value *InsertedOperand = LastInsertInst->getOperand(1);
9971     Optional<unsigned> OperandIndex =
9972         getInsertIndex(LastInsertInst, OperandOffset);
9973     if (!OperandIndex)
9974       return;
9975     if (isa<InsertElementInst>(InsertedOperand) ||
9976         isa<InsertValueInst>(InsertedOperand)) {
9977       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9978                              BuildVectorOpds, InsertElts, *OperandIndex);
9979 
9980     } else {
9981       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9982       InsertElts[*OperandIndex] = LastInsertInst;
9983     }
9984     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9985   } while (LastInsertInst != nullptr &&
9986            (isa<InsertValueInst>(LastInsertInst) ||
9987             isa<InsertElementInst>(LastInsertInst)) &&
9988            LastInsertInst->hasOneUse());
9989 }
9990 
9991 /// Recognize construction of vectors like
9992 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9993 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9994 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9995 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9996 ///  starting from the last insertelement or insertvalue instruction.
9997 ///
9998 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9999 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10000 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10001 ///
10002 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10003 ///
10004 /// \return true if it matches.
10005 static bool findBuildAggregate(Instruction *LastInsertInst,
10006                                TargetTransformInfo *TTI,
10007                                SmallVectorImpl<Value *> &BuildVectorOpds,
10008                                SmallVectorImpl<Value *> &InsertElts) {
10009 
10010   assert((isa<InsertElementInst>(LastInsertInst) ||
10011           isa<InsertValueInst>(LastInsertInst)) &&
10012          "Expected insertelement or insertvalue instruction!");
10013 
10014   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10015          "Expected empty result vectors!");
10016 
10017   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10018   if (!AggregateSize)
10019     return false;
10020   BuildVectorOpds.resize(*AggregateSize);
10021   InsertElts.resize(*AggregateSize);
10022 
10023   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10024   llvm::erase_value(BuildVectorOpds, nullptr);
10025   llvm::erase_value(InsertElts, nullptr);
10026   if (BuildVectorOpds.size() >= 2)
10027     return true;
10028 
10029   return false;
10030 }
10031 
10032 /// Try and get a reduction value from a phi node.
10033 ///
10034 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10035 /// if they come from either \p ParentBB or a containing loop latch.
10036 ///
10037 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10038 /// if not possible.
10039 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10040                                 BasicBlock *ParentBB, LoopInfo *LI) {
10041   // There are situations where the reduction value is not dominated by the
10042   // reduction phi. Vectorizing such cases has been reported to cause
10043   // miscompiles. See PR25787.
10044   auto DominatedReduxValue = [&](Value *R) {
10045     return isa<Instruction>(R) &&
10046            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10047   };
10048 
10049   Value *Rdx = nullptr;
10050 
10051   // Return the incoming value if it comes from the same BB as the phi node.
10052   if (P->getIncomingBlock(0) == ParentBB) {
10053     Rdx = P->getIncomingValue(0);
10054   } else if (P->getIncomingBlock(1) == ParentBB) {
10055     Rdx = P->getIncomingValue(1);
10056   }
10057 
10058   if (Rdx && DominatedReduxValue(Rdx))
10059     return Rdx;
10060 
10061   // Otherwise, check whether we have a loop latch to look at.
10062   Loop *BBL = LI->getLoopFor(ParentBB);
10063   if (!BBL)
10064     return nullptr;
10065   BasicBlock *BBLatch = BBL->getLoopLatch();
10066   if (!BBLatch)
10067     return nullptr;
10068 
10069   // There is a loop latch, return the incoming value if it comes from
10070   // that. This reduction pattern occasionally turns up.
10071   if (P->getIncomingBlock(0) == BBLatch) {
10072     Rdx = P->getIncomingValue(0);
10073   } else if (P->getIncomingBlock(1) == BBLatch) {
10074     Rdx = P->getIncomingValue(1);
10075   }
10076 
10077   if (Rdx && DominatedReduxValue(Rdx))
10078     return Rdx;
10079 
10080   return nullptr;
10081 }
10082 
10083 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10084   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10085     return true;
10086   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10087     return true;
10088   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10089     return true;
10090   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10091     return true;
10092   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10093     return true;
10094   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10095     return true;
10096   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10097     return true;
10098   return false;
10099 }
10100 
10101 /// Attempt to reduce a horizontal reduction.
10102 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10103 /// with reduction operators \a Root (or one of its operands) in a basic block
10104 /// \a BB, then check if it can be done. If horizontal reduction is not found
10105 /// and root instruction is a binary operation, vectorization of the operands is
10106 /// attempted.
10107 /// \returns true if a horizontal reduction was matched and reduced or operands
10108 /// of one of the binary instruction were vectorized.
10109 /// \returns false if a horizontal reduction was not matched (or not possible)
10110 /// or no vectorization of any binary operation feeding \a Root instruction was
10111 /// performed.
10112 static bool tryToVectorizeHorReductionOrInstOperands(
10113     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10114     TargetTransformInfo *TTI,
10115     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10116   if (!ShouldVectorizeHor)
10117     return false;
10118 
10119   if (!Root)
10120     return false;
10121 
10122   if (Root->getParent() != BB || isa<PHINode>(Root))
10123     return false;
10124   // Start analysis starting from Root instruction. If horizontal reduction is
10125   // found, try to vectorize it. If it is not a horizontal reduction or
10126   // vectorization is not possible or not effective, and currently analyzed
10127   // instruction is a binary operation, try to vectorize the operands, using
10128   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10129   // the same procedure considering each operand as a possible root of the
10130   // horizontal reduction.
10131   // Interrupt the process if the Root instruction itself was vectorized or all
10132   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10133   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10134   // CmpInsts so we can skip extra attempts in
10135   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10136   std::queue<std::pair<Instruction *, unsigned>> Stack;
10137   Stack.emplace(Root, 0);
10138   SmallPtrSet<Value *, 8> VisitedInstrs;
10139   SmallVector<WeakTrackingVH> PostponedInsts;
10140   bool Res = false;
10141   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10142                                      Value *&B1) -> Value * {
10143     bool IsBinop = matchRdxBop(Inst, B0, B1);
10144     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10145     if (IsBinop || IsSelect) {
10146       HorizontalReduction HorRdx;
10147       if (HorRdx.matchAssociativeReduction(P, Inst))
10148         return HorRdx.tryToReduce(R, TTI);
10149     }
10150     return nullptr;
10151   };
10152   while (!Stack.empty()) {
10153     Instruction *Inst;
10154     unsigned Level;
10155     std::tie(Inst, Level) = Stack.front();
10156     Stack.pop();
10157     // Do not try to analyze instruction that has already been vectorized.
10158     // This may happen when we vectorize instruction operands on a previous
10159     // iteration while stack was populated before that happened.
10160     if (R.isDeleted(Inst))
10161       continue;
10162     Value *B0 = nullptr, *B1 = nullptr;
10163     if (Value *V = TryToReduce(Inst, B0, B1)) {
10164       Res = true;
10165       // Set P to nullptr to avoid re-analysis of phi node in
10166       // matchAssociativeReduction function unless this is the root node.
10167       P = nullptr;
10168       if (auto *I = dyn_cast<Instruction>(V)) {
10169         // Try to find another reduction.
10170         Stack.emplace(I, Level);
10171         continue;
10172       }
10173     } else {
10174       bool IsBinop = B0 && B1;
10175       if (P && IsBinop) {
10176         Inst = dyn_cast<Instruction>(B0);
10177         if (Inst == P)
10178           Inst = dyn_cast<Instruction>(B1);
10179         if (!Inst) {
10180           // Set P to nullptr to avoid re-analysis of phi node in
10181           // matchAssociativeReduction function unless this is the root node.
10182           P = nullptr;
10183           continue;
10184         }
10185       }
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       // Do not try to vectorize CmpInst operands, this is done separately.
10190       // Final attempt for binop args vectorization should happen after the loop
10191       // to try to find reductions.
10192       if (!isa<CmpInst>(Inst))
10193         PostponedInsts.push_back(Inst);
10194     }
10195 
10196     // Try to vectorize operands.
10197     // Continue analysis for the instruction from the same basic block only to
10198     // save compile time.
10199     if (++Level < RecursionMaxDepth)
10200       for (auto *Op : Inst->operand_values())
10201         if (VisitedInstrs.insert(Op).second)
10202           if (auto *I = dyn_cast<Instruction>(Op))
10203             // Do not try to vectorize CmpInst operands,  this is done
10204             // separately.
10205             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10206                 I->getParent() == BB)
10207               Stack.emplace(I, Level);
10208   }
10209   // Try to vectorized binops where reductions were not found.
10210   for (Value *V : PostponedInsts)
10211     if (auto *Inst = dyn_cast<Instruction>(V))
10212       if (!R.isDeleted(Inst))
10213         Res |= Vectorize(Inst, R);
10214   return Res;
10215 }
10216 
10217 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10218                                                  BasicBlock *BB, BoUpSLP &R,
10219                                                  TargetTransformInfo *TTI) {
10220   auto *I = dyn_cast_or_null<Instruction>(V);
10221   if (!I)
10222     return false;
10223 
10224   if (!isa<BinaryOperator>(I))
10225     P = nullptr;
10226   // Try to match and vectorize a horizontal reduction.
10227   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10228     return tryToVectorize(I, R);
10229   };
10230   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10231                                                   ExtraVectorization);
10232 }
10233 
10234 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10235                                                  BasicBlock *BB, BoUpSLP &R) {
10236   const DataLayout &DL = BB->getModule()->getDataLayout();
10237   if (!R.canMapToVector(IVI->getType(), DL))
10238     return false;
10239 
10240   SmallVector<Value *, 16> BuildVectorOpds;
10241   SmallVector<Value *, 16> BuildVectorInsts;
10242   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10243     return false;
10244 
10245   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10246   // Aggregate value is unlikely to be processed in vector register.
10247   return tryToVectorizeList(BuildVectorOpds, R);
10248 }
10249 
10250 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10251                                                    BasicBlock *BB, BoUpSLP &R) {
10252   SmallVector<Value *, 16> BuildVectorInsts;
10253   SmallVector<Value *, 16> BuildVectorOpds;
10254   SmallVector<int> Mask;
10255   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10256       (llvm::all_of(
10257            BuildVectorOpds,
10258            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10259        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10260     return false;
10261 
10262   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10263   return tryToVectorizeList(BuildVectorInsts, R);
10264 }
10265 
10266 template <typename T>
10267 static bool
10268 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10269                        function_ref<unsigned(T *)> Limit,
10270                        function_ref<bool(T *, T *)> Comparator,
10271                        function_ref<bool(T *, T *)> AreCompatible,
10272                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10273                        bool LimitForRegisterSize) {
10274   bool Changed = false;
10275   // Sort by type, parent, operands.
10276   stable_sort(Incoming, Comparator);
10277 
10278   // Try to vectorize elements base on their type.
10279   SmallVector<T *> Candidates;
10280   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10281     // Look for the next elements with the same type, parent and operand
10282     // kinds.
10283     auto *SameTypeIt = IncIt;
10284     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10285       ++SameTypeIt;
10286 
10287     // Try to vectorize them.
10288     unsigned NumElts = (SameTypeIt - IncIt);
10289     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10290                       << NumElts << ")\n");
10291     // The vectorization is a 3-state attempt:
10292     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10293     // size of maximal register at first.
10294     // 2. Try to vectorize remaining instructions with the same type, if
10295     // possible. This may result in the better vectorization results rather than
10296     // if we try just to vectorize instructions with the same/alternate opcodes.
10297     // 3. Final attempt to try to vectorize all instructions with the
10298     // same/alternate ops only, this may result in some extra final
10299     // vectorization.
10300     if (NumElts > 1 &&
10301         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10302       // Success start over because instructions might have been changed.
10303       Changed = true;
10304     } else if (NumElts < Limit(*IncIt) &&
10305                (Candidates.empty() ||
10306                 Candidates.front()->getType() == (*IncIt)->getType())) {
10307       Candidates.append(IncIt, std::next(IncIt, NumElts));
10308     }
10309     // Final attempt to vectorize instructions with the same types.
10310     if (Candidates.size() > 1 &&
10311         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10312       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10313         // Success start over because instructions might have been changed.
10314         Changed = true;
10315       } else if (LimitForRegisterSize) {
10316         // Try to vectorize using small vectors.
10317         for (auto *It = Candidates.begin(), *End = Candidates.end();
10318              It != End;) {
10319           auto *SameTypeIt = It;
10320           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10321             ++SameTypeIt;
10322           unsigned NumElts = (SameTypeIt - It);
10323           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10324                                             /*LimitForRegisterSize=*/false))
10325             Changed = true;
10326           It = SameTypeIt;
10327         }
10328       }
10329       Candidates.clear();
10330     }
10331 
10332     // Start over at the next instruction of a different type (or the end).
10333     IncIt = SameTypeIt;
10334   }
10335   return Changed;
10336 }
10337 
10338 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10339 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10340 /// operands. If IsCompatibility is false, function implements strict weak
10341 /// ordering relation between two cmp instructions, returning true if the first
10342 /// instruction is "less" than the second, i.e. its predicate is less than the
10343 /// predicate of the second or the operands IDs are less than the operands IDs
10344 /// of the second cmp instruction.
10345 template <bool IsCompatibility>
10346 static bool compareCmp(Value *V, Value *V2,
10347                        function_ref<bool(Instruction *)> IsDeleted) {
10348   auto *CI1 = cast<CmpInst>(V);
10349   auto *CI2 = cast<CmpInst>(V2);
10350   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10351     return false;
10352   if (CI1->getOperand(0)->getType()->getTypeID() <
10353       CI2->getOperand(0)->getType()->getTypeID())
10354     return !IsCompatibility;
10355   if (CI1->getOperand(0)->getType()->getTypeID() >
10356       CI2->getOperand(0)->getType()->getTypeID())
10357     return false;
10358   CmpInst::Predicate Pred1 = CI1->getPredicate();
10359   CmpInst::Predicate Pred2 = CI2->getPredicate();
10360   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10361   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10362   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10363   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10364   if (BasePred1 < BasePred2)
10365     return !IsCompatibility;
10366   if (BasePred1 > BasePred2)
10367     return false;
10368   // Compare operands.
10369   bool LEPreds = Pred1 <= Pred2;
10370   bool GEPreds = Pred1 >= Pred2;
10371   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10372     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10373     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10374     if (Op1->getValueID() < Op2->getValueID())
10375       return !IsCompatibility;
10376     if (Op1->getValueID() > Op2->getValueID())
10377       return false;
10378     if (auto *I1 = dyn_cast<Instruction>(Op1))
10379       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10380         if (I1->getParent() != I2->getParent())
10381           return false;
10382         InstructionsState S = getSameOpcode({I1, I2});
10383         if (S.getOpcode())
10384           continue;
10385         return false;
10386       }
10387   }
10388   return IsCompatibility;
10389 }
10390 
10391 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10392     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10393     bool AtTerminator) {
10394   bool OpsChanged = false;
10395   SmallVector<Instruction *, 4> PostponedCmps;
10396   for (auto *I : reverse(Instructions)) {
10397     if (R.isDeleted(I))
10398       continue;
10399     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10400       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10401     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10402       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10403     else if (isa<CmpInst>(I))
10404       PostponedCmps.push_back(I);
10405   }
10406   if (AtTerminator) {
10407     // Try to find reductions first.
10408     for (Instruction *I : PostponedCmps) {
10409       if (R.isDeleted(I))
10410         continue;
10411       for (Value *Op : I->operands())
10412         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10413     }
10414     // Try to vectorize operands as vector bundles.
10415     for (Instruction *I : PostponedCmps) {
10416       if (R.isDeleted(I))
10417         continue;
10418       OpsChanged |= tryToVectorize(I, R);
10419     }
10420     // Try to vectorize list of compares.
10421     // Sort by type, compare predicate, etc.
10422     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10423       return compareCmp<false>(V, V2,
10424                                [&R](Instruction *I) { return R.isDeleted(I); });
10425     };
10426 
10427     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10428       if (V1 == V2)
10429         return true;
10430       return compareCmp<true>(V1, V2,
10431                               [&R](Instruction *I) { return R.isDeleted(I); });
10432     };
10433     auto Limit = [&R](Value *V) {
10434       unsigned EltSize = R.getVectorElementSize(V);
10435       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10436     };
10437 
10438     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10439     OpsChanged |= tryToVectorizeSequence<Value>(
10440         Vals, Limit, CompareSorter, AreCompatibleCompares,
10441         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10442           // Exclude possible reductions from other blocks.
10443           bool ArePossiblyReducedInOtherBlock =
10444               any_of(Candidates, [](Value *V) {
10445                 return any_of(V->users(), [V](User *U) {
10446                   return isa<SelectInst>(U) &&
10447                          cast<SelectInst>(U)->getParent() !=
10448                              cast<Instruction>(V)->getParent();
10449                 });
10450               });
10451           if (ArePossiblyReducedInOtherBlock)
10452             return false;
10453           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10454         },
10455         /*LimitForRegisterSize=*/true);
10456     Instructions.clear();
10457   } else {
10458     // Insert in reverse order since the PostponedCmps vector was filled in
10459     // reverse order.
10460     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10461   }
10462   return OpsChanged;
10463 }
10464 
10465 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10466   bool Changed = false;
10467   SmallVector<Value *, 4> Incoming;
10468   SmallPtrSet<Value *, 16> VisitedInstrs;
10469   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10470   // node. Allows better to identify the chains that can be vectorized in the
10471   // better way.
10472   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10473   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10474     assert(isValidElementType(V1->getType()) &&
10475            isValidElementType(V2->getType()) &&
10476            "Expected vectorizable types only.");
10477     // It is fine to compare type IDs here, since we expect only vectorizable
10478     // types, like ints, floats and pointers, we don't care about other type.
10479     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10480       return true;
10481     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10482       return false;
10483     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10484     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10485     if (Opcodes1.size() < Opcodes2.size())
10486       return true;
10487     if (Opcodes1.size() > Opcodes2.size())
10488       return false;
10489     Optional<bool> ConstOrder;
10490     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10491       // Undefs are compatible with any other value.
10492       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10493         if (!ConstOrder)
10494           ConstOrder =
10495               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10496         continue;
10497       }
10498       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10499         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10500           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10501           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10502           if (!NodeI1)
10503             return NodeI2 != nullptr;
10504           if (!NodeI2)
10505             return false;
10506           assert((NodeI1 == NodeI2) ==
10507                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10508                  "Different nodes should have different DFS numbers");
10509           if (NodeI1 != NodeI2)
10510             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10511           InstructionsState S = getSameOpcode({I1, I2});
10512           if (S.getOpcode())
10513             continue;
10514           return I1->getOpcode() < I2->getOpcode();
10515         }
10516       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10517         if (!ConstOrder)
10518           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10519         continue;
10520       }
10521       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10522         return true;
10523       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10524         return false;
10525     }
10526     return ConstOrder && *ConstOrder;
10527   };
10528   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10529     if (V1 == V2)
10530       return true;
10531     if (V1->getType() != V2->getType())
10532       return false;
10533     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10534     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10535     if (Opcodes1.size() != Opcodes2.size())
10536       return false;
10537     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10538       // Undefs are compatible with any other value.
10539       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10540         continue;
10541       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10542         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10543           if (I1->getParent() != I2->getParent())
10544             return false;
10545           InstructionsState S = getSameOpcode({I1, I2});
10546           if (S.getOpcode())
10547             continue;
10548           return false;
10549         }
10550       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10551         continue;
10552       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10553         return false;
10554     }
10555     return true;
10556   };
10557   auto Limit = [&R](Value *V) {
10558     unsigned EltSize = R.getVectorElementSize(V);
10559     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10560   };
10561 
10562   bool HaveVectorizedPhiNodes = false;
10563   do {
10564     // Collect the incoming values from the PHIs.
10565     Incoming.clear();
10566     for (Instruction &I : *BB) {
10567       PHINode *P = dyn_cast<PHINode>(&I);
10568       if (!P)
10569         break;
10570 
10571       // No need to analyze deleted, vectorized and non-vectorizable
10572       // instructions.
10573       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10574           isValidElementType(P->getType()))
10575         Incoming.push_back(P);
10576     }
10577 
10578     // Find the corresponding non-phi nodes for better matching when trying to
10579     // build the tree.
10580     for (Value *V : Incoming) {
10581       SmallVectorImpl<Value *> &Opcodes =
10582           PHIToOpcodes.try_emplace(V).first->getSecond();
10583       if (!Opcodes.empty())
10584         continue;
10585       SmallVector<Value *, 4> Nodes(1, V);
10586       SmallPtrSet<Value *, 4> Visited;
10587       while (!Nodes.empty()) {
10588         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10589         if (!Visited.insert(PHI).second)
10590           continue;
10591         for (Value *V : PHI->incoming_values()) {
10592           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10593             Nodes.push_back(PHI1);
10594             continue;
10595           }
10596           Opcodes.emplace_back(V);
10597         }
10598       }
10599     }
10600 
10601     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10602         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10603         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10604           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10605         },
10606         /*LimitForRegisterSize=*/true);
10607     Changed |= HaveVectorizedPhiNodes;
10608     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10609   } while (HaveVectorizedPhiNodes);
10610 
10611   VisitedInstrs.clear();
10612 
10613   SmallVector<Instruction *, 8> PostProcessInstructions;
10614   SmallDenseSet<Instruction *, 4> KeyNodes;
10615   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10616     // Skip instructions with scalable type. The num of elements is unknown at
10617     // compile-time for scalable type.
10618     if (isa<ScalableVectorType>(it->getType()))
10619       continue;
10620 
10621     // Skip instructions marked for the deletion.
10622     if (R.isDeleted(&*it))
10623       continue;
10624     // We may go through BB multiple times so skip the one we have checked.
10625     if (!VisitedInstrs.insert(&*it).second) {
10626       if (it->use_empty() && KeyNodes.contains(&*it) &&
10627           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10628                                       it->isTerminator())) {
10629         // We would like to start over since some instructions are deleted
10630         // and the iterator may become invalid value.
10631         Changed = true;
10632         it = BB->begin();
10633         e = BB->end();
10634       }
10635       continue;
10636     }
10637 
10638     if (isa<DbgInfoIntrinsic>(it))
10639       continue;
10640 
10641     // Try to vectorize reductions that use PHINodes.
10642     if (PHINode *P = dyn_cast<PHINode>(it)) {
10643       // Check that the PHI is a reduction PHI.
10644       if (P->getNumIncomingValues() == 2) {
10645         // Try to match and vectorize a horizontal reduction.
10646         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10647                                      TTI)) {
10648           Changed = true;
10649           it = BB->begin();
10650           e = BB->end();
10651           continue;
10652         }
10653       }
10654       // Try to vectorize the incoming values of the PHI, to catch reductions
10655       // that feed into PHIs.
10656       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10657         // Skip if the incoming block is the current BB for now. Also, bypass
10658         // unreachable IR for efficiency and to avoid crashing.
10659         // TODO: Collect the skipped incoming values and try to vectorize them
10660         // after processing BB.
10661         if (BB == P->getIncomingBlock(I) ||
10662             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10663           continue;
10664 
10665         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10666                                             P->getIncomingBlock(I), R, TTI);
10667       }
10668       continue;
10669     }
10670 
10671     // Ran into an instruction without users, like terminator, or function call
10672     // with ignored return value, store. Ignore unused instructions (basing on
10673     // instruction type, except for CallInst and InvokeInst).
10674     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10675                             isa<InvokeInst>(it))) {
10676       KeyNodes.insert(&*it);
10677       bool OpsChanged = false;
10678       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10679         for (auto *V : it->operand_values()) {
10680           // Try to match and vectorize a horizontal reduction.
10681           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10682         }
10683       }
10684       // Start vectorization of post-process list of instructions from the
10685       // top-tree instructions to try to vectorize as many instructions as
10686       // possible.
10687       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10688                                                 it->isTerminator());
10689       if (OpsChanged) {
10690         // We would like to start over since some instructions are deleted
10691         // and the iterator may become invalid value.
10692         Changed = true;
10693         it = BB->begin();
10694         e = BB->end();
10695         continue;
10696       }
10697     }
10698 
10699     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10700         isa<InsertValueInst>(it))
10701       PostProcessInstructions.push_back(&*it);
10702   }
10703 
10704   return Changed;
10705 }
10706 
10707 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10708   auto Changed = false;
10709   for (auto &Entry : GEPs) {
10710     // If the getelementptr list has fewer than two elements, there's nothing
10711     // to do.
10712     if (Entry.second.size() < 2)
10713       continue;
10714 
10715     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10716                       << Entry.second.size() << ".\n");
10717 
10718     // Process the GEP list in chunks suitable for the target's supported
10719     // vector size. If a vector register can't hold 1 element, we are done. We
10720     // are trying to vectorize the index computations, so the maximum number of
10721     // elements is based on the size of the index expression, rather than the
10722     // size of the GEP itself (the target's pointer size).
10723     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10724     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10725     if (MaxVecRegSize < EltSize)
10726       continue;
10727 
10728     unsigned MaxElts = MaxVecRegSize / EltSize;
10729     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10730       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10731       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10732 
10733       // Initialize a set a candidate getelementptrs. Note that we use a
10734       // SetVector here to preserve program order. If the index computations
10735       // are vectorizable and begin with loads, we want to minimize the chance
10736       // of having to reorder them later.
10737       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10738 
10739       // Some of the candidates may have already been vectorized after we
10740       // initially collected them. If so, they are marked as deleted, so remove
10741       // them from the set of candidates.
10742       Candidates.remove_if(
10743           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10744 
10745       // Remove from the set of candidates all pairs of getelementptrs with
10746       // constant differences. Such getelementptrs are likely not good
10747       // candidates for vectorization in a bottom-up phase since one can be
10748       // computed from the other. We also ensure all candidate getelementptr
10749       // indices are unique.
10750       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10751         auto *GEPI = GEPList[I];
10752         if (!Candidates.count(GEPI))
10753           continue;
10754         auto *SCEVI = SE->getSCEV(GEPList[I]);
10755         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10756           auto *GEPJ = GEPList[J];
10757           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10758           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10759             Candidates.remove(GEPI);
10760             Candidates.remove(GEPJ);
10761           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10762             Candidates.remove(GEPJ);
10763           }
10764         }
10765       }
10766 
10767       // We break out of the above computation as soon as we know there are
10768       // fewer than two candidates remaining.
10769       if (Candidates.size() < 2)
10770         continue;
10771 
10772       // Add the single, non-constant index of each candidate to the bundle. We
10773       // ensured the indices met these constraints when we originally collected
10774       // the getelementptrs.
10775       SmallVector<Value *, 16> Bundle(Candidates.size());
10776       auto BundleIndex = 0u;
10777       for (auto *V : Candidates) {
10778         auto *GEP = cast<GetElementPtrInst>(V);
10779         auto *GEPIdx = GEP->idx_begin()->get();
10780         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10781         Bundle[BundleIndex++] = GEPIdx;
10782       }
10783 
10784       // Try and vectorize the indices. We are currently only interested in
10785       // gather-like cases of the form:
10786       //
10787       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10788       //
10789       // where the loads of "a", the loads of "b", and the subtractions can be
10790       // performed in parallel. It's likely that detecting this pattern in a
10791       // bottom-up phase will be simpler and less costly than building a
10792       // full-blown top-down phase beginning at the consecutive loads.
10793       Changed |= tryToVectorizeList(Bundle, R);
10794     }
10795   }
10796   return Changed;
10797 }
10798 
10799 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10800   bool Changed = false;
10801   // Sort by type, base pointers and values operand. Value operands must be
10802   // compatible (have the same opcode, same parent), otherwise it is
10803   // definitely not profitable to try to vectorize them.
10804   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10805     if (V->getPointerOperandType()->getTypeID() <
10806         V2->getPointerOperandType()->getTypeID())
10807       return true;
10808     if (V->getPointerOperandType()->getTypeID() >
10809         V2->getPointerOperandType()->getTypeID())
10810       return false;
10811     // UndefValues are compatible with all other values.
10812     if (isa<UndefValue>(V->getValueOperand()) ||
10813         isa<UndefValue>(V2->getValueOperand()))
10814       return false;
10815     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10816       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10817         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10818             DT->getNode(I1->getParent());
10819         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10820             DT->getNode(I2->getParent());
10821         assert(NodeI1 && "Should only process reachable instructions");
10822         assert(NodeI1 && "Should only process reachable instructions");
10823         assert((NodeI1 == NodeI2) ==
10824                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10825                "Different nodes should have different DFS numbers");
10826         if (NodeI1 != NodeI2)
10827           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10828         InstructionsState S = getSameOpcode({I1, I2});
10829         if (S.getOpcode())
10830           return false;
10831         return I1->getOpcode() < I2->getOpcode();
10832       }
10833     if (isa<Constant>(V->getValueOperand()) &&
10834         isa<Constant>(V2->getValueOperand()))
10835       return false;
10836     return V->getValueOperand()->getValueID() <
10837            V2->getValueOperand()->getValueID();
10838   };
10839 
10840   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10841     if (V1 == V2)
10842       return true;
10843     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10844       return false;
10845     // Undefs are compatible with any other value.
10846     if (isa<UndefValue>(V1->getValueOperand()) ||
10847         isa<UndefValue>(V2->getValueOperand()))
10848       return true;
10849     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10850       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10851         if (I1->getParent() != I2->getParent())
10852           return false;
10853         InstructionsState S = getSameOpcode({I1, I2});
10854         return S.getOpcode() > 0;
10855       }
10856     if (isa<Constant>(V1->getValueOperand()) &&
10857         isa<Constant>(V2->getValueOperand()))
10858       return true;
10859     return V1->getValueOperand()->getValueID() ==
10860            V2->getValueOperand()->getValueID();
10861   };
10862   auto Limit = [&R, this](StoreInst *SI) {
10863     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10864     return R.getMinVF(EltSize);
10865   };
10866 
10867   // Attempt to sort and vectorize each of the store-groups.
10868   for (auto &Pair : Stores) {
10869     if (Pair.second.size() < 2)
10870       continue;
10871 
10872     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10873                       << Pair.second.size() << ".\n");
10874 
10875     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10876       continue;
10877 
10878     Changed |= tryToVectorizeSequence<StoreInst>(
10879         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10880         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10881           return vectorizeStores(Candidates, R);
10882         },
10883         /*LimitForRegisterSize=*/false);
10884   }
10885   return Changed;
10886 }
10887 
10888 char SLPVectorizer::ID = 0;
10889 
10890 static const char lv_name[] = "SLP Vectorizer";
10891 
10892 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10893 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10894 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10895 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10896 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10897 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10898 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10899 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10900 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10901 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10902 
10903 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10904