1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper data structure to hold the operands of a vector of instructions.
1038   /// This supports a fixed vector length for all operand vectors.
1039   class VLOperands {
1040     /// For each operand we need (i) the value, and (ii) the opcode that it
1041     /// would be attached to if the expression was in a left-linearized form.
1042     /// This is required to avoid illegal operand reordering.
1043     /// For example:
1044     /// \verbatim
1045     ///                         0 Op1
1046     ///                         |/
1047     /// Op1 Op2   Linearized    + Op2
1048     ///   \ /     ---------->   |/
1049     ///    -                    -
1050     ///
1051     /// Op1 - Op2            (0 + Op1) - Op2
1052     /// \endverbatim
1053     ///
1054     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1055     ///
1056     /// Another way to think of this is to track all the operations across the
1057     /// path from the operand all the way to the root of the tree and to
1058     /// calculate the operation that corresponds to this path. For example, the
1059     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1060     /// corresponding operation is a '-' (which matches the one in the
1061     /// linearized tree, as shown above).
1062     ///
1063     /// For lack of a better term, we refer to this operation as Accumulated
1064     /// Path Operation (APO).
1065     struct OperandData {
1066       OperandData() = default;
1067       OperandData(Value *V, bool APO, bool IsUsed)
1068           : V(V), APO(APO), IsUsed(IsUsed) {}
1069       /// The operand value.
1070       Value *V = nullptr;
1071       /// TreeEntries only allow a single opcode, or an alternate sequence of
1072       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1073       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1074       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1075       /// (e.g., Add/Mul)
1076       bool APO = false;
1077       /// Helper data for the reordering function.
1078       bool IsUsed = false;
1079     };
1080 
1081     /// During operand reordering, we are trying to select the operand at lane
1082     /// that matches best with the operand at the neighboring lane. Our
1083     /// selection is based on the type of value we are looking for. For example,
1084     /// if the neighboring lane has a load, we need to look for a load that is
1085     /// accessing a consecutive address. These strategies are summarized in the
1086     /// 'ReorderingMode' enumerator.
1087     enum class ReorderingMode {
1088       Load,     ///< Matching loads to consecutive memory addresses
1089       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1090       Constant, ///< Matching constants
1091       Splat,    ///< Matching the same instruction multiple times (broadcast)
1092       Failed,   ///< We failed to create a vectorizable group
1093     };
1094 
1095     using OperandDataVec = SmallVector<OperandData, 2>;
1096 
1097     /// A vector of operand vectors.
1098     SmallVector<OperandDataVec, 4> OpsVec;
1099 
1100     const DataLayout &DL;
1101     ScalarEvolution &SE;
1102     const BoUpSLP &R;
1103 
1104     /// \returns the operand data at \p OpIdx and \p Lane.
1105     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1106       return OpsVec[OpIdx][Lane];
1107     }
1108 
1109     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1110     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1111       return OpsVec[OpIdx][Lane];
1112     }
1113 
1114     /// Clears the used flag for all entries.
1115     void clearUsed() {
1116       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1117            OpIdx != NumOperands; ++OpIdx)
1118         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1119              ++Lane)
1120           OpsVec[OpIdx][Lane].IsUsed = false;
1121     }
1122 
1123     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1124     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1125       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1126     }
1127 
1128     // The hard-coded scores listed here are not very important, though it shall
1129     // be higher for better matches to improve the resulting cost. When
1130     // computing the scores of matching one sub-tree with another, we are
1131     // basically counting the number of values that are matching. So even if all
1132     // scores are set to 1, we would still get a decent matching result.
1133     // However, sometimes we have to break ties. For example we may have to
1134     // choose between matching loads vs matching opcodes. This is what these
1135     // scores are helping us with: they provide the order of preference. Also,
1136     // this is important if the scalar is externally used or used in another
1137     // tree entry node in the different lane.
1138 
1139     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1140     static const int ScoreConsecutiveLoads = 4;
1141     /// The same load multiple times. This should have a better score than
1142     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1143     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1144     /// a vector load and 1.0 for a broadcast.
1145     static const int ScoreSplatLoads = 3;
1146     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1147     static const int ScoreReversedLoads = 3;
1148     /// ExtractElementInst from same vector and consecutive indexes.
1149     static const int ScoreConsecutiveExtracts = 4;
1150     /// ExtractElementInst from same vector and reversed indices.
1151     static const int ScoreReversedExtracts = 3;
1152     /// Constants.
1153     static const int ScoreConstants = 2;
1154     /// Instructions with the same opcode.
1155     static const int ScoreSameOpcode = 2;
1156     /// Instructions with alt opcodes (e.g, add + sub).
1157     static const int ScoreAltOpcodes = 1;
1158     /// Identical instructions (a.k.a. splat or broadcast).
1159     static const int ScoreSplat = 1;
1160     /// Matching with an undef is preferable to failing.
1161     static const int ScoreUndef = 1;
1162     /// Score for failing to find a decent match.
1163     static const int ScoreFail = 0;
1164     /// Score if all users are vectorized.
1165     static const int ScoreAllUserVectorized = 1;
1166 
1167     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1168     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1169     /// MainAltOps.
1170     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1171                         const DataLayout &DL, ScalarEvolution &SE, int NumLanes,
1172                         ArrayRef<Value *> MainAltOps) {
1173       if (V1 == V2) {
1174         if (isa<LoadInst>(V1)) {
1175           // Retruns true if the users of V1 and V2 won't need to be extracted.
1176           auto AllUsersAreInternal = [NumLanes, U1, U2, this](Value *V1,
1177                                                               Value *V2) {
1178             // Bail out if we have too many uses to save compilation time.
1179             static constexpr unsigned Limit = 8;
1180             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1181               return false;
1182 
1183             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1184               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1185                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1186               });
1187             };
1188             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1189           };
1190           // A broadcast of a load can be cheaper on some targets.
1191           if (R.TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1192               ((int)V1->getNumUses() == NumLanes ||
1193                AllUsersAreInternal(V1, V2)))
1194             return VLOperands::ScoreSplatLoads;
1195         }
1196         return VLOperands::ScoreSplat;
1197       }
1198 
1199       auto *LI1 = dyn_cast<LoadInst>(V1);
1200       auto *LI2 = dyn_cast<LoadInst>(V2);
1201       if (LI1 && LI2) {
1202         if (LI1->getParent() != LI2->getParent())
1203           return VLOperands::ScoreFail;
1204 
1205         Optional<int> Dist = getPointersDiff(
1206             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1207             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1208         if (!Dist || *Dist == 0)
1209           return VLOperands::ScoreFail;
1210         // The distance is too large - still may be profitable to use masked
1211         // loads/gathers.
1212         if (std::abs(*Dist) > NumLanes / 2)
1213           return VLOperands::ScoreAltOpcodes;
1214         // This still will detect consecutive loads, but we might have "holes"
1215         // in some cases. It is ok for non-power-2 vectorization and may produce
1216         // better results. It should not affect current vectorization.
1217         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1218                            : VLOperands::ScoreReversedLoads;
1219       }
1220 
1221       auto *C1 = dyn_cast<Constant>(V1);
1222       auto *C2 = dyn_cast<Constant>(V2);
1223       if (C1 && C2)
1224         return VLOperands::ScoreConstants;
1225 
1226       // Extracts from consecutive indexes of the same vector better score as
1227       // the extracts could be optimized away.
1228       Value *EV1;
1229       ConstantInt *Ex1Idx;
1230       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1231         // Undefs are always profitable for extractelements.
1232         if (isa<UndefValue>(V2))
1233           return VLOperands::ScoreConsecutiveExtracts;
1234         Value *EV2 = nullptr;
1235         ConstantInt *Ex2Idx = nullptr;
1236         if (match(V2,
1237                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1238                                                          m_Undef())))) {
1239           // Undefs are always profitable for extractelements.
1240           if (!Ex2Idx)
1241             return VLOperands::ScoreConsecutiveExtracts;
1242           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1243             return VLOperands::ScoreConsecutiveExtracts;
1244           if (EV2 == EV1) {
1245             int Idx1 = Ex1Idx->getZExtValue();
1246             int Idx2 = Ex2Idx->getZExtValue();
1247             int Dist = Idx2 - Idx1;
1248             // The distance is too large - still may be profitable to use
1249             // shuffles.
1250             if (std::abs(Dist) == 0)
1251               return VLOperands::ScoreSplat;
1252             if (std::abs(Dist) > NumLanes / 2)
1253               return VLOperands::ScoreSameOpcode;
1254             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1255                               : VLOperands::ScoreReversedExtracts;
1256           }
1257           return VLOperands::ScoreAltOpcodes;
1258         }
1259         return VLOperands::ScoreFail;
1260       }
1261 
1262       auto *I1 = dyn_cast<Instruction>(V1);
1263       auto *I2 = dyn_cast<Instruction>(V2);
1264       if (I1 && I2) {
1265         if (I1->getParent() != I2->getParent())
1266           return VLOperands::ScoreFail;
1267         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1268         Ops.push_back(I1);
1269         Ops.push_back(I2);
1270         InstructionsState S = getSameOpcode(Ops);
1271         // Note: Only consider instructions with <= 2 operands to avoid
1272         // complexity explosion.
1273         if (S.getOpcode() &&
1274             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1275              !S.isAltShuffle()) &&
1276             all_of(Ops, [&S](Value *V) {
1277               return cast<Instruction>(V)->getNumOperands() ==
1278                      S.MainOp->getNumOperands();
1279             }))
1280           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1281                                   : VLOperands::ScoreSameOpcode;
1282       }
1283 
1284       if (isa<UndefValue>(V2))
1285         return VLOperands::ScoreUndef;
1286 
1287       return VLOperands::ScoreFail;
1288     }
1289 
1290     /// \param Lane lane of the operands under analysis.
1291     /// \param OpIdx operand index in \p Lane lane we're looking the best
1292     /// candidate for.
1293     /// \param Idx operand index of the current candidate value.
1294     /// \returns The additional score due to possible broadcasting of the
1295     /// elements in the lane. It is more profitable to have power-of-2 unique
1296     /// elements in the lane, it will be vectorized with higher probability
1297     /// after removing duplicates. Currently the SLP vectorizer supports only
1298     /// vectorization of the power-of-2 number of unique scalars.
1299     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1300       Value *IdxLaneV = getData(Idx, Lane).V;
1301       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1302         return 0;
1303       SmallPtrSet<Value *, 4> Uniques;
1304       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1305         if (Ln == Lane)
1306           continue;
1307         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1308         if (!isa<Instruction>(OpIdxLnV))
1309           return 0;
1310         Uniques.insert(OpIdxLnV);
1311       }
1312       int UniquesCount = Uniques.size();
1313       int UniquesCntWithIdxLaneV =
1314           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1315       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1316       int UniquesCntWithOpIdxLaneV =
1317           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1318       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1319         return 0;
1320       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1321               UniquesCntWithOpIdxLaneV) -
1322              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1323     }
1324 
1325     /// \param Lane lane of the operands under analysis.
1326     /// \param OpIdx operand index in \p Lane lane we're looking the best
1327     /// candidate for.
1328     /// \param Idx operand index of the current candidate value.
1329     /// \returns The additional score for the scalar which users are all
1330     /// vectorized.
1331     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1332       Value *IdxLaneV = getData(Idx, Lane).V;
1333       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1334       // Do not care about number of uses for vector-like instructions
1335       // (extractelement/extractvalue with constant indices), they are extracts
1336       // themselves and already externally used. Vectorization of such
1337       // instructions does not add extra extractelement instruction, just may
1338       // remove it.
1339       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1340           isVectorLikeInstWithConstOps(OpIdxLaneV))
1341         return VLOperands::ScoreAllUserVectorized;
1342       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1343       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1344         return 0;
1345       return R.areAllUsersVectorized(IdxLaneI, None)
1346                  ? VLOperands::ScoreAllUserVectorized
1347                  : 0;
1348     }
1349 
1350     /// Go through the operands of \p LHS and \p RHS recursively until \p
1351     /// MaxLevel, and return the cummulative score. For example:
1352     /// \verbatim
1353     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1354     ///     \ /         \ /         \ /        \ /
1355     ///      +           +           +          +
1356     ///     G1          G2          G3         G4
1357     /// \endverbatim
1358     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1359     /// each level recursively, accumulating the score. It starts from matching
1360     /// the additions at level 0, then moves on to the loads (level 1). The
1361     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1362     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1363     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1364     /// Please note that the order of the operands does not matter, as we
1365     /// evaluate the score of all profitable combinations of operands. In
1366     /// other words the score of G1 and G4 is the same as G1 and G2. This
1367     /// heuristic is based on ideas described in:
1368     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1369     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1370     ///   Luís F. W. Góes
1371     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1372                            Instruction *U2, int CurrLevel, int MaxLevel,
1373                            ArrayRef<Value *> MainAltOps) {
1374 
1375       // Get the shallow score of V1 and V2.
1376       int ShallowScoreAtThisLevel =
1377           getShallowScore(LHS, RHS, U1, U2, DL, SE, getNumLanes(), MainAltOps);
1378 
1379       // If reached MaxLevel,
1380       //  or if V1 and V2 are not instructions,
1381       //  or if they are SPLAT,
1382       //  or if they are not consecutive,
1383       //  or if profitable to vectorize loads or extractelements, early return
1384       //  the current cost.
1385       auto *I1 = dyn_cast<Instruction>(LHS);
1386       auto *I2 = dyn_cast<Instruction>(RHS);
1387       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1388           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1389           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1390             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1391             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1392            ShallowScoreAtThisLevel))
1393         return ShallowScoreAtThisLevel;
1394       assert(I1 && I2 && "Should have early exited.");
1395 
1396       // Contains the I2 operand indexes that got matched with I1 operands.
1397       SmallSet<unsigned, 4> Op2Used;
1398 
1399       // Recursion towards the operands of I1 and I2. We are trying all possible
1400       // operand pairs, and keeping track of the best score.
1401       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1402            OpIdx1 != NumOperands1; ++OpIdx1) {
1403         // Try to pair op1I with the best operand of I2.
1404         int MaxTmpScore = 0;
1405         unsigned MaxOpIdx2 = 0;
1406         bool FoundBest = false;
1407         // If I2 is commutative try all combinations.
1408         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1409         unsigned ToIdx = isCommutative(I2)
1410                              ? I2->getNumOperands()
1411                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1412         assert(FromIdx <= ToIdx && "Bad index");
1413         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1414           // Skip operands already paired with OpIdx1.
1415           if (Op2Used.count(OpIdx2))
1416             continue;
1417           // Recursively calculate the cost at each level
1418           int TmpScore =
1419               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1420                                  I1, I2, CurrLevel + 1, MaxLevel, None);
1421           // Look for the best score.
1422           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1423             MaxTmpScore = TmpScore;
1424             MaxOpIdx2 = OpIdx2;
1425             FoundBest = true;
1426           }
1427         }
1428         if (FoundBest) {
1429           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1430           Op2Used.insert(MaxOpIdx2);
1431           ShallowScoreAtThisLevel += MaxTmpScore;
1432         }
1433       }
1434       return ShallowScoreAtThisLevel;
1435     }
1436 
1437     /// Score scaling factor for fully compatible instructions but with
1438     /// different number of external uses. Allows better selection of the
1439     /// instructions with less external uses.
1440     static const int ScoreScaleFactor = 10;
1441 
1442     /// \Returns the look-ahead score, which tells us how much the sub-trees
1443     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1444     /// score. This helps break ties in an informed way when we cannot decide on
1445     /// the order of the operands by just considering the immediate
1446     /// predecessors.
1447     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1448                           int Lane, unsigned OpIdx, unsigned Idx,
1449                           bool &IsUsed) {
1450       // Keep track of the instruction stack as we recurse into the operands
1451       // during the look-ahead score exploration.
1452       int Score = getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1453                                      1, LookAheadMaxDepth, MainAltOps);
1454       if (Score) {
1455         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1456         if (Score <= -SplatScore) {
1457           // Set the minimum score for splat-like sequence to avoid setting
1458           // failed state.
1459           Score = 1;
1460         } else {
1461           Score += SplatScore;
1462           // Scale score to see the difference between different operands
1463           // and similar operands but all vectorized/not all vectorized
1464           // uses. It does not affect actual selection of the best
1465           // compatible operand in general, just allows to select the
1466           // operand with all vectorized uses.
1467           Score *= ScoreScaleFactor;
1468           Score += getExternalUseScore(Lane, OpIdx, Idx);
1469           IsUsed = true;
1470         }
1471       }
1472       return Score;
1473     }
1474 
1475     /// Best defined scores per lanes between the passes. Used to choose the
1476     /// best operand (with the highest score) between the passes.
1477     /// The key - {Operand Index, Lane}.
1478     /// The value - the best score between the passes for the lane and the
1479     /// operand.
1480     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1481         BestScoresPerLanes;
1482 
1483     // Search all operands in Ops[*][Lane] for the one that matches best
1484     // Ops[OpIdx][LastLane] and return its opreand index.
1485     // If no good match can be found, return None.
1486     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1487                                       ArrayRef<ReorderingMode> ReorderingModes,
1488                                       ArrayRef<Value *> MainAltOps) {
1489       unsigned NumOperands = getNumOperands();
1490 
1491       // The operand of the previous lane at OpIdx.
1492       Value *OpLastLane = getData(OpIdx, LastLane).V;
1493 
1494       // Our strategy mode for OpIdx.
1495       ReorderingMode RMode = ReorderingModes[OpIdx];
1496       if (RMode == ReorderingMode::Failed)
1497         return None;
1498 
1499       // The linearized opcode of the operand at OpIdx, Lane.
1500       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1501 
1502       // The best operand index and its score.
1503       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1504       // are using the score to differentiate between the two.
1505       struct BestOpData {
1506         Optional<unsigned> Idx = None;
1507         unsigned Score = 0;
1508       } BestOp;
1509       BestOp.Score =
1510           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1511               .first->second;
1512 
1513       // Track if the operand must be marked as used. If the operand is set to
1514       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1515       // want to reestimate the operands again on the following iterations).
1516       bool IsUsed =
1517           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1518       // Iterate through all unused operands and look for the best.
1519       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1520         // Get the operand at Idx and Lane.
1521         OperandData &OpData = getData(Idx, Lane);
1522         Value *Op = OpData.V;
1523         bool OpAPO = OpData.APO;
1524 
1525         // Skip already selected operands.
1526         if (OpData.IsUsed)
1527           continue;
1528 
1529         // Skip if we are trying to move the operand to a position with a
1530         // different opcode in the linearized tree form. This would break the
1531         // semantics.
1532         if (OpAPO != OpIdxAPO)
1533           continue;
1534 
1535         // Look for an operand that matches the current mode.
1536         switch (RMode) {
1537         case ReorderingMode::Load:
1538         case ReorderingMode::Constant:
1539         case ReorderingMode::Opcode: {
1540           bool LeftToRight = Lane > LastLane;
1541           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1542           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1543           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1544                                         OpIdx, Idx, IsUsed);
1545           if (Score > static_cast<int>(BestOp.Score)) {
1546             BestOp.Idx = Idx;
1547             BestOp.Score = Score;
1548             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1549           }
1550           break;
1551         }
1552         case ReorderingMode::Splat:
1553           if (Op == OpLastLane)
1554             BestOp.Idx = Idx;
1555           break;
1556         case ReorderingMode::Failed:
1557           llvm_unreachable("Not expected Failed reordering mode.");
1558         }
1559       }
1560 
1561       if (BestOp.Idx) {
1562         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1563         return BestOp.Idx;
1564       }
1565       // If we could not find a good match return None.
1566       return None;
1567     }
1568 
1569     /// Helper for reorderOperandVecs.
1570     /// \returns the lane that we should start reordering from. This is the one
1571     /// which has the least number of operands that can freely move about or
1572     /// less profitable because it already has the most optimal set of operands.
1573     unsigned getBestLaneToStartReordering() const {
1574       unsigned Min = UINT_MAX;
1575       unsigned SameOpNumber = 0;
1576       // std::pair<unsigned, unsigned> is used to implement a simple voting
1577       // algorithm and choose the lane with the least number of operands that
1578       // can freely move about or less profitable because it already has the
1579       // most optimal set of operands. The first unsigned is a counter for
1580       // voting, the second unsigned is the counter of lanes with instructions
1581       // with same/alternate opcodes and same parent basic block.
1582       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1583       // Try to be closer to the original results, if we have multiple lanes
1584       // with same cost. If 2 lanes have the same cost, use the one with the
1585       // lowest index.
1586       for (int I = getNumLanes(); I > 0; --I) {
1587         unsigned Lane = I - 1;
1588         OperandsOrderData NumFreeOpsHash =
1589             getMaxNumOperandsThatCanBeReordered(Lane);
1590         // Compare the number of operands that can move and choose the one with
1591         // the least number.
1592         if (NumFreeOpsHash.NumOfAPOs < Min) {
1593           Min = NumFreeOpsHash.NumOfAPOs;
1594           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1595           HashMap.clear();
1596           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1597         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1598                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1599           // Select the most optimal lane in terms of number of operands that
1600           // should be moved around.
1601           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1602           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1603         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1604                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1605           auto It = HashMap.find(NumFreeOpsHash.Hash);
1606           if (It == HashMap.end())
1607             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1608           else
1609             ++It->second.first;
1610         }
1611       }
1612       // Select the lane with the minimum counter.
1613       unsigned BestLane = 0;
1614       unsigned CntMin = UINT_MAX;
1615       for (const auto &Data : reverse(HashMap)) {
1616         if (Data.second.first < CntMin) {
1617           CntMin = Data.second.first;
1618           BestLane = Data.second.second;
1619         }
1620       }
1621       return BestLane;
1622     }
1623 
1624     /// Data structure that helps to reorder operands.
1625     struct OperandsOrderData {
1626       /// The best number of operands with the same APOs, which can be
1627       /// reordered.
1628       unsigned NumOfAPOs = UINT_MAX;
1629       /// Number of operands with the same/alternate instruction opcode and
1630       /// parent.
1631       unsigned NumOpsWithSameOpcodeParent = 0;
1632       /// Hash for the actual operands ordering.
1633       /// Used to count operands, actually their position id and opcode
1634       /// value. It is used in the voting mechanism to find the lane with the
1635       /// least number of operands that can freely move about or less profitable
1636       /// because it already has the most optimal set of operands. Can be
1637       /// replaced with SmallVector<unsigned> instead but hash code is faster
1638       /// and requires less memory.
1639       unsigned Hash = 0;
1640     };
1641     /// \returns the maximum number of operands that are allowed to be reordered
1642     /// for \p Lane and the number of compatible instructions(with the same
1643     /// parent/opcode). This is used as a heuristic for selecting the first lane
1644     /// to start operand reordering.
1645     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1646       unsigned CntTrue = 0;
1647       unsigned NumOperands = getNumOperands();
1648       // Operands with the same APO can be reordered. We therefore need to count
1649       // how many of them we have for each APO, like this: Cnt[APO] = x.
1650       // Since we only have two APOs, namely true and false, we can avoid using
1651       // a map. Instead we can simply count the number of operands that
1652       // correspond to one of them (in this case the 'true' APO), and calculate
1653       // the other by subtracting it from the total number of operands.
1654       // Operands with the same instruction opcode and parent are more
1655       // profitable since we don't need to move them in many cases, with a high
1656       // probability such lane already can be vectorized effectively.
1657       bool AllUndefs = true;
1658       unsigned NumOpsWithSameOpcodeParent = 0;
1659       Instruction *OpcodeI = nullptr;
1660       BasicBlock *Parent = nullptr;
1661       unsigned Hash = 0;
1662       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1663         const OperandData &OpData = getData(OpIdx, Lane);
1664         if (OpData.APO)
1665           ++CntTrue;
1666         // Use Boyer-Moore majority voting for finding the majority opcode and
1667         // the number of times it occurs.
1668         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1669           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1670               I->getParent() != Parent) {
1671             if (NumOpsWithSameOpcodeParent == 0) {
1672               NumOpsWithSameOpcodeParent = 1;
1673               OpcodeI = I;
1674               Parent = I->getParent();
1675             } else {
1676               --NumOpsWithSameOpcodeParent;
1677             }
1678           } else {
1679             ++NumOpsWithSameOpcodeParent;
1680           }
1681         }
1682         Hash = hash_combine(
1683             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1684         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1685       }
1686       if (AllUndefs)
1687         return {};
1688       OperandsOrderData Data;
1689       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1690       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1691       Data.Hash = Hash;
1692       return Data;
1693     }
1694 
1695     /// Go through the instructions in VL and append their operands.
1696     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1697       assert(!VL.empty() && "Bad VL");
1698       assert((empty() || VL.size() == getNumLanes()) &&
1699              "Expected same number of lanes");
1700       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1701       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1702       OpsVec.resize(NumOperands);
1703       unsigned NumLanes = VL.size();
1704       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1705         OpsVec[OpIdx].resize(NumLanes);
1706         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1707           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1708           // Our tree has just 3 nodes: the root and two operands.
1709           // It is therefore trivial to get the APO. We only need to check the
1710           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1711           // RHS operand. The LHS operand of both add and sub is never attached
1712           // to an inversese operation in the linearized form, therefore its APO
1713           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1714 
1715           // Since operand reordering is performed on groups of commutative
1716           // operations or alternating sequences (e.g., +, -), we can safely
1717           // tell the inverse operations by checking commutativity.
1718           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1719           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1720           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1721                                  APO, false};
1722         }
1723       }
1724     }
1725 
1726     /// \returns the number of operands.
1727     unsigned getNumOperands() const { return OpsVec.size(); }
1728 
1729     /// \returns the number of lanes.
1730     unsigned getNumLanes() const { return OpsVec[0].size(); }
1731 
1732     /// \returns the operand value at \p OpIdx and \p Lane.
1733     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1734       return getData(OpIdx, Lane).V;
1735     }
1736 
1737     /// \returns true if the data structure is empty.
1738     bool empty() const { return OpsVec.empty(); }
1739 
1740     /// Clears the data.
1741     void clear() { OpsVec.clear(); }
1742 
1743     /// \Returns true if there are enough operands identical to \p Op to fill
1744     /// the whole vector.
1745     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1746     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1747       bool OpAPO = getData(OpIdx, Lane).APO;
1748       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1749         if (Ln == Lane)
1750           continue;
1751         // This is set to true if we found a candidate for broadcast at Lane.
1752         bool FoundCandidate = false;
1753         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1754           OperandData &Data = getData(OpI, Ln);
1755           if (Data.APO != OpAPO || Data.IsUsed)
1756             continue;
1757           if (Data.V == Op) {
1758             FoundCandidate = true;
1759             Data.IsUsed = true;
1760             break;
1761           }
1762         }
1763         if (!FoundCandidate)
1764           return false;
1765       }
1766       return true;
1767     }
1768 
1769   public:
1770     /// Initialize with all the operands of the instruction vector \p RootVL.
1771     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1772                ScalarEvolution &SE, const BoUpSLP &R)
1773         : DL(DL), SE(SE), R(R) {
1774       // Append all the operands of RootVL.
1775       appendOperandsOfVL(RootVL);
1776     }
1777 
1778     /// \Returns a value vector with the operands across all lanes for the
1779     /// opearnd at \p OpIdx.
1780     ValueList getVL(unsigned OpIdx) const {
1781       ValueList OpVL(OpsVec[OpIdx].size());
1782       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1783              "Expected same num of lanes across all operands");
1784       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1785         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1786       return OpVL;
1787     }
1788 
1789     // Performs operand reordering for 2 or more operands.
1790     // The original operands are in OrigOps[OpIdx][Lane].
1791     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1792     void reorder() {
1793       unsigned NumOperands = getNumOperands();
1794       unsigned NumLanes = getNumLanes();
1795       // Each operand has its own mode. We are using this mode to help us select
1796       // the instructions for each lane, so that they match best with the ones
1797       // we have selected so far.
1798       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1799 
1800       // This is a greedy single-pass algorithm. We are going over each lane
1801       // once and deciding on the best order right away with no back-tracking.
1802       // However, in order to increase its effectiveness, we start with the lane
1803       // that has operands that can move the least. For example, given the
1804       // following lanes:
1805       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1806       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1807       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1808       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1809       // we will start at Lane 1, since the operands of the subtraction cannot
1810       // be reordered. Then we will visit the rest of the lanes in a circular
1811       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1812 
1813       // Find the first lane that we will start our search from.
1814       unsigned FirstLane = getBestLaneToStartReordering();
1815 
1816       // Initialize the modes.
1817       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1818         Value *OpLane0 = getValue(OpIdx, FirstLane);
1819         // Keep track if we have instructions with all the same opcode on one
1820         // side.
1821         if (isa<LoadInst>(OpLane0))
1822           ReorderingModes[OpIdx] = ReorderingMode::Load;
1823         else if (isa<Instruction>(OpLane0)) {
1824           // Check if OpLane0 should be broadcast.
1825           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1826             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1827           else
1828             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1829         }
1830         else if (isa<Constant>(OpLane0))
1831           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1832         else if (isa<Argument>(OpLane0))
1833           // Our best hope is a Splat. It may save some cost in some cases.
1834           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1835         else
1836           // NOTE: This should be unreachable.
1837           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1838       }
1839 
1840       // Check that we don't have same operands. No need to reorder if operands
1841       // are just perfect diamond or shuffled diamond match. Do not do it only
1842       // for possible broadcasts or non-power of 2 number of scalars (just for
1843       // now).
1844       auto &&SkipReordering = [this]() {
1845         SmallPtrSet<Value *, 4> UniqueValues;
1846         ArrayRef<OperandData> Op0 = OpsVec.front();
1847         for (const OperandData &Data : Op0)
1848           UniqueValues.insert(Data.V);
1849         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1850           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1851                 return !UniqueValues.contains(Data.V);
1852               }))
1853             return false;
1854         }
1855         // TODO: Check if we can remove a check for non-power-2 number of
1856         // scalars after full support of non-power-2 vectorization.
1857         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1858       };
1859 
1860       // If the initial strategy fails for any of the operand indexes, then we
1861       // perform reordering again in a second pass. This helps avoid assigning
1862       // high priority to the failed strategy, and should improve reordering for
1863       // the non-failed operand indexes.
1864       for (int Pass = 0; Pass != 2; ++Pass) {
1865         // Check if no need to reorder operands since they're are perfect or
1866         // shuffled diamond match.
1867         // Need to to do it to avoid extra external use cost counting for
1868         // shuffled matches, which may cause regressions.
1869         if (SkipReordering())
1870           break;
1871         // Skip the second pass if the first pass did not fail.
1872         bool StrategyFailed = false;
1873         // Mark all operand data as free to use.
1874         clearUsed();
1875         // We keep the original operand order for the FirstLane, so reorder the
1876         // rest of the lanes. We are visiting the nodes in a circular fashion,
1877         // using FirstLane as the center point and increasing the radius
1878         // distance.
1879         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1880         for (unsigned I = 0; I < NumOperands; ++I)
1881           MainAltOps[I].push_back(getData(I, FirstLane).V);
1882 
1883         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1884           // Visit the lane on the right and then the lane on the left.
1885           for (int Direction : {+1, -1}) {
1886             int Lane = FirstLane + Direction * Distance;
1887             if (Lane < 0 || Lane >= (int)NumLanes)
1888               continue;
1889             int LastLane = Lane - Direction;
1890             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1891                    "Out of bounds");
1892             // Look for a good match for each operand.
1893             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1894               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1895               Optional<unsigned> BestIdx = getBestOperand(
1896                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1897               // By not selecting a value, we allow the operands that follow to
1898               // select a better matching value. We will get a non-null value in
1899               // the next run of getBestOperand().
1900               if (BestIdx) {
1901                 // Swap the current operand with the one returned by
1902                 // getBestOperand().
1903                 swap(OpIdx, BestIdx.getValue(), Lane);
1904               } else {
1905                 // We failed to find a best operand, set mode to 'Failed'.
1906                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1907                 // Enable the second pass.
1908                 StrategyFailed = true;
1909               }
1910               // Try to get the alternate opcode and follow it during analysis.
1911               if (MainAltOps[OpIdx].size() != 2) {
1912                 OperandData &AltOp = getData(OpIdx, Lane);
1913                 InstructionsState OpS =
1914                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1915                 if (OpS.getOpcode() && OpS.isAltShuffle())
1916                   MainAltOps[OpIdx].push_back(AltOp.V);
1917               }
1918             }
1919           }
1920         }
1921         // Skip second pass if the strategy did not fail.
1922         if (!StrategyFailed)
1923           break;
1924       }
1925     }
1926 
1927 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1928     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1929       switch (RMode) {
1930       case ReorderingMode::Load:
1931         return "Load";
1932       case ReorderingMode::Opcode:
1933         return "Opcode";
1934       case ReorderingMode::Constant:
1935         return "Constant";
1936       case ReorderingMode::Splat:
1937         return "Splat";
1938       case ReorderingMode::Failed:
1939         return "Failed";
1940       }
1941       llvm_unreachable("Unimplemented Reordering Type");
1942     }
1943 
1944     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1945                                                    raw_ostream &OS) {
1946       return OS << getModeStr(RMode);
1947     }
1948 
1949     /// Debug print.
1950     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1951       printMode(RMode, dbgs());
1952     }
1953 
1954     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1955       return printMode(RMode, OS);
1956     }
1957 
1958     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1959       const unsigned Indent = 2;
1960       unsigned Cnt = 0;
1961       for (const OperandDataVec &OpDataVec : OpsVec) {
1962         OS << "Operand " << Cnt++ << "\n";
1963         for (const OperandData &OpData : OpDataVec) {
1964           OS.indent(Indent) << "{";
1965           if (Value *V = OpData.V)
1966             OS << *V;
1967           else
1968             OS << "null";
1969           OS << ", APO:" << OpData.APO << "}\n";
1970         }
1971         OS << "\n";
1972       }
1973       return OS;
1974     }
1975 
1976     /// Debug print.
1977     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1978 #endif
1979   };
1980 
1981   /// Checks if the instruction is marked for deletion.
1982   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1983 
1984   /// Removes an instruction from its block and eventually deletes it.
1985   /// It's like Instruction::eraseFromParent() except that the actual deletion
1986   /// is delayed until BoUpSLP is destructed.
1987   void eraseInstruction(Instruction *I) {
1988     DeletedInstructions.insert(I);
1989   }
1990 
1991   ~BoUpSLP();
1992 
1993 private:
1994   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1995   /// reordering (i.e. the operands can be reordered because they have only one
1996   /// user and reordarable).
1997   /// \param ReorderableGathers List of all gather nodes that require reordering
1998   /// (e.g., gather of extractlements or partially vectorizable loads).
1999   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2000   /// reordering, subset of \p NonVectorized.
2001   bool
2002   canReorderOperands(TreeEntry *UserTE,
2003                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2004                      ArrayRef<TreeEntry *> ReorderableGathers,
2005                      SmallVectorImpl<TreeEntry *> &GatherOps);
2006 
2007   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2008   /// if any. If it is not vectorized (gather node), returns nullptr.
2009   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2010     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2011     TreeEntry *TE = nullptr;
2012     const auto *It = find_if(VL, [this, &TE](Value *V) {
2013       TE = getTreeEntry(V);
2014       return TE;
2015     });
2016     if (It != VL.end() && TE->isSame(VL))
2017       return TE;
2018     return nullptr;
2019   }
2020 
2021   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2022   /// if any. If it is not vectorized (gather node), returns nullptr.
2023   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2024                                         unsigned OpIdx) const {
2025     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2026         const_cast<TreeEntry *>(UserTE), OpIdx);
2027   }
2028 
2029   /// Checks if all users of \p I are the part of the vectorization tree.
2030   bool areAllUsersVectorized(Instruction *I,
2031                              ArrayRef<Value *> VectorizedVals) const;
2032 
2033   /// \returns the cost of the vectorizable entry.
2034   InstructionCost getEntryCost(const TreeEntry *E,
2035                                ArrayRef<Value *> VectorizedVals);
2036 
2037   /// This is the recursive part of buildTree.
2038   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2039                      const EdgeInfo &EI);
2040 
2041   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2042   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2043   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2044   /// returns false, setting \p CurrentOrder to either an empty vector or a
2045   /// non-identity permutation that allows to reuse extract instructions.
2046   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2047                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2048 
2049   /// Vectorize a single entry in the tree.
2050   Value *vectorizeTree(TreeEntry *E);
2051 
2052   /// Vectorize a single entry in the tree, starting in \p VL.
2053   Value *vectorizeTree(ArrayRef<Value *> VL);
2054 
2055   /// Create a new vector from a list of scalar values.  Produces a sequence
2056   /// which exploits values reused across lanes, and arranges the inserts
2057   /// for ease of later optimization.
2058   Value *createBuildVector(ArrayRef<Value *> VL);
2059 
2060   /// \returns the scalarization cost for this type. Scalarization in this
2061   /// context means the creation of vectors from a group of scalars. If \p
2062   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2063   /// vector elements.
2064   InstructionCost getGatherCost(FixedVectorType *Ty,
2065                                 const APInt &ShuffledIndices,
2066                                 bool NeedToShuffle) const;
2067 
2068   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2069   /// tree entries.
2070   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2071   /// previous tree entries. \p Mask is filled with the shuffle mask.
2072   Optional<TargetTransformInfo::ShuffleKind>
2073   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2074                         SmallVectorImpl<const TreeEntry *> &Entries);
2075 
2076   /// \returns the scalarization cost for this list of values. Assuming that
2077   /// this subtree gets vectorized, we may need to extract the values from the
2078   /// roots. This method calculates the cost of extracting the values.
2079   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2080 
2081   /// Set the Builder insert point to one after the last instruction in
2082   /// the bundle
2083   void setInsertPointAfterBundle(const TreeEntry *E);
2084 
2085   /// \returns a vector from a collection of scalars in \p VL.
2086   Value *gather(ArrayRef<Value *> VL);
2087 
2088   /// \returns whether the VectorizableTree is fully vectorizable and will
2089   /// be beneficial even the tree height is tiny.
2090   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2091 
2092   /// Reorder commutative or alt operands to get better probability of
2093   /// generating vectorized code.
2094   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2095                                              SmallVectorImpl<Value *> &Left,
2096                                              SmallVectorImpl<Value *> &Right,
2097                                              const DataLayout &DL,
2098                                              ScalarEvolution &SE,
2099                                              const BoUpSLP &R);
2100   struct TreeEntry {
2101     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2102     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2103 
2104     /// \returns true if the scalars in VL are equal to this entry.
2105     bool isSame(ArrayRef<Value *> VL) const {
2106       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2107         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2108           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2109         return VL.size() == Mask.size() &&
2110                std::equal(VL.begin(), VL.end(), Mask.begin(),
2111                           [Scalars](Value *V, int Idx) {
2112                             return (isa<UndefValue>(V) &&
2113                                     Idx == UndefMaskElem) ||
2114                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2115                           });
2116       };
2117       if (!ReorderIndices.empty()) {
2118         // TODO: implement matching if the nodes are just reordered, still can
2119         // treat the vector as the same if the list of scalars matches VL
2120         // directly, without reordering.
2121         SmallVector<int> Mask;
2122         inversePermutation(ReorderIndices, Mask);
2123         if (VL.size() == Scalars.size())
2124           return IsSame(Scalars, Mask);
2125         if (VL.size() == ReuseShuffleIndices.size()) {
2126           ::addMask(Mask, ReuseShuffleIndices);
2127           return IsSame(Scalars, Mask);
2128         }
2129         return false;
2130       }
2131       return IsSame(Scalars, ReuseShuffleIndices);
2132     }
2133 
2134     /// \returns true if current entry has same operands as \p TE.
2135     bool hasEqualOperands(const TreeEntry &TE) const {
2136       if (TE.getNumOperands() != getNumOperands())
2137         return false;
2138       SmallBitVector Used(getNumOperands());
2139       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2140         unsigned PrevCount = Used.count();
2141         for (unsigned K = 0; K < E; ++K) {
2142           if (Used.test(K))
2143             continue;
2144           if (getOperand(K) == TE.getOperand(I)) {
2145             Used.set(K);
2146             break;
2147           }
2148         }
2149         // Check if we actually found the matching operand.
2150         if (PrevCount == Used.count())
2151           return false;
2152       }
2153       return true;
2154     }
2155 
2156     /// \return Final vectorization factor for the node. Defined by the total
2157     /// number of vectorized scalars, including those, used several times in the
2158     /// entry and counted in the \a ReuseShuffleIndices, if any.
2159     unsigned getVectorFactor() const {
2160       if (!ReuseShuffleIndices.empty())
2161         return ReuseShuffleIndices.size();
2162       return Scalars.size();
2163     };
2164 
2165     /// A vector of scalars.
2166     ValueList Scalars;
2167 
2168     /// The Scalars are vectorized into this value. It is initialized to Null.
2169     Value *VectorizedValue = nullptr;
2170 
2171     /// Do we need to gather this sequence or vectorize it
2172     /// (either with vector instruction or with scatter/gather
2173     /// intrinsics for store/load)?
2174     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2175     EntryState State;
2176 
2177     /// Does this sequence require some shuffling?
2178     SmallVector<int, 4> ReuseShuffleIndices;
2179 
2180     /// Does this entry require reordering?
2181     SmallVector<unsigned, 4> ReorderIndices;
2182 
2183     /// Points back to the VectorizableTree.
2184     ///
2185     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2186     /// to be a pointer and needs to be able to initialize the child iterator.
2187     /// Thus we need a reference back to the container to translate the indices
2188     /// to entries.
2189     VecTreeTy &Container;
2190 
2191     /// The TreeEntry index containing the user of this entry.  We can actually
2192     /// have multiple users so the data structure is not truly a tree.
2193     SmallVector<EdgeInfo, 1> UserTreeIndices;
2194 
2195     /// The index of this treeEntry in VectorizableTree.
2196     int Idx = -1;
2197 
2198   private:
2199     /// The operands of each instruction in each lane Operands[op_index][lane].
2200     /// Note: This helps avoid the replication of the code that performs the
2201     /// reordering of operands during buildTree_rec() and vectorizeTree().
2202     SmallVector<ValueList, 2> Operands;
2203 
2204     /// The main/alternate instruction.
2205     Instruction *MainOp = nullptr;
2206     Instruction *AltOp = nullptr;
2207 
2208   public:
2209     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2210     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2211       if (Operands.size() < OpIdx + 1)
2212         Operands.resize(OpIdx + 1);
2213       assert(Operands[OpIdx].empty() && "Already resized?");
2214       assert(OpVL.size() <= Scalars.size() &&
2215              "Number of operands is greater than the number of scalars.");
2216       Operands[OpIdx].resize(OpVL.size());
2217       copy(OpVL, Operands[OpIdx].begin());
2218     }
2219 
2220     /// Set the operands of this bundle in their original order.
2221     void setOperandsInOrder() {
2222       assert(Operands.empty() && "Already initialized?");
2223       auto *I0 = cast<Instruction>(Scalars[0]);
2224       Operands.resize(I0->getNumOperands());
2225       unsigned NumLanes = Scalars.size();
2226       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2227            OpIdx != NumOperands; ++OpIdx) {
2228         Operands[OpIdx].resize(NumLanes);
2229         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2230           auto *I = cast<Instruction>(Scalars[Lane]);
2231           assert(I->getNumOperands() == NumOperands &&
2232                  "Expected same number of operands");
2233           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2234         }
2235       }
2236     }
2237 
2238     /// Reorders operands of the node to the given mask \p Mask.
2239     void reorderOperands(ArrayRef<int> Mask) {
2240       for (ValueList &Operand : Operands)
2241         reorderScalars(Operand, Mask);
2242     }
2243 
2244     /// \returns the \p OpIdx operand of this TreeEntry.
2245     ValueList &getOperand(unsigned OpIdx) {
2246       assert(OpIdx < Operands.size() && "Off bounds");
2247       return Operands[OpIdx];
2248     }
2249 
2250     /// \returns the \p OpIdx operand of this TreeEntry.
2251     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2252       assert(OpIdx < Operands.size() && "Off bounds");
2253       return Operands[OpIdx];
2254     }
2255 
2256     /// \returns the number of operands.
2257     unsigned getNumOperands() const { return Operands.size(); }
2258 
2259     /// \return the single \p OpIdx operand.
2260     Value *getSingleOperand(unsigned OpIdx) const {
2261       assert(OpIdx < Operands.size() && "Off bounds");
2262       assert(!Operands[OpIdx].empty() && "No operand available");
2263       return Operands[OpIdx][0];
2264     }
2265 
2266     /// Some of the instructions in the list have alternate opcodes.
2267     bool isAltShuffle() const { return MainOp != AltOp; }
2268 
2269     bool isOpcodeOrAlt(Instruction *I) const {
2270       unsigned CheckedOpcode = I->getOpcode();
2271       return (getOpcode() == CheckedOpcode ||
2272               getAltOpcode() == CheckedOpcode);
2273     }
2274 
2275     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2276     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2277     /// \p OpValue.
2278     Value *isOneOf(Value *Op) const {
2279       auto *I = dyn_cast<Instruction>(Op);
2280       if (I && isOpcodeOrAlt(I))
2281         return Op;
2282       return MainOp;
2283     }
2284 
2285     void setOperations(const InstructionsState &S) {
2286       MainOp = S.MainOp;
2287       AltOp = S.AltOp;
2288     }
2289 
2290     Instruction *getMainOp() const {
2291       return MainOp;
2292     }
2293 
2294     Instruction *getAltOp() const {
2295       return AltOp;
2296     }
2297 
2298     /// The main/alternate opcodes for the list of instructions.
2299     unsigned getOpcode() const {
2300       return MainOp ? MainOp->getOpcode() : 0;
2301     }
2302 
2303     unsigned getAltOpcode() const {
2304       return AltOp ? AltOp->getOpcode() : 0;
2305     }
2306 
2307     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2308     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2309     int findLaneForValue(Value *V) const {
2310       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2311       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2312       if (!ReorderIndices.empty())
2313         FoundLane = ReorderIndices[FoundLane];
2314       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2315       if (!ReuseShuffleIndices.empty()) {
2316         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2317                                   find(ReuseShuffleIndices, FoundLane));
2318       }
2319       return FoundLane;
2320     }
2321 
2322 #ifndef NDEBUG
2323     /// Debug printer.
2324     LLVM_DUMP_METHOD void dump() const {
2325       dbgs() << Idx << ".\n";
2326       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2327         dbgs() << "Operand " << OpI << ":\n";
2328         for (const Value *V : Operands[OpI])
2329           dbgs().indent(2) << *V << "\n";
2330       }
2331       dbgs() << "Scalars: \n";
2332       for (Value *V : Scalars)
2333         dbgs().indent(2) << *V << "\n";
2334       dbgs() << "State: ";
2335       switch (State) {
2336       case Vectorize:
2337         dbgs() << "Vectorize\n";
2338         break;
2339       case ScatterVectorize:
2340         dbgs() << "ScatterVectorize\n";
2341         break;
2342       case NeedToGather:
2343         dbgs() << "NeedToGather\n";
2344         break;
2345       }
2346       dbgs() << "MainOp: ";
2347       if (MainOp)
2348         dbgs() << *MainOp << "\n";
2349       else
2350         dbgs() << "NULL\n";
2351       dbgs() << "AltOp: ";
2352       if (AltOp)
2353         dbgs() << *AltOp << "\n";
2354       else
2355         dbgs() << "NULL\n";
2356       dbgs() << "VectorizedValue: ";
2357       if (VectorizedValue)
2358         dbgs() << *VectorizedValue << "\n";
2359       else
2360         dbgs() << "NULL\n";
2361       dbgs() << "ReuseShuffleIndices: ";
2362       if (ReuseShuffleIndices.empty())
2363         dbgs() << "Empty";
2364       else
2365         for (int ReuseIdx : ReuseShuffleIndices)
2366           dbgs() << ReuseIdx << ", ";
2367       dbgs() << "\n";
2368       dbgs() << "ReorderIndices: ";
2369       for (unsigned ReorderIdx : ReorderIndices)
2370         dbgs() << ReorderIdx << ", ";
2371       dbgs() << "\n";
2372       dbgs() << "UserTreeIndices: ";
2373       for (const auto &EInfo : UserTreeIndices)
2374         dbgs() << EInfo << ", ";
2375       dbgs() << "\n";
2376     }
2377 #endif
2378   };
2379 
2380 #ifndef NDEBUG
2381   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2382                      InstructionCost VecCost,
2383                      InstructionCost ScalarCost) const {
2384     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2385     dbgs() << "SLP: Costs:\n";
2386     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2387     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2388     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2389     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2390                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2391   }
2392 #endif
2393 
2394   /// Create a new VectorizableTree entry.
2395   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2396                           const InstructionsState &S,
2397                           const EdgeInfo &UserTreeIdx,
2398                           ArrayRef<int> ReuseShuffleIndices = None,
2399                           ArrayRef<unsigned> ReorderIndices = None) {
2400     TreeEntry::EntryState EntryState =
2401         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2402     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2403                         ReuseShuffleIndices, ReorderIndices);
2404   }
2405 
2406   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2407                           TreeEntry::EntryState EntryState,
2408                           Optional<ScheduleData *> Bundle,
2409                           const InstructionsState &S,
2410                           const EdgeInfo &UserTreeIdx,
2411                           ArrayRef<int> ReuseShuffleIndices = None,
2412                           ArrayRef<unsigned> ReorderIndices = None) {
2413     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2414             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2415            "Need to vectorize gather entry?");
2416     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2417     TreeEntry *Last = VectorizableTree.back().get();
2418     Last->Idx = VectorizableTree.size() - 1;
2419     Last->State = EntryState;
2420     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2421                                      ReuseShuffleIndices.end());
2422     if (ReorderIndices.empty()) {
2423       Last->Scalars.assign(VL.begin(), VL.end());
2424       Last->setOperations(S);
2425     } else {
2426       // Reorder scalars and build final mask.
2427       Last->Scalars.assign(VL.size(), nullptr);
2428       transform(ReorderIndices, Last->Scalars.begin(),
2429                 [VL](unsigned Idx) -> Value * {
2430                   if (Idx >= VL.size())
2431                     return UndefValue::get(VL.front()->getType());
2432                   return VL[Idx];
2433                 });
2434       InstructionsState S = getSameOpcode(Last->Scalars);
2435       Last->setOperations(S);
2436       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2437     }
2438     if (Last->State != TreeEntry::NeedToGather) {
2439       for (Value *V : VL) {
2440         assert(!getTreeEntry(V) && "Scalar already in tree!");
2441         ScalarToTreeEntry[V] = Last;
2442       }
2443       // Update the scheduler bundle to point to this TreeEntry.
2444       ScheduleData *BundleMember = Bundle.getValue();
2445       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2446               isVectorLikeInstWithConstOps(S.MainOp) ||
2447               doesNotNeedToSchedule(VL)) &&
2448              "Bundle and VL out of sync");
2449       if (BundleMember) {
2450         for (Value *V : VL) {
2451           if (doesNotNeedToBeScheduled(V))
2452             continue;
2453           assert(BundleMember && "Unexpected end of bundle.");
2454           BundleMember->TE = Last;
2455           BundleMember = BundleMember->NextInBundle;
2456         }
2457       }
2458       assert(!BundleMember && "Bundle and VL out of sync");
2459     } else {
2460       MustGather.insert(VL.begin(), VL.end());
2461     }
2462 
2463     if (UserTreeIdx.UserTE)
2464       Last->UserTreeIndices.push_back(UserTreeIdx);
2465 
2466     return Last;
2467   }
2468 
2469   /// -- Vectorization State --
2470   /// Holds all of the tree entries.
2471   TreeEntry::VecTreeTy VectorizableTree;
2472 
2473 #ifndef NDEBUG
2474   /// Debug printer.
2475   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2476     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2477       VectorizableTree[Id]->dump();
2478       dbgs() << "\n";
2479     }
2480   }
2481 #endif
2482 
2483   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2484 
2485   const TreeEntry *getTreeEntry(Value *V) const {
2486     return ScalarToTreeEntry.lookup(V);
2487   }
2488 
2489   /// Maps a specific scalar to its tree entry.
2490   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2491 
2492   /// Maps a value to the proposed vectorizable size.
2493   SmallDenseMap<Value *, unsigned> InstrElementSize;
2494 
2495   /// A list of scalars that we found that we need to keep as scalars.
2496   ValueSet MustGather;
2497 
2498   /// This POD struct describes one external user in the vectorized tree.
2499   struct ExternalUser {
2500     ExternalUser(Value *S, llvm::User *U, int L)
2501         : Scalar(S), User(U), Lane(L) {}
2502 
2503     // Which scalar in our function.
2504     Value *Scalar;
2505 
2506     // Which user that uses the scalar.
2507     llvm::User *User;
2508 
2509     // Which lane does the scalar belong to.
2510     int Lane;
2511   };
2512   using UserList = SmallVector<ExternalUser, 16>;
2513 
2514   /// Checks if two instructions may access the same memory.
2515   ///
2516   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2517   /// is invariant in the calling loop.
2518   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2519                  Instruction *Inst2) {
2520     // First check if the result is already in the cache.
2521     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2522     Optional<bool> &result = AliasCache[key];
2523     if (result.hasValue()) {
2524       return result.getValue();
2525     }
2526     bool aliased = true;
2527     if (Loc1.Ptr && isSimple(Inst1))
2528       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2529     // Store the result in the cache.
2530     result = aliased;
2531     return aliased;
2532   }
2533 
2534   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2535 
2536   /// Cache for alias results.
2537   /// TODO: consider moving this to the AliasAnalysis itself.
2538   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2539 
2540   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2541   // globally through SLP because we don't perform any action which
2542   // invalidates capture results.
2543   BatchAAResults BatchAA;
2544 
2545   /// Temporary store for deleted instructions. Instructions will be deleted
2546   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2547   /// ensure that there are no incorrect collisions in the AliasCache, which
2548   /// can happen if a new instruction is allocated at the same address as a
2549   /// previously deleted instruction.
2550   DenseSet<Instruction *> DeletedInstructions;
2551 
2552   /// A list of values that need to extracted out of the tree.
2553   /// This list holds pairs of (Internal Scalar : External User). External User
2554   /// can be nullptr, it means that this Internal Scalar will be used later,
2555   /// after vectorization.
2556   UserList ExternalUses;
2557 
2558   /// Values used only by @llvm.assume calls.
2559   SmallPtrSet<const Value *, 32> EphValues;
2560 
2561   /// Holds all of the instructions that we gathered.
2562   SetVector<Instruction *> GatherShuffleSeq;
2563 
2564   /// A list of blocks that we are going to CSE.
2565   SetVector<BasicBlock *> CSEBlocks;
2566 
2567   /// Contains all scheduling relevant data for an instruction.
2568   /// A ScheduleData either represents a single instruction or a member of an
2569   /// instruction bundle (= a group of instructions which is combined into a
2570   /// vector instruction).
2571   struct ScheduleData {
2572     // The initial value for the dependency counters. It means that the
2573     // dependencies are not calculated yet.
2574     enum { InvalidDeps = -1 };
2575 
2576     ScheduleData() = default;
2577 
2578     void init(int BlockSchedulingRegionID, Value *OpVal) {
2579       FirstInBundle = this;
2580       NextInBundle = nullptr;
2581       NextLoadStore = nullptr;
2582       IsScheduled = false;
2583       SchedulingRegionID = BlockSchedulingRegionID;
2584       clearDependencies();
2585       OpValue = OpVal;
2586       TE = nullptr;
2587     }
2588 
2589     /// Verify basic self consistency properties
2590     void verify() {
2591       if (hasValidDependencies()) {
2592         assert(UnscheduledDeps <= Dependencies && "invariant");
2593       } else {
2594         assert(UnscheduledDeps == Dependencies && "invariant");
2595       }
2596 
2597       if (IsScheduled) {
2598         assert(isSchedulingEntity() &&
2599                 "unexpected scheduled state");
2600         for (const ScheduleData *BundleMember = this; BundleMember;
2601              BundleMember = BundleMember->NextInBundle) {
2602           assert(BundleMember->hasValidDependencies() &&
2603                  BundleMember->UnscheduledDeps == 0 &&
2604                  "unexpected scheduled state");
2605           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2606                  "only bundle is marked scheduled");
2607         }
2608       }
2609 
2610       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2611              "all bundle members must be in same basic block");
2612     }
2613 
2614     /// Returns true if the dependency information has been calculated.
2615     /// Note that depenendency validity can vary between instructions within
2616     /// a single bundle.
2617     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2618 
2619     /// Returns true for single instructions and for bundle representatives
2620     /// (= the head of a bundle).
2621     bool isSchedulingEntity() const { return FirstInBundle == this; }
2622 
2623     /// Returns true if it represents an instruction bundle and not only a
2624     /// single instruction.
2625     bool isPartOfBundle() const {
2626       return NextInBundle != nullptr || FirstInBundle != this || TE;
2627     }
2628 
2629     /// Returns true if it is ready for scheduling, i.e. it has no more
2630     /// unscheduled depending instructions/bundles.
2631     bool isReady() const {
2632       assert(isSchedulingEntity() &&
2633              "can't consider non-scheduling entity for ready list");
2634       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2635     }
2636 
2637     /// Modifies the number of unscheduled dependencies for this instruction,
2638     /// and returns the number of remaining dependencies for the containing
2639     /// bundle.
2640     int incrementUnscheduledDeps(int Incr) {
2641       assert(hasValidDependencies() &&
2642              "increment of unscheduled deps would be meaningless");
2643       UnscheduledDeps += Incr;
2644       return FirstInBundle->unscheduledDepsInBundle();
2645     }
2646 
2647     /// Sets the number of unscheduled dependencies to the number of
2648     /// dependencies.
2649     void resetUnscheduledDeps() {
2650       UnscheduledDeps = Dependencies;
2651     }
2652 
2653     /// Clears all dependency information.
2654     void clearDependencies() {
2655       Dependencies = InvalidDeps;
2656       resetUnscheduledDeps();
2657       MemoryDependencies.clear();
2658       ControlDependencies.clear();
2659     }
2660 
2661     int unscheduledDepsInBundle() const {
2662       assert(isSchedulingEntity() && "only meaningful on the bundle");
2663       int Sum = 0;
2664       for (const ScheduleData *BundleMember = this; BundleMember;
2665            BundleMember = BundleMember->NextInBundle) {
2666         if (BundleMember->UnscheduledDeps == InvalidDeps)
2667           return InvalidDeps;
2668         Sum += BundleMember->UnscheduledDeps;
2669       }
2670       return Sum;
2671     }
2672 
2673     void dump(raw_ostream &os) const {
2674       if (!isSchedulingEntity()) {
2675         os << "/ " << *Inst;
2676       } else if (NextInBundle) {
2677         os << '[' << *Inst;
2678         ScheduleData *SD = NextInBundle;
2679         while (SD) {
2680           os << ';' << *SD->Inst;
2681           SD = SD->NextInBundle;
2682         }
2683         os << ']';
2684       } else {
2685         os << *Inst;
2686       }
2687     }
2688 
2689     Instruction *Inst = nullptr;
2690 
2691     /// Opcode of the current instruction in the schedule data.
2692     Value *OpValue = nullptr;
2693 
2694     /// The TreeEntry that this instruction corresponds to.
2695     TreeEntry *TE = nullptr;
2696 
2697     /// Points to the head in an instruction bundle (and always to this for
2698     /// single instructions).
2699     ScheduleData *FirstInBundle = nullptr;
2700 
2701     /// Single linked list of all instructions in a bundle. Null if it is a
2702     /// single instruction.
2703     ScheduleData *NextInBundle = nullptr;
2704 
2705     /// Single linked list of all memory instructions (e.g. load, store, call)
2706     /// in the block - until the end of the scheduling region.
2707     ScheduleData *NextLoadStore = nullptr;
2708 
2709     /// The dependent memory instructions.
2710     /// This list is derived on demand in calculateDependencies().
2711     SmallVector<ScheduleData *, 4> MemoryDependencies;
2712 
2713     /// List of instructions which this instruction could be control dependent
2714     /// on.  Allowing such nodes to be scheduled below this one could introduce
2715     /// a runtime fault which didn't exist in the original program.
2716     /// ex: this is a load or udiv following a readonly call which inf loops
2717     SmallVector<ScheduleData *, 4> ControlDependencies;
2718 
2719     /// This ScheduleData is in the current scheduling region if this matches
2720     /// the current SchedulingRegionID of BlockScheduling.
2721     int SchedulingRegionID = 0;
2722 
2723     /// Used for getting a "good" final ordering of instructions.
2724     int SchedulingPriority = 0;
2725 
2726     /// The number of dependencies. Constitutes of the number of users of the
2727     /// instruction plus the number of dependent memory instructions (if any).
2728     /// This value is calculated on demand.
2729     /// If InvalidDeps, the number of dependencies is not calculated yet.
2730     int Dependencies = InvalidDeps;
2731 
2732     /// The number of dependencies minus the number of dependencies of scheduled
2733     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2734     /// for scheduling.
2735     /// Note that this is negative as long as Dependencies is not calculated.
2736     int UnscheduledDeps = InvalidDeps;
2737 
2738     /// True if this instruction is scheduled (or considered as scheduled in the
2739     /// dry-run).
2740     bool IsScheduled = false;
2741   };
2742 
2743 #ifndef NDEBUG
2744   friend inline raw_ostream &operator<<(raw_ostream &os,
2745                                         const BoUpSLP::ScheduleData &SD) {
2746     SD.dump(os);
2747     return os;
2748   }
2749 #endif
2750 
2751   friend struct GraphTraits<BoUpSLP *>;
2752   friend struct DOTGraphTraits<BoUpSLP *>;
2753 
2754   /// Contains all scheduling data for a basic block.
2755   /// It does not schedules instructions, which are not memory read/write
2756   /// instructions and their operands are either constants, or arguments, or
2757   /// phis, or instructions from others blocks, or their users are phis or from
2758   /// the other blocks. The resulting vector instructions can be placed at the
2759   /// beginning of the basic block without scheduling (if operands does not need
2760   /// to be scheduled) or at the end of the block (if users are outside of the
2761   /// block). It allows to save some compile time and memory used by the
2762   /// compiler.
2763   /// ScheduleData is assigned for each instruction in between the boundaries of
2764   /// the tree entry, even for those, which are not part of the graph. It is
2765   /// required to correctly follow the dependencies between the instructions and
2766   /// their correct scheduling. The ScheduleData is not allocated for the
2767   /// instructions, which do not require scheduling, like phis, nodes with
2768   /// extractelements/insertelements only or nodes with instructions, with
2769   /// uses/operands outside of the block.
2770   struct BlockScheduling {
2771     BlockScheduling(BasicBlock *BB)
2772         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2773 
2774     void clear() {
2775       ReadyInsts.clear();
2776       ScheduleStart = nullptr;
2777       ScheduleEnd = nullptr;
2778       FirstLoadStoreInRegion = nullptr;
2779       LastLoadStoreInRegion = nullptr;
2780       RegionHasStackSave = false;
2781 
2782       // Reduce the maximum schedule region size by the size of the
2783       // previous scheduling run.
2784       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2785       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2786         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2787       ScheduleRegionSize = 0;
2788 
2789       // Make a new scheduling region, i.e. all existing ScheduleData is not
2790       // in the new region yet.
2791       ++SchedulingRegionID;
2792     }
2793 
2794     ScheduleData *getScheduleData(Instruction *I) {
2795       if (BB != I->getParent())
2796         // Avoid lookup if can't possibly be in map.
2797         return nullptr;
2798       ScheduleData *SD = ScheduleDataMap.lookup(I);
2799       if (SD && isInSchedulingRegion(SD))
2800         return SD;
2801       return nullptr;
2802     }
2803 
2804     ScheduleData *getScheduleData(Value *V) {
2805       if (auto *I = dyn_cast<Instruction>(V))
2806         return getScheduleData(I);
2807       return nullptr;
2808     }
2809 
2810     ScheduleData *getScheduleData(Value *V, Value *Key) {
2811       if (V == Key)
2812         return getScheduleData(V);
2813       auto I = ExtraScheduleDataMap.find(V);
2814       if (I != ExtraScheduleDataMap.end()) {
2815         ScheduleData *SD = I->second.lookup(Key);
2816         if (SD && isInSchedulingRegion(SD))
2817           return SD;
2818       }
2819       return nullptr;
2820     }
2821 
2822     bool isInSchedulingRegion(ScheduleData *SD) const {
2823       return SD->SchedulingRegionID == SchedulingRegionID;
2824     }
2825 
2826     /// Marks an instruction as scheduled and puts all dependent ready
2827     /// instructions into the ready-list.
2828     template <typename ReadyListType>
2829     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2830       SD->IsScheduled = true;
2831       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2832 
2833       for (ScheduleData *BundleMember = SD; BundleMember;
2834            BundleMember = BundleMember->NextInBundle) {
2835         if (BundleMember->Inst != BundleMember->OpValue)
2836           continue;
2837 
2838         // Handle the def-use chain dependencies.
2839 
2840         // Decrement the unscheduled counter and insert to ready list if ready.
2841         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2842           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2843             if (OpDef && OpDef->hasValidDependencies() &&
2844                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2845               // There are no more unscheduled dependencies after
2846               // decrementing, so we can put the dependent instruction
2847               // into the ready list.
2848               ScheduleData *DepBundle = OpDef->FirstInBundle;
2849               assert(!DepBundle->IsScheduled &&
2850                      "already scheduled bundle gets ready");
2851               ReadyList.insert(DepBundle);
2852               LLVM_DEBUG(dbgs()
2853                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2854             }
2855           });
2856         };
2857 
2858         // If BundleMember is a vector bundle, its operands may have been
2859         // reordered during buildTree(). We therefore need to get its operands
2860         // through the TreeEntry.
2861         if (TreeEntry *TE = BundleMember->TE) {
2862           // Need to search for the lane since the tree entry can be reordered.
2863           int Lane = std::distance(TE->Scalars.begin(),
2864                                    find(TE->Scalars, BundleMember->Inst));
2865           assert(Lane >= 0 && "Lane not set");
2866 
2867           // Since vectorization tree is being built recursively this assertion
2868           // ensures that the tree entry has all operands set before reaching
2869           // this code. Couple of exceptions known at the moment are extracts
2870           // where their second (immediate) operand is not added. Since
2871           // immediates do not affect scheduler behavior this is considered
2872           // okay.
2873           auto *In = BundleMember->Inst;
2874           assert(In &&
2875                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2876                   In->getNumOperands() == TE->getNumOperands()) &&
2877                  "Missed TreeEntry operands?");
2878           (void)In; // fake use to avoid build failure when assertions disabled
2879 
2880           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2881                OpIdx != NumOperands; ++OpIdx)
2882             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2883               DecrUnsched(I);
2884         } else {
2885           // If BundleMember is a stand-alone instruction, no operand reordering
2886           // has taken place, so we directly access its operands.
2887           for (Use &U : BundleMember->Inst->operands())
2888             if (auto *I = dyn_cast<Instruction>(U.get()))
2889               DecrUnsched(I);
2890         }
2891         // Handle the memory dependencies.
2892         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2893           if (MemoryDepSD->hasValidDependencies() &&
2894               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2895             // There are no more unscheduled dependencies after decrementing,
2896             // so we can put the dependent instruction into the ready list.
2897             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2898             assert(!DepBundle->IsScheduled &&
2899                    "already scheduled bundle gets ready");
2900             ReadyList.insert(DepBundle);
2901             LLVM_DEBUG(dbgs()
2902                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2903           }
2904         }
2905         // Handle the control dependencies.
2906         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2907           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2908             // There are no more unscheduled dependencies after decrementing,
2909             // so we can put the dependent instruction into the ready list.
2910             ScheduleData *DepBundle = DepSD->FirstInBundle;
2911             assert(!DepBundle->IsScheduled &&
2912                    "already scheduled bundle gets ready");
2913             ReadyList.insert(DepBundle);
2914             LLVM_DEBUG(dbgs()
2915                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2916           }
2917         }
2918 
2919       }
2920     }
2921 
2922     /// Verify basic self consistency properties of the data structure.
2923     void verify() {
2924       if (!ScheduleStart)
2925         return;
2926 
2927       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2928              ScheduleStart->comesBefore(ScheduleEnd) &&
2929              "Not a valid scheduling region?");
2930 
2931       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2932         auto *SD = getScheduleData(I);
2933         if (!SD)
2934           continue;
2935         assert(isInSchedulingRegion(SD) &&
2936                "primary schedule data not in window?");
2937         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2938                "entire bundle in window!");
2939         (void)SD;
2940         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2941       }
2942 
2943       for (auto *SD : ReadyInsts) {
2944         assert(SD->isSchedulingEntity() && SD->isReady() &&
2945                "item in ready list not ready?");
2946         (void)SD;
2947       }
2948     }
2949 
2950     void doForAllOpcodes(Value *V,
2951                          function_ref<void(ScheduleData *SD)> Action) {
2952       if (ScheduleData *SD = getScheduleData(V))
2953         Action(SD);
2954       auto I = ExtraScheduleDataMap.find(V);
2955       if (I != ExtraScheduleDataMap.end())
2956         for (auto &P : I->second)
2957           if (isInSchedulingRegion(P.second))
2958             Action(P.second);
2959     }
2960 
2961     /// Put all instructions into the ReadyList which are ready for scheduling.
2962     template <typename ReadyListType>
2963     void initialFillReadyList(ReadyListType &ReadyList) {
2964       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2965         doForAllOpcodes(I, [&](ScheduleData *SD) {
2966           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2967               SD->isReady()) {
2968             ReadyList.insert(SD);
2969             LLVM_DEBUG(dbgs()
2970                        << "SLP:    initially in ready list: " << *SD << "\n");
2971           }
2972         });
2973       }
2974     }
2975 
2976     /// Build a bundle from the ScheduleData nodes corresponding to the
2977     /// scalar instruction for each lane.
2978     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2979 
2980     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2981     /// cyclic dependencies. This is only a dry-run, no instructions are
2982     /// actually moved at this stage.
2983     /// \returns the scheduling bundle. The returned Optional value is non-None
2984     /// if \p VL is allowed to be scheduled.
2985     Optional<ScheduleData *>
2986     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2987                       const InstructionsState &S);
2988 
2989     /// Un-bundles a group of instructions.
2990     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2991 
2992     /// Allocates schedule data chunk.
2993     ScheduleData *allocateScheduleDataChunks();
2994 
2995     /// Extends the scheduling region so that V is inside the region.
2996     /// \returns true if the region size is within the limit.
2997     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2998 
2999     /// Initialize the ScheduleData structures for new instructions in the
3000     /// scheduling region.
3001     void initScheduleData(Instruction *FromI, Instruction *ToI,
3002                           ScheduleData *PrevLoadStore,
3003                           ScheduleData *NextLoadStore);
3004 
3005     /// Updates the dependency information of a bundle and of all instructions/
3006     /// bundles which depend on the original bundle.
3007     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3008                                BoUpSLP *SLP);
3009 
3010     /// Sets all instruction in the scheduling region to un-scheduled.
3011     void resetSchedule();
3012 
3013     BasicBlock *BB;
3014 
3015     /// Simple memory allocation for ScheduleData.
3016     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3017 
3018     /// The size of a ScheduleData array in ScheduleDataChunks.
3019     int ChunkSize;
3020 
3021     /// The allocator position in the current chunk, which is the last entry
3022     /// of ScheduleDataChunks.
3023     int ChunkPos;
3024 
3025     /// Attaches ScheduleData to Instruction.
3026     /// Note that the mapping survives during all vectorization iterations, i.e.
3027     /// ScheduleData structures are recycled.
3028     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3029 
3030     /// Attaches ScheduleData to Instruction with the leading key.
3031     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3032         ExtraScheduleDataMap;
3033 
3034     /// The ready-list for scheduling (only used for the dry-run).
3035     SetVector<ScheduleData *> ReadyInsts;
3036 
3037     /// The first instruction of the scheduling region.
3038     Instruction *ScheduleStart = nullptr;
3039 
3040     /// The first instruction _after_ the scheduling region.
3041     Instruction *ScheduleEnd = nullptr;
3042 
3043     /// The first memory accessing instruction in the scheduling region
3044     /// (can be null).
3045     ScheduleData *FirstLoadStoreInRegion = nullptr;
3046 
3047     /// The last memory accessing instruction in the scheduling region
3048     /// (can be null).
3049     ScheduleData *LastLoadStoreInRegion = nullptr;
3050 
3051     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3052     /// region?  Used to optimize the dependence calculation for the
3053     /// common case where there isn't.
3054     bool RegionHasStackSave = false;
3055 
3056     /// The current size of the scheduling region.
3057     int ScheduleRegionSize = 0;
3058 
3059     /// The maximum size allowed for the scheduling region.
3060     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3061 
3062     /// The ID of the scheduling region. For a new vectorization iteration this
3063     /// is incremented which "removes" all ScheduleData from the region.
3064     /// Make sure that the initial SchedulingRegionID is greater than the
3065     /// initial SchedulingRegionID in ScheduleData (which is 0).
3066     int SchedulingRegionID = 1;
3067   };
3068 
3069   /// Attaches the BlockScheduling structures to basic blocks.
3070   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3071 
3072   /// Performs the "real" scheduling. Done before vectorization is actually
3073   /// performed in a basic block.
3074   void scheduleBlock(BlockScheduling *BS);
3075 
3076   /// List of users to ignore during scheduling and that don't need extracting.
3077   ArrayRef<Value *> UserIgnoreList;
3078 
3079   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3080   /// sorted SmallVectors of unsigned.
3081   struct OrdersTypeDenseMapInfo {
3082     static OrdersType getEmptyKey() {
3083       OrdersType V;
3084       V.push_back(~1U);
3085       return V;
3086     }
3087 
3088     static OrdersType getTombstoneKey() {
3089       OrdersType V;
3090       V.push_back(~2U);
3091       return V;
3092     }
3093 
3094     static unsigned getHashValue(const OrdersType &V) {
3095       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3096     }
3097 
3098     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3099       return LHS == RHS;
3100     }
3101   };
3102 
3103   // Analysis and block reference.
3104   Function *F;
3105   ScalarEvolution *SE;
3106   TargetTransformInfo *TTI;
3107   TargetLibraryInfo *TLI;
3108   LoopInfo *LI;
3109   DominatorTree *DT;
3110   AssumptionCache *AC;
3111   DemandedBits *DB;
3112   const DataLayout *DL;
3113   OptimizationRemarkEmitter *ORE;
3114 
3115   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3116   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3117 
3118   /// Instruction builder to construct the vectorized tree.
3119   IRBuilder<> Builder;
3120 
3121   /// A map of scalar integer values to the smallest bit width with which they
3122   /// can legally be represented. The values map to (width, signed) pairs,
3123   /// where "width" indicates the minimum bit width and "signed" is True if the
3124   /// value must be signed-extended, rather than zero-extended, back to its
3125   /// original width.
3126   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3127 };
3128 
3129 } // end namespace slpvectorizer
3130 
3131 template <> struct GraphTraits<BoUpSLP *> {
3132   using TreeEntry = BoUpSLP::TreeEntry;
3133 
3134   /// NodeRef has to be a pointer per the GraphWriter.
3135   using NodeRef = TreeEntry *;
3136 
3137   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3138 
3139   /// Add the VectorizableTree to the index iterator to be able to return
3140   /// TreeEntry pointers.
3141   struct ChildIteratorType
3142       : public iterator_adaptor_base<
3143             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3144     ContainerTy &VectorizableTree;
3145 
3146     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3147                       ContainerTy &VT)
3148         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3149 
3150     NodeRef operator*() { return I->UserTE; }
3151   };
3152 
3153   static NodeRef getEntryNode(BoUpSLP &R) {
3154     return R.VectorizableTree[0].get();
3155   }
3156 
3157   static ChildIteratorType child_begin(NodeRef N) {
3158     return {N->UserTreeIndices.begin(), N->Container};
3159   }
3160 
3161   static ChildIteratorType child_end(NodeRef N) {
3162     return {N->UserTreeIndices.end(), N->Container};
3163   }
3164 
3165   /// For the node iterator we just need to turn the TreeEntry iterator into a
3166   /// TreeEntry* iterator so that it dereferences to NodeRef.
3167   class nodes_iterator {
3168     using ItTy = ContainerTy::iterator;
3169     ItTy It;
3170 
3171   public:
3172     nodes_iterator(const ItTy &It2) : It(It2) {}
3173     NodeRef operator*() { return It->get(); }
3174     nodes_iterator operator++() {
3175       ++It;
3176       return *this;
3177     }
3178     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3179   };
3180 
3181   static nodes_iterator nodes_begin(BoUpSLP *R) {
3182     return nodes_iterator(R->VectorizableTree.begin());
3183   }
3184 
3185   static nodes_iterator nodes_end(BoUpSLP *R) {
3186     return nodes_iterator(R->VectorizableTree.end());
3187   }
3188 
3189   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3190 };
3191 
3192 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3193   using TreeEntry = BoUpSLP::TreeEntry;
3194 
3195   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3196 
3197   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3198     std::string Str;
3199     raw_string_ostream OS(Str);
3200     if (isSplat(Entry->Scalars))
3201       OS << "<splat> ";
3202     for (auto V : Entry->Scalars) {
3203       OS << *V;
3204       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3205             return EU.Scalar == V;
3206           }))
3207         OS << " <extract>";
3208       OS << "\n";
3209     }
3210     return Str;
3211   }
3212 
3213   static std::string getNodeAttributes(const TreeEntry *Entry,
3214                                        const BoUpSLP *) {
3215     if (Entry->State == TreeEntry::NeedToGather)
3216       return "color=red";
3217     return "";
3218   }
3219 };
3220 
3221 } // end namespace llvm
3222 
3223 BoUpSLP::~BoUpSLP() {
3224   SmallVector<WeakTrackingVH> DeadInsts;
3225   for (auto *I : DeletedInstructions) {
3226     for (Use &U : I->operands()) {
3227       auto *Op = dyn_cast<Instruction>(U.get());
3228       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3229           wouldInstructionBeTriviallyDead(Op, TLI))
3230         DeadInsts.emplace_back(Op);
3231     }
3232     I->dropAllReferences();
3233   }
3234   for (auto *I : DeletedInstructions) {
3235     assert(I->use_empty() &&
3236            "trying to erase instruction with users.");
3237     I->eraseFromParent();
3238   }
3239 
3240   // Cleanup any dead scalar code feeding the vectorized instructions
3241   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3242 
3243 #ifdef EXPENSIVE_CHECKS
3244   // If we could guarantee that this call is not extremely slow, we could
3245   // remove the ifdef limitation (see PR47712).
3246   assert(!verifyFunction(*F, &dbgs()));
3247 #endif
3248 }
3249 
3250 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3251 /// contains original mask for the scalars reused in the node. Procedure
3252 /// transform this mask in accordance with the given \p Mask.
3253 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3254   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3255          "Expected non-empty mask.");
3256   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3257   Prev.swap(Reuses);
3258   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3259     if (Mask[I] != UndefMaskElem)
3260       Reuses[Mask[I]] = Prev[I];
3261 }
3262 
3263 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3264 /// the original order of the scalars. Procedure transforms the provided order
3265 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3266 /// identity order, \p Order is cleared.
3267 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3268   assert(!Mask.empty() && "Expected non-empty mask.");
3269   SmallVector<int> MaskOrder;
3270   if (Order.empty()) {
3271     MaskOrder.resize(Mask.size());
3272     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3273   } else {
3274     inversePermutation(Order, MaskOrder);
3275   }
3276   reorderReuses(MaskOrder, Mask);
3277   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3278     Order.clear();
3279     return;
3280   }
3281   Order.assign(Mask.size(), Mask.size());
3282   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3283     if (MaskOrder[I] != UndefMaskElem)
3284       Order[MaskOrder[I]] = I;
3285   fixupOrderingIndices(Order);
3286 }
3287 
3288 Optional<BoUpSLP::OrdersType>
3289 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3290   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3291   unsigned NumScalars = TE.Scalars.size();
3292   OrdersType CurrentOrder(NumScalars, NumScalars);
3293   SmallVector<int> Positions;
3294   SmallBitVector UsedPositions(NumScalars);
3295   const TreeEntry *STE = nullptr;
3296   // Try to find all gathered scalars that are gets vectorized in other
3297   // vectorize node. Here we can have only one single tree vector node to
3298   // correctly identify order of the gathered scalars.
3299   for (unsigned I = 0; I < NumScalars; ++I) {
3300     Value *V = TE.Scalars[I];
3301     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3302       continue;
3303     if (const auto *LocalSTE = getTreeEntry(V)) {
3304       if (!STE)
3305         STE = LocalSTE;
3306       else if (STE != LocalSTE)
3307         // Take the order only from the single vector node.
3308         return None;
3309       unsigned Lane =
3310           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3311       if (Lane >= NumScalars)
3312         return None;
3313       if (CurrentOrder[Lane] != NumScalars) {
3314         if (Lane != I)
3315           continue;
3316         UsedPositions.reset(CurrentOrder[Lane]);
3317       }
3318       // The partial identity (where only some elements of the gather node are
3319       // in the identity order) is good.
3320       CurrentOrder[Lane] = I;
3321       UsedPositions.set(I);
3322     }
3323   }
3324   // Need to keep the order if we have a vector entry and at least 2 scalars or
3325   // the vectorized entry has just 2 scalars.
3326   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3327     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3328       for (unsigned I = 0; I < NumScalars; ++I)
3329         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3330           return false;
3331       return true;
3332     };
3333     if (IsIdentityOrder(CurrentOrder)) {
3334       CurrentOrder.clear();
3335       return CurrentOrder;
3336     }
3337     auto *It = CurrentOrder.begin();
3338     for (unsigned I = 0; I < NumScalars;) {
3339       if (UsedPositions.test(I)) {
3340         ++I;
3341         continue;
3342       }
3343       if (*It == NumScalars) {
3344         *It = I;
3345         ++I;
3346       }
3347       ++It;
3348     }
3349     return CurrentOrder;
3350   }
3351   return None;
3352 }
3353 
3354 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3355                                                          bool TopToBottom) {
3356   // No need to reorder if need to shuffle reuses, still need to shuffle the
3357   // node.
3358   if (!TE.ReuseShuffleIndices.empty())
3359     return None;
3360   if (TE.State == TreeEntry::Vectorize &&
3361       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3362        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3363       !TE.isAltShuffle())
3364     return TE.ReorderIndices;
3365   if (TE.State == TreeEntry::NeedToGather) {
3366     // TODO: add analysis of other gather nodes with extractelement
3367     // instructions and other values/instructions, not only undefs.
3368     if (((TE.getOpcode() == Instruction::ExtractElement &&
3369           !TE.isAltShuffle()) ||
3370          (all_of(TE.Scalars,
3371                  [](Value *V) {
3372                    return isa<UndefValue, ExtractElementInst>(V);
3373                  }) &&
3374           any_of(TE.Scalars,
3375                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3376         all_of(TE.Scalars,
3377                [](Value *V) {
3378                  auto *EE = dyn_cast<ExtractElementInst>(V);
3379                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3380                }) &&
3381         allSameType(TE.Scalars)) {
3382       // Check that gather of extractelements can be represented as
3383       // just a shuffle of a single vector.
3384       OrdersType CurrentOrder;
3385       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3386       if (Reuse || !CurrentOrder.empty()) {
3387         if (!CurrentOrder.empty())
3388           fixupOrderingIndices(CurrentOrder);
3389         return CurrentOrder;
3390       }
3391     }
3392     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3393       return CurrentOrder;
3394   }
3395   return None;
3396 }
3397 
3398 void BoUpSLP::reorderTopToBottom() {
3399   // Maps VF to the graph nodes.
3400   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3401   // ExtractElement gather nodes which can be vectorized and need to handle
3402   // their ordering.
3403   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3404   // Find all reorderable nodes with the given VF.
3405   // Currently the are vectorized stores,loads,extracts + some gathering of
3406   // extracts.
3407   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3408                                  const std::unique_ptr<TreeEntry> &TE) {
3409     if (Optional<OrdersType> CurrentOrder =
3410             getReorderingData(*TE, /*TopToBottom=*/true)) {
3411       // Do not include ordering for nodes used in the alt opcode vectorization,
3412       // better to reorder them during bottom-to-top stage. If follow the order
3413       // here, it causes reordering of the whole graph though actually it is
3414       // profitable just to reorder the subgraph that starts from the alternate
3415       // opcode vectorization node. Such nodes already end-up with the shuffle
3416       // instruction and it is just enough to change this shuffle rather than
3417       // rotate the scalars for the whole graph.
3418       unsigned Cnt = 0;
3419       const TreeEntry *UserTE = TE.get();
3420       while (UserTE && Cnt < RecursionMaxDepth) {
3421         if (UserTE->UserTreeIndices.size() != 1)
3422           break;
3423         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3424               return EI.UserTE->State == TreeEntry::Vectorize &&
3425                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3426             }))
3427           return;
3428         if (UserTE->UserTreeIndices.empty())
3429           UserTE = nullptr;
3430         else
3431           UserTE = UserTE->UserTreeIndices.back().UserTE;
3432         ++Cnt;
3433       }
3434       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3435       if (TE->State != TreeEntry::Vectorize)
3436         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3437     }
3438   });
3439 
3440   // Reorder the graph nodes according to their vectorization factor.
3441   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3442        VF /= 2) {
3443     auto It = VFToOrderedEntries.find(VF);
3444     if (It == VFToOrderedEntries.end())
3445       continue;
3446     // Try to find the most profitable order. We just are looking for the most
3447     // used order and reorder scalar elements in the nodes according to this
3448     // mostly used order.
3449     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3450     // All operands are reordered and used only in this node - propagate the
3451     // most used order to the user node.
3452     MapVector<OrdersType, unsigned,
3453               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3454         OrdersUses;
3455     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3456     for (const TreeEntry *OpTE : OrderedEntries) {
3457       // No need to reorder this nodes, still need to extend and to use shuffle,
3458       // just need to merge reordering shuffle and the reuse shuffle.
3459       if (!OpTE->ReuseShuffleIndices.empty())
3460         continue;
3461       // Count number of orders uses.
3462       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3463         if (OpTE->State == TreeEntry::NeedToGather)
3464           return GathersToOrders.find(OpTE)->second;
3465         return OpTE->ReorderIndices;
3466       }();
3467       // Stores actually store the mask, not the order, need to invert.
3468       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3469           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3470         SmallVector<int> Mask;
3471         inversePermutation(Order, Mask);
3472         unsigned E = Order.size();
3473         OrdersType CurrentOrder(E, E);
3474         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3475           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3476         });
3477         fixupOrderingIndices(CurrentOrder);
3478         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3479       } else {
3480         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3481       }
3482     }
3483     // Set order of the user node.
3484     if (OrdersUses.empty())
3485       continue;
3486     // Choose the most used order.
3487     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3488     unsigned Cnt = OrdersUses.front().second;
3489     for (const auto &Pair : drop_begin(OrdersUses)) {
3490       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3491         BestOrder = Pair.first;
3492         Cnt = Pair.second;
3493       }
3494     }
3495     // Set order of the user node.
3496     if (BestOrder.empty())
3497       continue;
3498     SmallVector<int> Mask;
3499     inversePermutation(BestOrder, Mask);
3500     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3501     unsigned E = BestOrder.size();
3502     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3503       return I < E ? static_cast<int>(I) : UndefMaskElem;
3504     });
3505     // Do an actual reordering, if profitable.
3506     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3507       // Just do the reordering for the nodes with the given VF.
3508       if (TE->Scalars.size() != VF) {
3509         if (TE->ReuseShuffleIndices.size() == VF) {
3510           // Need to reorder the reuses masks of the operands with smaller VF to
3511           // be able to find the match between the graph nodes and scalar
3512           // operands of the given node during vectorization/cost estimation.
3513           assert(all_of(TE->UserTreeIndices,
3514                         [VF, &TE](const EdgeInfo &EI) {
3515                           return EI.UserTE->Scalars.size() == VF ||
3516                                  EI.UserTE->Scalars.size() ==
3517                                      TE->Scalars.size();
3518                         }) &&
3519                  "All users must be of VF size.");
3520           // Update ordering of the operands with the smaller VF than the given
3521           // one.
3522           reorderReuses(TE->ReuseShuffleIndices, Mask);
3523         }
3524         continue;
3525       }
3526       if (TE->State == TreeEntry::Vectorize &&
3527           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3528               InsertElementInst>(TE->getMainOp()) &&
3529           !TE->isAltShuffle()) {
3530         // Build correct orders for extract{element,value}, loads and
3531         // stores.
3532         reorderOrder(TE->ReorderIndices, Mask);
3533         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3534           TE->reorderOperands(Mask);
3535       } else {
3536         // Reorder the node and its operands.
3537         TE->reorderOperands(Mask);
3538         assert(TE->ReorderIndices.empty() &&
3539                "Expected empty reorder sequence.");
3540         reorderScalars(TE->Scalars, Mask);
3541       }
3542       if (!TE->ReuseShuffleIndices.empty()) {
3543         // Apply reversed order to keep the original ordering of the reused
3544         // elements to avoid extra reorder indices shuffling.
3545         OrdersType CurrentOrder;
3546         reorderOrder(CurrentOrder, MaskOrder);
3547         SmallVector<int> NewReuses;
3548         inversePermutation(CurrentOrder, NewReuses);
3549         addMask(NewReuses, TE->ReuseShuffleIndices);
3550         TE->ReuseShuffleIndices.swap(NewReuses);
3551       }
3552     }
3553   }
3554 }
3555 
3556 bool BoUpSLP::canReorderOperands(
3557     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3558     ArrayRef<TreeEntry *> ReorderableGathers,
3559     SmallVectorImpl<TreeEntry *> &GatherOps) {
3560   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3561     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3562           return OpData.first == I &&
3563                  OpData.second->State == TreeEntry::Vectorize;
3564         }))
3565       continue;
3566     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3567       // Do not reorder if operand node is used by many user nodes.
3568       if (any_of(TE->UserTreeIndices,
3569                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3570         return false;
3571       // Add the node to the list of the ordered nodes with the identity
3572       // order.
3573       Edges.emplace_back(I, TE);
3574       continue;
3575     }
3576     ArrayRef<Value *> VL = UserTE->getOperand(I);
3577     TreeEntry *Gather = nullptr;
3578     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3579           assert(TE->State != TreeEntry::Vectorize &&
3580                  "Only non-vectorized nodes are expected.");
3581           if (TE->isSame(VL)) {
3582             Gather = TE;
3583             return true;
3584           }
3585           return false;
3586         }) > 1)
3587       return false;
3588     if (Gather)
3589       GatherOps.push_back(Gather);
3590   }
3591   return true;
3592 }
3593 
3594 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3595   SetVector<TreeEntry *> OrderedEntries;
3596   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3597   // Find all reorderable leaf nodes with the given VF.
3598   // Currently the are vectorized loads,extracts without alternate operands +
3599   // some gathering of extracts.
3600   SmallVector<TreeEntry *> NonVectorized;
3601   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3602                               &NonVectorized](
3603                                  const std::unique_ptr<TreeEntry> &TE) {
3604     if (TE->State != TreeEntry::Vectorize)
3605       NonVectorized.push_back(TE.get());
3606     if (Optional<OrdersType> CurrentOrder =
3607             getReorderingData(*TE, /*TopToBottom=*/false)) {
3608       OrderedEntries.insert(TE.get());
3609       if (TE->State != TreeEntry::Vectorize)
3610         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3611     }
3612   });
3613 
3614   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3615   // I.e., if the node has operands, that are reordered, try to make at least
3616   // one operand order in the natural order and reorder others + reorder the
3617   // user node itself.
3618   SmallPtrSet<const TreeEntry *, 4> Visited;
3619   while (!OrderedEntries.empty()) {
3620     // 1. Filter out only reordered nodes.
3621     // 2. If the entry has multiple uses - skip it and jump to the next node.
3622     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3623     SmallVector<TreeEntry *> Filtered;
3624     for (TreeEntry *TE : OrderedEntries) {
3625       if (!(TE->State == TreeEntry::Vectorize ||
3626             (TE->State == TreeEntry::NeedToGather &&
3627              GathersToOrders.count(TE))) ||
3628           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3629           !all_of(drop_begin(TE->UserTreeIndices),
3630                   [TE](const EdgeInfo &EI) {
3631                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3632                   }) ||
3633           !Visited.insert(TE).second) {
3634         Filtered.push_back(TE);
3635         continue;
3636       }
3637       // Build a map between user nodes and their operands order to speedup
3638       // search. The graph currently does not provide this dependency directly.
3639       for (EdgeInfo &EI : TE->UserTreeIndices) {
3640         TreeEntry *UserTE = EI.UserTE;
3641         auto It = Users.find(UserTE);
3642         if (It == Users.end())
3643           It = Users.insert({UserTE, {}}).first;
3644         It->second.emplace_back(EI.EdgeIdx, TE);
3645       }
3646     }
3647     // Erase filtered entries.
3648     for_each(Filtered,
3649              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3650     for (auto &Data : Users) {
3651       // Check that operands are used only in the User node.
3652       SmallVector<TreeEntry *> GatherOps;
3653       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3654                               GatherOps)) {
3655         for_each(Data.second,
3656                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3657                    OrderedEntries.remove(Op.second);
3658                  });
3659         continue;
3660       }
3661       // All operands are reordered and used only in this node - propagate the
3662       // most used order to the user node.
3663       MapVector<OrdersType, unsigned,
3664                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3665           OrdersUses;
3666       // Do the analysis for each tree entry only once, otherwise the order of
3667       // the same node my be considered several times, though might be not
3668       // profitable.
3669       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3670       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3671       for (const auto &Op : Data.second) {
3672         TreeEntry *OpTE = Op.second;
3673         if (!VisitedOps.insert(OpTE).second)
3674           continue;
3675         if (!OpTE->ReuseShuffleIndices.empty() ||
3676             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3677           continue;
3678         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3679           if (OpTE->State == TreeEntry::NeedToGather)
3680             return GathersToOrders.find(OpTE)->second;
3681           return OpTE->ReorderIndices;
3682         }();
3683         unsigned NumOps = count_if(
3684             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3685               return P.second == OpTE;
3686             });
3687         // Stores actually store the mask, not the order, need to invert.
3688         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3689             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3690           SmallVector<int> Mask;
3691           inversePermutation(Order, Mask);
3692           unsigned E = Order.size();
3693           OrdersType CurrentOrder(E, E);
3694           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3695             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3696           });
3697           fixupOrderingIndices(CurrentOrder);
3698           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3699               NumOps;
3700         } else {
3701           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3702         }
3703         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3704         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3705                                             const TreeEntry *TE) {
3706           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3707               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3708               (IgnoreReorder && TE->Idx == 0))
3709             return true;
3710           if (TE->State == TreeEntry::NeedToGather) {
3711             auto It = GathersToOrders.find(TE);
3712             if (It != GathersToOrders.end())
3713               return !It->second.empty();
3714             return true;
3715           }
3716           return false;
3717         };
3718         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3719           TreeEntry *UserTE = EI.UserTE;
3720           if (!VisitedUsers.insert(UserTE).second)
3721             continue;
3722           // May reorder user node if it requires reordering, has reused
3723           // scalars, is an alternate op vectorize node or its op nodes require
3724           // reordering.
3725           if (AllowsReordering(UserTE))
3726             continue;
3727           // Check if users allow reordering.
3728           // Currently look up just 1 level of operands to avoid increase of
3729           // the compile time.
3730           // Profitable to reorder if definitely more operands allow
3731           // reordering rather than those with natural order.
3732           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3733           if (static_cast<unsigned>(count_if(
3734                   Ops, [UserTE, &AllowsReordering](
3735                            const std::pair<unsigned, TreeEntry *> &Op) {
3736                     return AllowsReordering(Op.second) &&
3737                            all_of(Op.second->UserTreeIndices,
3738                                   [UserTE](const EdgeInfo &EI) {
3739                                     return EI.UserTE == UserTE;
3740                                   });
3741                   })) <= Ops.size() / 2)
3742             ++Res.first->second;
3743         }
3744       }
3745       // If no orders - skip current nodes and jump to the next one, if any.
3746       if (OrdersUses.empty()) {
3747         for_each(Data.second,
3748                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3749                    OrderedEntries.remove(Op.second);
3750                  });
3751         continue;
3752       }
3753       // Choose the best order.
3754       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3755       unsigned Cnt = OrdersUses.front().second;
3756       for (const auto &Pair : drop_begin(OrdersUses)) {
3757         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3758           BestOrder = Pair.first;
3759           Cnt = Pair.second;
3760         }
3761       }
3762       // Set order of the user node (reordering of operands and user nodes).
3763       if (BestOrder.empty()) {
3764         for_each(Data.second,
3765                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3766                    OrderedEntries.remove(Op.second);
3767                  });
3768         continue;
3769       }
3770       // Erase operands from OrderedEntries list and adjust their orders.
3771       VisitedOps.clear();
3772       SmallVector<int> Mask;
3773       inversePermutation(BestOrder, Mask);
3774       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3775       unsigned E = BestOrder.size();
3776       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3777         return I < E ? static_cast<int>(I) : UndefMaskElem;
3778       });
3779       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3780         TreeEntry *TE = Op.second;
3781         OrderedEntries.remove(TE);
3782         if (!VisitedOps.insert(TE).second)
3783           continue;
3784         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3785           // Just reorder reuses indices.
3786           reorderReuses(TE->ReuseShuffleIndices, Mask);
3787           continue;
3788         }
3789         // Gathers are processed separately.
3790         if (TE->State != TreeEntry::Vectorize)
3791           continue;
3792         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3793                 TE->ReorderIndices.empty()) &&
3794                "Non-matching sizes of user/operand entries.");
3795         reorderOrder(TE->ReorderIndices, Mask);
3796       }
3797       // For gathers just need to reorder its scalars.
3798       for (TreeEntry *Gather : GatherOps) {
3799         assert(Gather->ReorderIndices.empty() &&
3800                "Unexpected reordering of gathers.");
3801         if (!Gather->ReuseShuffleIndices.empty()) {
3802           // Just reorder reuses indices.
3803           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3804           continue;
3805         }
3806         reorderScalars(Gather->Scalars, Mask);
3807         OrderedEntries.remove(Gather);
3808       }
3809       // Reorder operands of the user node and set the ordering for the user
3810       // node itself.
3811       if (Data.first->State != TreeEntry::Vectorize ||
3812           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3813               Data.first->getMainOp()) ||
3814           Data.first->isAltShuffle())
3815         Data.first->reorderOperands(Mask);
3816       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3817           Data.first->isAltShuffle()) {
3818         reorderScalars(Data.first->Scalars, Mask);
3819         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3820         if (Data.first->ReuseShuffleIndices.empty() &&
3821             !Data.first->ReorderIndices.empty() &&
3822             !Data.first->isAltShuffle()) {
3823           // Insert user node to the list to try to sink reordering deeper in
3824           // the graph.
3825           OrderedEntries.insert(Data.first);
3826         }
3827       } else {
3828         reorderOrder(Data.first->ReorderIndices, Mask);
3829       }
3830     }
3831   }
3832   // If the reordering is unnecessary, just remove the reorder.
3833   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3834       VectorizableTree.front()->ReuseShuffleIndices.empty())
3835     VectorizableTree.front()->ReorderIndices.clear();
3836 }
3837 
3838 void BoUpSLP::buildExternalUses(
3839     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3840   // Collect the values that we need to extract from the tree.
3841   for (auto &TEPtr : VectorizableTree) {
3842     TreeEntry *Entry = TEPtr.get();
3843 
3844     // No need to handle users of gathered values.
3845     if (Entry->State == TreeEntry::NeedToGather)
3846       continue;
3847 
3848     // For each lane:
3849     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3850       Value *Scalar = Entry->Scalars[Lane];
3851       int FoundLane = Entry->findLaneForValue(Scalar);
3852 
3853       // Check if the scalar is externally used as an extra arg.
3854       auto ExtI = ExternallyUsedValues.find(Scalar);
3855       if (ExtI != ExternallyUsedValues.end()) {
3856         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3857                           << Lane << " from " << *Scalar << ".\n");
3858         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3859       }
3860       for (User *U : Scalar->users()) {
3861         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3862 
3863         Instruction *UserInst = dyn_cast<Instruction>(U);
3864         if (!UserInst)
3865           continue;
3866 
3867         if (isDeleted(UserInst))
3868           continue;
3869 
3870         // Skip in-tree scalars that become vectors
3871         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3872           Value *UseScalar = UseEntry->Scalars[0];
3873           // Some in-tree scalars will remain as scalar in vectorized
3874           // instructions. If that is the case, the one in Lane 0 will
3875           // be used.
3876           if (UseScalar != U ||
3877               UseEntry->State == TreeEntry::ScatterVectorize ||
3878               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3879             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3880                               << ".\n");
3881             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3882             continue;
3883           }
3884         }
3885 
3886         // Ignore users in the user ignore list.
3887         if (is_contained(UserIgnoreList, UserInst))
3888           continue;
3889 
3890         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3891                           << Lane << " from " << *Scalar << ".\n");
3892         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3893       }
3894     }
3895   }
3896 }
3897 
3898 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3899                         ArrayRef<Value *> UserIgnoreLst) {
3900   deleteTree();
3901   UserIgnoreList = UserIgnoreLst;
3902   if (!allSameType(Roots))
3903     return;
3904   buildTree_rec(Roots, 0, EdgeInfo());
3905 }
3906 
3907 namespace {
3908 /// Tracks the state we can represent the loads in the given sequence.
3909 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3910 } // anonymous namespace
3911 
3912 /// Checks if the given array of loads can be represented as a vectorized,
3913 /// scatter or just simple gather.
3914 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3915                                     const TargetTransformInfo &TTI,
3916                                     const DataLayout &DL, ScalarEvolution &SE,
3917                                     SmallVectorImpl<unsigned> &Order,
3918                                     SmallVectorImpl<Value *> &PointerOps) {
3919   // Check that a vectorized load would load the same memory as a scalar
3920   // load. For example, we don't want to vectorize loads that are smaller
3921   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3922   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3923   // from such a struct, we read/write packed bits disagreeing with the
3924   // unvectorized version.
3925   Type *ScalarTy = VL0->getType();
3926 
3927   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3928     return LoadsState::Gather;
3929 
3930   // Make sure all loads in the bundle are simple - we can't vectorize
3931   // atomic or volatile loads.
3932   PointerOps.clear();
3933   PointerOps.resize(VL.size());
3934   auto *POIter = PointerOps.begin();
3935   for (Value *V : VL) {
3936     auto *L = cast<LoadInst>(V);
3937     if (!L->isSimple())
3938       return LoadsState::Gather;
3939     *POIter = L->getPointerOperand();
3940     ++POIter;
3941   }
3942 
3943   Order.clear();
3944   // Check the order of pointer operands.
3945   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3946     Value *Ptr0;
3947     Value *PtrN;
3948     if (Order.empty()) {
3949       Ptr0 = PointerOps.front();
3950       PtrN = PointerOps.back();
3951     } else {
3952       Ptr0 = PointerOps[Order.front()];
3953       PtrN = PointerOps[Order.back()];
3954     }
3955     Optional<int> Diff =
3956         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3957     // Check that the sorted loads are consecutive.
3958     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3959       return LoadsState::Vectorize;
3960     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3961     for (Value *V : VL)
3962       CommonAlignment =
3963           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3964     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3965                                 CommonAlignment))
3966       return LoadsState::ScatterVectorize;
3967   }
3968 
3969   return LoadsState::Gather;
3970 }
3971 
3972 /// \return true if the specified list of values has only one instruction that
3973 /// requires scheduling, false otherwise.
3974 #ifndef NDEBUG
3975 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3976   Value *NeedsScheduling = nullptr;
3977   for (Value *V : VL) {
3978     if (doesNotNeedToBeScheduled(V))
3979       continue;
3980     if (!NeedsScheduling) {
3981       NeedsScheduling = V;
3982       continue;
3983     }
3984     return false;
3985   }
3986   return NeedsScheduling;
3987 }
3988 #endif
3989 
3990 /// Generates key/subkey pair for the given value to provide effective sorting
3991 /// of the values and better detection of the vectorizable values sequences. The
3992 /// keys/subkeys can be used for better sorting of the values themselves (keys)
3993 /// and in values subgroups (subkeys).
3994 static std::pair<size_t, size_t> generateKeySubkey(
3995     Value *V, const TargetLibraryInfo *TLI,
3996     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
3997     bool AllowAlternate) {
3998   hash_code Key = hash_value(V->getValueID() + 2);
3999   hash_code SubKey = hash_value(0);
4000   // Sort the loads by the distance between the pointers.
4001   if (auto *LI = dyn_cast<LoadInst>(V)) {
4002     Key = hash_combine(hash_value(LI->getParent()), Key);
4003     if (LI->isSimple())
4004       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4005     else
4006       SubKey = hash_value(LI);
4007   } else if (isVectorLikeInstWithConstOps(V)) {
4008     // Sort extracts by the vector operands.
4009     if (isa<ExtractElementInst, UndefValue>(V))
4010       Key = hash_value(Value::UndefValueVal + 1);
4011     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4012       if (!isUndefVector(EI->getVectorOperand()) &&
4013           !isa<UndefValue>(EI->getIndexOperand()))
4014         SubKey = hash_value(EI->getVectorOperand());
4015     }
4016   } else if (auto *I = dyn_cast<Instruction>(V)) {
4017     // Sort other instructions just by the opcodes except for CMPInst.
4018     // For CMP also sort by the predicate kind.
4019     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4020         isValidForAlternation(I->getOpcode())) {
4021       if (AllowAlternate)
4022         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4023       else
4024         Key = hash_combine(hash_value(I->getOpcode()), Key);
4025       SubKey = hash_combine(
4026           hash_value(I->getOpcode()), hash_value(I->getType()),
4027           hash_value(isa<BinaryOperator>(I)
4028                          ? I->getType()
4029                          : cast<CastInst>(I)->getOperand(0)->getType()));
4030     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4031       CmpInst::Predicate Pred = CI->getPredicate();
4032       if (CI->isCommutative())
4033         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4034       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4035       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4036                             hash_value(SwapPred),
4037                             hash_value(CI->getOperand(0)->getType()));
4038     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4039       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4040       if (isTriviallyVectorizable(ID))
4041         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4042       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4043         SubKey = hash_combine(hash_value(I->getOpcode()),
4044                               hash_value(Call->getCalledFunction()));
4045       else
4046         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4047       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4048         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4049                               hash_value(Op.Tag), SubKey);
4050     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4051       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4052         SubKey = hash_value(Gep->getPointerOperand());
4053       else
4054         SubKey = hash_value(Gep);
4055     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4056                !isa<ConstantInt>(I->getOperand(1))) {
4057       // Do not try to vectorize instructions with potentially high cost.
4058       SubKey = hash_value(I);
4059     } else {
4060       SubKey = hash_value(I->getOpcode());
4061     }
4062     Key = hash_combine(hash_value(I->getParent()), Key);
4063   }
4064   return std::make_pair(Key, SubKey);
4065 }
4066 
4067 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4068                             const EdgeInfo &UserTreeIdx) {
4069   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4070 
4071   SmallVector<int> ReuseShuffleIndicies;
4072   SmallVector<Value *> UniqueValues;
4073   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4074                                 &UserTreeIdx,
4075                                 this](const InstructionsState &S) {
4076     // Check that every instruction appears once in this bundle.
4077     DenseMap<Value *, unsigned> UniquePositions;
4078     for (Value *V : VL) {
4079       if (isConstant(V)) {
4080         ReuseShuffleIndicies.emplace_back(
4081             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4082         UniqueValues.emplace_back(V);
4083         continue;
4084       }
4085       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4086       ReuseShuffleIndicies.emplace_back(Res.first->second);
4087       if (Res.second)
4088         UniqueValues.emplace_back(V);
4089     }
4090     size_t NumUniqueScalarValues = UniqueValues.size();
4091     if (NumUniqueScalarValues == VL.size()) {
4092       ReuseShuffleIndicies.clear();
4093     } else {
4094       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4095       if (NumUniqueScalarValues <= 1 ||
4096           (UniquePositions.size() == 1 && all_of(UniqueValues,
4097                                                  [](Value *V) {
4098                                                    return isa<UndefValue>(V) ||
4099                                                           !isConstant(V);
4100                                                  })) ||
4101           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4102         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4103         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4104         return false;
4105       }
4106       VL = UniqueValues;
4107     }
4108     return true;
4109   };
4110 
4111   InstructionsState S = getSameOpcode(VL);
4112   if (Depth == RecursionMaxDepth) {
4113     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4114     if (TryToFindDuplicates(S))
4115       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4116                    ReuseShuffleIndicies);
4117     return;
4118   }
4119 
4120   // Don't handle scalable vectors
4121   if (S.getOpcode() == Instruction::ExtractElement &&
4122       isa<ScalableVectorType>(
4123           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4124     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4125     if (TryToFindDuplicates(S))
4126       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4127                    ReuseShuffleIndicies);
4128     return;
4129   }
4130 
4131   // Don't handle vectors.
4132   if (S.OpValue->getType()->isVectorTy() &&
4133       !isa<InsertElementInst>(S.OpValue)) {
4134     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4135     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4136     return;
4137   }
4138 
4139   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4140     if (SI->getValueOperand()->getType()->isVectorTy()) {
4141       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4142       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4143       return;
4144     }
4145 
4146   // If all of the operands are identical or constant we have a simple solution.
4147   // If we deal with insert/extract instructions, they all must have constant
4148   // indices, otherwise we should gather them, not try to vectorize.
4149   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4150       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4151        !all_of(VL, isVectorLikeInstWithConstOps))) {
4152     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4153     if (TryToFindDuplicates(S))
4154       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4155                    ReuseShuffleIndicies);
4156     return;
4157   }
4158 
4159   // We now know that this is a vector of instructions of the same type from
4160   // the same block.
4161 
4162   // Don't vectorize ephemeral values.
4163   for (Value *V : VL) {
4164     if (EphValues.count(V)) {
4165       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4166                         << ") is ephemeral.\n");
4167       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4168       return;
4169     }
4170   }
4171 
4172   // Check if this is a duplicate of another entry.
4173   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4174     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4175     if (!E->isSame(VL)) {
4176       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4177       if (TryToFindDuplicates(S))
4178         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4179                      ReuseShuffleIndicies);
4180       return;
4181     }
4182     // Record the reuse of the tree node.  FIXME, currently this is only used to
4183     // properly draw the graph rather than for the actual vectorization.
4184     E->UserTreeIndices.push_back(UserTreeIdx);
4185     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4186                       << ".\n");
4187     return;
4188   }
4189 
4190   // Check that none of the instructions in the bundle are already in the tree.
4191   for (Value *V : VL) {
4192     auto *I = dyn_cast<Instruction>(V);
4193     if (!I)
4194       continue;
4195     if (getTreeEntry(I)) {
4196       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4197                         << ") is already in tree.\n");
4198       if (TryToFindDuplicates(S))
4199         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4200                      ReuseShuffleIndicies);
4201       return;
4202     }
4203   }
4204 
4205   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4206   for (Value *V : VL) {
4207     if (is_contained(UserIgnoreList, V)) {
4208       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4209       if (TryToFindDuplicates(S))
4210         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4211                      ReuseShuffleIndicies);
4212       return;
4213     }
4214   }
4215 
4216   // Check that all of the users of the scalars that we want to vectorize are
4217   // schedulable.
4218   auto *VL0 = cast<Instruction>(S.OpValue);
4219   BasicBlock *BB = VL0->getParent();
4220 
4221   if (!DT->isReachableFromEntry(BB)) {
4222     // Don't go into unreachable blocks. They may contain instructions with
4223     // dependency cycles which confuse the final scheduling.
4224     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4225     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4226     return;
4227   }
4228 
4229   // Check that every instruction appears once in this bundle.
4230   if (!TryToFindDuplicates(S))
4231     return;
4232 
4233   auto &BSRef = BlocksSchedules[BB];
4234   if (!BSRef)
4235     BSRef = std::make_unique<BlockScheduling>(BB);
4236 
4237   BlockScheduling &BS = *BSRef;
4238 
4239   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4240 #ifdef EXPENSIVE_CHECKS
4241   // Make sure we didn't break any internal invariants
4242   BS.verify();
4243 #endif
4244   if (!Bundle) {
4245     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4246     assert((!BS.getScheduleData(VL0) ||
4247             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4248            "tryScheduleBundle should cancelScheduling on failure");
4249     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4250                  ReuseShuffleIndicies);
4251     return;
4252   }
4253   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4254 
4255   unsigned ShuffleOrOp = S.isAltShuffle() ?
4256                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4257   switch (ShuffleOrOp) {
4258     case Instruction::PHI: {
4259       auto *PH = cast<PHINode>(VL0);
4260 
4261       // Check for terminator values (e.g. invoke).
4262       for (Value *V : VL)
4263         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4264           Instruction *Term = dyn_cast<Instruction>(Incoming);
4265           if (Term && Term->isTerminator()) {
4266             LLVM_DEBUG(dbgs()
4267                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4268             BS.cancelScheduling(VL, VL0);
4269             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4270                          ReuseShuffleIndicies);
4271             return;
4272           }
4273         }
4274 
4275       TreeEntry *TE =
4276           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4277       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4278 
4279       // Keeps the reordered operands to avoid code duplication.
4280       SmallVector<ValueList, 2> OperandsVec;
4281       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4282         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4283           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4284           TE->setOperand(I, Operands);
4285           OperandsVec.push_back(Operands);
4286           continue;
4287         }
4288         ValueList Operands;
4289         // Prepare the operand vector.
4290         for (Value *V : VL)
4291           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4292               PH->getIncomingBlock(I)));
4293         TE->setOperand(I, Operands);
4294         OperandsVec.push_back(Operands);
4295       }
4296       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4297         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4298       return;
4299     }
4300     case Instruction::ExtractValue:
4301     case Instruction::ExtractElement: {
4302       OrdersType CurrentOrder;
4303       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4304       if (Reuse) {
4305         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4306         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4307                      ReuseShuffleIndicies);
4308         // This is a special case, as it does not gather, but at the same time
4309         // we are not extending buildTree_rec() towards the operands.
4310         ValueList Op0;
4311         Op0.assign(VL.size(), VL0->getOperand(0));
4312         VectorizableTree.back()->setOperand(0, Op0);
4313         return;
4314       }
4315       if (!CurrentOrder.empty()) {
4316         LLVM_DEBUG({
4317           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4318                     "with order";
4319           for (unsigned Idx : CurrentOrder)
4320             dbgs() << " " << Idx;
4321           dbgs() << "\n";
4322         });
4323         fixupOrderingIndices(CurrentOrder);
4324         // Insert new order with initial value 0, if it does not exist,
4325         // otherwise return the iterator to the existing one.
4326         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4327                      ReuseShuffleIndicies, CurrentOrder);
4328         // This is a special case, as it does not gather, but at the same time
4329         // we are not extending buildTree_rec() towards the operands.
4330         ValueList Op0;
4331         Op0.assign(VL.size(), VL0->getOperand(0));
4332         VectorizableTree.back()->setOperand(0, Op0);
4333         return;
4334       }
4335       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4336       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4337                    ReuseShuffleIndicies);
4338       BS.cancelScheduling(VL, VL0);
4339       return;
4340     }
4341     case Instruction::InsertElement: {
4342       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4343 
4344       // Check that we have a buildvector and not a shuffle of 2 or more
4345       // different vectors.
4346       ValueSet SourceVectors;
4347       for (Value *V : VL) {
4348         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4349         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4350       }
4351 
4352       if (count_if(VL, [&SourceVectors](Value *V) {
4353             return !SourceVectors.contains(V);
4354           }) >= 2) {
4355         // Found 2nd source vector - cancel.
4356         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4357                              "different source vectors.\n");
4358         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4359         BS.cancelScheduling(VL, VL0);
4360         return;
4361       }
4362 
4363       auto OrdCompare = [](const std::pair<int, int> &P1,
4364                            const std::pair<int, int> &P2) {
4365         return P1.first > P2.first;
4366       };
4367       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4368                     decltype(OrdCompare)>
4369           Indices(OrdCompare);
4370       for (int I = 0, E = VL.size(); I < E; ++I) {
4371         unsigned Idx = *getInsertIndex(VL[I]);
4372         Indices.emplace(Idx, I);
4373       }
4374       OrdersType CurrentOrder(VL.size(), VL.size());
4375       bool IsIdentity = true;
4376       for (int I = 0, E = VL.size(); I < E; ++I) {
4377         CurrentOrder[Indices.top().second] = I;
4378         IsIdentity &= Indices.top().second == I;
4379         Indices.pop();
4380       }
4381       if (IsIdentity)
4382         CurrentOrder.clear();
4383       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4384                                    None, CurrentOrder);
4385       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4386 
4387       constexpr int NumOps = 2;
4388       ValueList VectorOperands[NumOps];
4389       for (int I = 0; I < NumOps; ++I) {
4390         for (Value *V : VL)
4391           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4392 
4393         TE->setOperand(I, VectorOperands[I]);
4394       }
4395       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4396       return;
4397     }
4398     case Instruction::Load: {
4399       // Check that a vectorized load would load the same memory as a scalar
4400       // load. For example, we don't want to vectorize loads that are smaller
4401       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4402       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4403       // from such a struct, we read/write packed bits disagreeing with the
4404       // unvectorized version.
4405       SmallVector<Value *> PointerOps;
4406       OrdersType CurrentOrder;
4407       TreeEntry *TE = nullptr;
4408       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4409                                 PointerOps)) {
4410       case LoadsState::Vectorize:
4411         if (CurrentOrder.empty()) {
4412           // Original loads are consecutive and does not require reordering.
4413           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4414                             ReuseShuffleIndicies);
4415           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4416         } else {
4417           fixupOrderingIndices(CurrentOrder);
4418           // Need to reorder.
4419           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4420                             ReuseShuffleIndicies, CurrentOrder);
4421           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4422         }
4423         TE->setOperandsInOrder();
4424         break;
4425       case LoadsState::ScatterVectorize:
4426         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4427         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4428                           UserTreeIdx, ReuseShuffleIndicies);
4429         TE->setOperandsInOrder();
4430         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4431         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4432         break;
4433       case LoadsState::Gather:
4434         BS.cancelScheduling(VL, VL0);
4435         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4436                      ReuseShuffleIndicies);
4437 #ifndef NDEBUG
4438         Type *ScalarTy = VL0->getType();
4439         if (DL->getTypeSizeInBits(ScalarTy) !=
4440             DL->getTypeAllocSizeInBits(ScalarTy))
4441           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4442         else if (any_of(VL, [](Value *V) {
4443                    return !cast<LoadInst>(V)->isSimple();
4444                  }))
4445           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4446         else
4447           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4448 #endif // NDEBUG
4449         break;
4450       }
4451       return;
4452     }
4453     case Instruction::ZExt:
4454     case Instruction::SExt:
4455     case Instruction::FPToUI:
4456     case Instruction::FPToSI:
4457     case Instruction::FPExt:
4458     case Instruction::PtrToInt:
4459     case Instruction::IntToPtr:
4460     case Instruction::SIToFP:
4461     case Instruction::UIToFP:
4462     case Instruction::Trunc:
4463     case Instruction::FPTrunc:
4464     case Instruction::BitCast: {
4465       Type *SrcTy = VL0->getOperand(0)->getType();
4466       for (Value *V : VL) {
4467         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4468         if (Ty != SrcTy || !isValidElementType(Ty)) {
4469           BS.cancelScheduling(VL, VL0);
4470           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4471                        ReuseShuffleIndicies);
4472           LLVM_DEBUG(dbgs()
4473                      << "SLP: Gathering casts with different src types.\n");
4474           return;
4475         }
4476       }
4477       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4478                                    ReuseShuffleIndicies);
4479       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4480 
4481       TE->setOperandsInOrder();
4482       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4483         ValueList Operands;
4484         // Prepare the operand vector.
4485         for (Value *V : VL)
4486           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4487 
4488         buildTree_rec(Operands, Depth + 1, {TE, i});
4489       }
4490       return;
4491     }
4492     case Instruction::ICmp:
4493     case Instruction::FCmp: {
4494       // Check that all of the compares have the same predicate.
4495       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4496       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4497       Type *ComparedTy = VL0->getOperand(0)->getType();
4498       for (Value *V : VL) {
4499         CmpInst *Cmp = cast<CmpInst>(V);
4500         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4501             Cmp->getOperand(0)->getType() != ComparedTy) {
4502           BS.cancelScheduling(VL, VL0);
4503           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4504                        ReuseShuffleIndicies);
4505           LLVM_DEBUG(dbgs()
4506                      << "SLP: Gathering cmp with different predicate.\n");
4507           return;
4508         }
4509       }
4510 
4511       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4512                                    ReuseShuffleIndicies);
4513       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4514 
4515       ValueList Left, Right;
4516       if (cast<CmpInst>(VL0)->isCommutative()) {
4517         // Commutative predicate - collect + sort operands of the instructions
4518         // so that each side is more likely to have the same opcode.
4519         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4520         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4521       } else {
4522         // Collect operands - commute if it uses the swapped predicate.
4523         for (Value *V : VL) {
4524           auto *Cmp = cast<CmpInst>(V);
4525           Value *LHS = Cmp->getOperand(0);
4526           Value *RHS = Cmp->getOperand(1);
4527           if (Cmp->getPredicate() != P0)
4528             std::swap(LHS, RHS);
4529           Left.push_back(LHS);
4530           Right.push_back(RHS);
4531         }
4532       }
4533       TE->setOperand(0, Left);
4534       TE->setOperand(1, Right);
4535       buildTree_rec(Left, Depth + 1, {TE, 0});
4536       buildTree_rec(Right, Depth + 1, {TE, 1});
4537       return;
4538     }
4539     case Instruction::Select:
4540     case Instruction::FNeg:
4541     case Instruction::Add:
4542     case Instruction::FAdd:
4543     case Instruction::Sub:
4544     case Instruction::FSub:
4545     case Instruction::Mul:
4546     case Instruction::FMul:
4547     case Instruction::UDiv:
4548     case Instruction::SDiv:
4549     case Instruction::FDiv:
4550     case Instruction::URem:
4551     case Instruction::SRem:
4552     case Instruction::FRem:
4553     case Instruction::Shl:
4554     case Instruction::LShr:
4555     case Instruction::AShr:
4556     case Instruction::And:
4557     case Instruction::Or:
4558     case Instruction::Xor: {
4559       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4560                                    ReuseShuffleIndicies);
4561       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4562 
4563       // Sort operands of the instructions so that each side is more likely to
4564       // have the same opcode.
4565       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4566         ValueList Left, Right;
4567         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4568         TE->setOperand(0, Left);
4569         TE->setOperand(1, Right);
4570         buildTree_rec(Left, Depth + 1, {TE, 0});
4571         buildTree_rec(Right, Depth + 1, {TE, 1});
4572         return;
4573       }
4574 
4575       TE->setOperandsInOrder();
4576       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4577         ValueList Operands;
4578         // Prepare the operand vector.
4579         for (Value *V : VL)
4580           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4581 
4582         buildTree_rec(Operands, Depth + 1, {TE, i});
4583       }
4584       return;
4585     }
4586     case Instruction::GetElementPtr: {
4587       // We don't combine GEPs with complicated (nested) indexing.
4588       for (Value *V : VL) {
4589         if (cast<Instruction>(V)->getNumOperands() != 2) {
4590           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4591           BS.cancelScheduling(VL, VL0);
4592           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4593                        ReuseShuffleIndicies);
4594           return;
4595         }
4596       }
4597 
4598       // We can't combine several GEPs into one vector if they operate on
4599       // different types.
4600       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4601       for (Value *V : VL) {
4602         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4603         if (Ty0 != CurTy) {
4604           LLVM_DEBUG(dbgs()
4605                      << "SLP: not-vectorizable GEP (different types).\n");
4606           BS.cancelScheduling(VL, VL0);
4607           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4608                        ReuseShuffleIndicies);
4609           return;
4610         }
4611       }
4612 
4613       // We don't combine GEPs with non-constant indexes.
4614       Type *Ty1 = VL0->getOperand(1)->getType();
4615       for (Value *V : VL) {
4616         auto Op = cast<Instruction>(V)->getOperand(1);
4617         if (!isa<ConstantInt>(Op) ||
4618             (Op->getType() != Ty1 &&
4619              Op->getType()->getScalarSizeInBits() >
4620                  DL->getIndexSizeInBits(
4621                      V->getType()->getPointerAddressSpace()))) {
4622           LLVM_DEBUG(dbgs()
4623                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4624           BS.cancelScheduling(VL, VL0);
4625           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4626                        ReuseShuffleIndicies);
4627           return;
4628         }
4629       }
4630 
4631       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4632                                    ReuseShuffleIndicies);
4633       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4634       SmallVector<ValueList, 2> Operands(2);
4635       // Prepare the operand vector for pointer operands.
4636       for (Value *V : VL)
4637         Operands.front().push_back(
4638             cast<GetElementPtrInst>(V)->getPointerOperand());
4639       TE->setOperand(0, Operands.front());
4640       // Need to cast all indices to the same type before vectorization to
4641       // avoid crash.
4642       // Required to be able to find correct matches between different gather
4643       // nodes and reuse the vectorized values rather than trying to gather them
4644       // again.
4645       int IndexIdx = 1;
4646       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4647       Type *Ty = all_of(VL,
4648                         [VL0Ty, IndexIdx](Value *V) {
4649                           return VL0Ty == cast<GetElementPtrInst>(V)
4650                                               ->getOperand(IndexIdx)
4651                                               ->getType();
4652                         })
4653                      ? VL0Ty
4654                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4655                                             ->getPointerOperandType()
4656                                             ->getScalarType());
4657       // Prepare the operand vector.
4658       for (Value *V : VL) {
4659         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4660         auto *CI = cast<ConstantInt>(Op);
4661         Operands.back().push_back(ConstantExpr::getIntegerCast(
4662             CI, Ty, CI->getValue().isSignBitSet()));
4663       }
4664       TE->setOperand(IndexIdx, Operands.back());
4665 
4666       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4667         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4668       return;
4669     }
4670     case Instruction::Store: {
4671       // Check if the stores are consecutive or if we need to swizzle them.
4672       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4673       // Avoid types that are padded when being allocated as scalars, while
4674       // being packed together in a vector (such as i1).
4675       if (DL->getTypeSizeInBits(ScalarTy) !=
4676           DL->getTypeAllocSizeInBits(ScalarTy)) {
4677         BS.cancelScheduling(VL, VL0);
4678         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4679                      ReuseShuffleIndicies);
4680         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4681         return;
4682       }
4683       // Make sure all stores in the bundle are simple - we can't vectorize
4684       // atomic or volatile stores.
4685       SmallVector<Value *, 4> PointerOps(VL.size());
4686       ValueList Operands(VL.size());
4687       auto POIter = PointerOps.begin();
4688       auto OIter = Operands.begin();
4689       for (Value *V : VL) {
4690         auto *SI = cast<StoreInst>(V);
4691         if (!SI->isSimple()) {
4692           BS.cancelScheduling(VL, VL0);
4693           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4694                        ReuseShuffleIndicies);
4695           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4696           return;
4697         }
4698         *POIter = SI->getPointerOperand();
4699         *OIter = SI->getValueOperand();
4700         ++POIter;
4701         ++OIter;
4702       }
4703 
4704       OrdersType CurrentOrder;
4705       // Check the order of pointer operands.
4706       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4707         Value *Ptr0;
4708         Value *PtrN;
4709         if (CurrentOrder.empty()) {
4710           Ptr0 = PointerOps.front();
4711           PtrN = PointerOps.back();
4712         } else {
4713           Ptr0 = PointerOps[CurrentOrder.front()];
4714           PtrN = PointerOps[CurrentOrder.back()];
4715         }
4716         Optional<int> Dist =
4717             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4718         // Check that the sorted pointer operands are consecutive.
4719         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4720           if (CurrentOrder.empty()) {
4721             // Original stores are consecutive and does not require reordering.
4722             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4723                                          UserTreeIdx, ReuseShuffleIndicies);
4724             TE->setOperandsInOrder();
4725             buildTree_rec(Operands, Depth + 1, {TE, 0});
4726             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4727           } else {
4728             fixupOrderingIndices(CurrentOrder);
4729             TreeEntry *TE =
4730                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4731                              ReuseShuffleIndicies, CurrentOrder);
4732             TE->setOperandsInOrder();
4733             buildTree_rec(Operands, Depth + 1, {TE, 0});
4734             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4735           }
4736           return;
4737         }
4738       }
4739 
4740       BS.cancelScheduling(VL, VL0);
4741       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4742                    ReuseShuffleIndicies);
4743       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4744       return;
4745     }
4746     case Instruction::Call: {
4747       // Check if the calls are all to the same vectorizable intrinsic or
4748       // library function.
4749       CallInst *CI = cast<CallInst>(VL0);
4750       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4751 
4752       VFShape Shape = VFShape::get(
4753           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4754           false /*HasGlobalPred*/);
4755       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4756 
4757       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4758         BS.cancelScheduling(VL, VL0);
4759         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4760                      ReuseShuffleIndicies);
4761         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4762         return;
4763       }
4764       Function *F = CI->getCalledFunction();
4765       unsigned NumArgs = CI->arg_size();
4766       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4767       for (unsigned j = 0; j != NumArgs; ++j)
4768         if (hasVectorInstrinsicScalarOpd(ID, j))
4769           ScalarArgs[j] = CI->getArgOperand(j);
4770       for (Value *V : VL) {
4771         CallInst *CI2 = dyn_cast<CallInst>(V);
4772         if (!CI2 || CI2->getCalledFunction() != F ||
4773             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4774             (VecFunc &&
4775              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4776             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4777           BS.cancelScheduling(VL, VL0);
4778           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4779                        ReuseShuffleIndicies);
4780           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4781                             << "\n");
4782           return;
4783         }
4784         // Some intrinsics have scalar arguments and should be same in order for
4785         // them to be vectorized.
4786         for (unsigned j = 0; j != NumArgs; ++j) {
4787           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4788             Value *A1J = CI2->getArgOperand(j);
4789             if (ScalarArgs[j] != A1J) {
4790               BS.cancelScheduling(VL, VL0);
4791               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4792                            ReuseShuffleIndicies);
4793               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4794                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4795                                 << "\n");
4796               return;
4797             }
4798           }
4799         }
4800         // Verify that the bundle operands are identical between the two calls.
4801         if (CI->hasOperandBundles() &&
4802             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4803                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4804                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4805           BS.cancelScheduling(VL, VL0);
4806           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4807                        ReuseShuffleIndicies);
4808           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4809                             << *CI << "!=" << *V << '\n');
4810           return;
4811         }
4812       }
4813 
4814       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4815                                    ReuseShuffleIndicies);
4816       TE->setOperandsInOrder();
4817       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4818         // For scalar operands no need to to create an entry since no need to
4819         // vectorize it.
4820         if (hasVectorInstrinsicScalarOpd(ID, i))
4821           continue;
4822         ValueList Operands;
4823         // Prepare the operand vector.
4824         for (Value *V : VL) {
4825           auto *CI2 = cast<CallInst>(V);
4826           Operands.push_back(CI2->getArgOperand(i));
4827         }
4828         buildTree_rec(Operands, Depth + 1, {TE, i});
4829       }
4830       return;
4831     }
4832     case Instruction::ShuffleVector: {
4833       // If this is not an alternate sequence of opcode like add-sub
4834       // then do not vectorize this instruction.
4835       if (!S.isAltShuffle()) {
4836         BS.cancelScheduling(VL, VL0);
4837         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4838                      ReuseShuffleIndicies);
4839         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4840         return;
4841       }
4842       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4843                                    ReuseShuffleIndicies);
4844       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4845 
4846       // Reorder operands if reordering would enable vectorization.
4847       auto *CI = dyn_cast<CmpInst>(VL0);
4848       if (isa<BinaryOperator>(VL0) || CI) {
4849         ValueList Left, Right;
4850         if (!CI || all_of(VL, [](Value *V) {
4851               return cast<CmpInst>(V)->isCommutative();
4852             })) {
4853           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4854         } else {
4855           CmpInst::Predicate P0 = CI->getPredicate();
4856           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4857           assert(P0 != AltP0 &&
4858                  "Expected different main/alternate predicates.");
4859           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4860           Value *BaseOp0 = VL0->getOperand(0);
4861           Value *BaseOp1 = VL0->getOperand(1);
4862           // Collect operands - commute if it uses the swapped predicate or
4863           // alternate operation.
4864           for (Value *V : VL) {
4865             auto *Cmp = cast<CmpInst>(V);
4866             Value *LHS = Cmp->getOperand(0);
4867             Value *RHS = Cmp->getOperand(1);
4868             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4869             if (P0 == AltP0Swapped) {
4870               if (CI != Cmp && S.AltOp != Cmp &&
4871                   ((P0 == CurrentPred &&
4872                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4873                    (AltP0 == CurrentPred &&
4874                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4875                 std::swap(LHS, RHS);
4876             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4877               std::swap(LHS, RHS);
4878             }
4879             Left.push_back(LHS);
4880             Right.push_back(RHS);
4881           }
4882         }
4883         TE->setOperand(0, Left);
4884         TE->setOperand(1, Right);
4885         buildTree_rec(Left, Depth + 1, {TE, 0});
4886         buildTree_rec(Right, Depth + 1, {TE, 1});
4887         return;
4888       }
4889 
4890       TE->setOperandsInOrder();
4891       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4892         ValueList Operands;
4893         // Prepare the operand vector.
4894         for (Value *V : VL)
4895           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4896 
4897         buildTree_rec(Operands, Depth + 1, {TE, i});
4898       }
4899       return;
4900     }
4901     default:
4902       BS.cancelScheduling(VL, VL0);
4903       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4904                    ReuseShuffleIndicies);
4905       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4906       return;
4907   }
4908 }
4909 
4910 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4911   unsigned N = 1;
4912   Type *EltTy = T;
4913 
4914   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4915          isa<VectorType>(EltTy)) {
4916     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4917       // Check that struct is homogeneous.
4918       for (const auto *Ty : ST->elements())
4919         if (Ty != *ST->element_begin())
4920           return 0;
4921       N *= ST->getNumElements();
4922       EltTy = *ST->element_begin();
4923     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4924       N *= AT->getNumElements();
4925       EltTy = AT->getElementType();
4926     } else {
4927       auto *VT = cast<FixedVectorType>(EltTy);
4928       N *= VT->getNumElements();
4929       EltTy = VT->getElementType();
4930     }
4931   }
4932 
4933   if (!isValidElementType(EltTy))
4934     return 0;
4935   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4936   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4937     return 0;
4938   return N;
4939 }
4940 
4941 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4942                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4943   const auto *It = find_if(VL, [](Value *V) {
4944     return isa<ExtractElementInst, ExtractValueInst>(V);
4945   });
4946   assert(It != VL.end() && "Expected at least one extract instruction.");
4947   auto *E0 = cast<Instruction>(*It);
4948   assert(all_of(VL,
4949                 [](Value *V) {
4950                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4951                       V);
4952                 }) &&
4953          "Invalid opcode");
4954   // Check if all of the extracts come from the same vector and from the
4955   // correct offset.
4956   Value *Vec = E0->getOperand(0);
4957 
4958   CurrentOrder.clear();
4959 
4960   // We have to extract from a vector/aggregate with the same number of elements.
4961   unsigned NElts;
4962   if (E0->getOpcode() == Instruction::ExtractValue) {
4963     const DataLayout &DL = E0->getModule()->getDataLayout();
4964     NElts = canMapToVector(Vec->getType(), DL);
4965     if (!NElts)
4966       return false;
4967     // Check if load can be rewritten as load of vector.
4968     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4969     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4970       return false;
4971   } else {
4972     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4973   }
4974 
4975   if (NElts != VL.size())
4976     return false;
4977 
4978   // Check that all of the indices extract from the correct offset.
4979   bool ShouldKeepOrder = true;
4980   unsigned E = VL.size();
4981   // Assign to all items the initial value E + 1 so we can check if the extract
4982   // instruction index was used already.
4983   // Also, later we can check that all the indices are used and we have a
4984   // consecutive access in the extract instructions, by checking that no
4985   // element of CurrentOrder still has value E + 1.
4986   CurrentOrder.assign(E, E);
4987   unsigned I = 0;
4988   for (; I < E; ++I) {
4989     auto *Inst = dyn_cast<Instruction>(VL[I]);
4990     if (!Inst)
4991       continue;
4992     if (Inst->getOperand(0) != Vec)
4993       break;
4994     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4995       if (isa<UndefValue>(EE->getIndexOperand()))
4996         continue;
4997     Optional<unsigned> Idx = getExtractIndex(Inst);
4998     if (!Idx)
4999       break;
5000     const unsigned ExtIdx = *Idx;
5001     if (ExtIdx != I) {
5002       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5003         break;
5004       ShouldKeepOrder = false;
5005       CurrentOrder[ExtIdx] = I;
5006     } else {
5007       if (CurrentOrder[I] != E)
5008         break;
5009       CurrentOrder[I] = I;
5010     }
5011   }
5012   if (I < E) {
5013     CurrentOrder.clear();
5014     return false;
5015   }
5016   if (ShouldKeepOrder)
5017     CurrentOrder.clear();
5018 
5019   return ShouldKeepOrder;
5020 }
5021 
5022 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5023                                     ArrayRef<Value *> VectorizedVals) const {
5024   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5025          all_of(I->users(), [this](User *U) {
5026            return ScalarToTreeEntry.count(U) > 0 ||
5027                   isVectorLikeInstWithConstOps(U) ||
5028                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5029          });
5030 }
5031 
5032 static std::pair<InstructionCost, InstructionCost>
5033 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5034                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5035   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5036 
5037   // Calculate the cost of the scalar and vector calls.
5038   SmallVector<Type *, 4> VecTys;
5039   for (Use &Arg : CI->args())
5040     VecTys.push_back(
5041         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5042   FastMathFlags FMF;
5043   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5044     FMF = FPCI->getFastMathFlags();
5045   SmallVector<const Value *> Arguments(CI->args());
5046   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5047                                     dyn_cast<IntrinsicInst>(CI));
5048   auto IntrinsicCost =
5049     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5050 
5051   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5052                                      VecTy->getNumElements())),
5053                             false /*HasGlobalPred*/);
5054   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5055   auto LibCost = IntrinsicCost;
5056   if (!CI->isNoBuiltin() && VecFunc) {
5057     // Calculate the cost of the vector library call.
5058     // If the corresponding vector call is cheaper, return its cost.
5059     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5060                                     TTI::TCK_RecipThroughput);
5061   }
5062   return {IntrinsicCost, LibCost};
5063 }
5064 
5065 /// Compute the cost of creating a vector of type \p VecTy containing the
5066 /// extracted values from \p VL.
5067 static InstructionCost
5068 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5069                    TargetTransformInfo::ShuffleKind ShuffleKind,
5070                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5071   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5072 
5073   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5074       VecTy->getNumElements() < NumOfParts)
5075     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5076 
5077   bool AllConsecutive = true;
5078   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5079   unsigned Idx = -1;
5080   InstructionCost Cost = 0;
5081 
5082   // Process extracts in blocks of EltsPerVector to check if the source vector
5083   // operand can be re-used directly. If not, add the cost of creating a shuffle
5084   // to extract the values into a vector register.
5085   for (auto *V : VL) {
5086     ++Idx;
5087 
5088     // Need to exclude undefs from analysis.
5089     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5090       continue;
5091 
5092     // Reached the start of a new vector registers.
5093     if (Idx % EltsPerVector == 0) {
5094       AllConsecutive = true;
5095       continue;
5096     }
5097 
5098     // Check all extracts for a vector register on the target directly
5099     // extract values in order.
5100     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5101     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5102       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5103       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5104                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5105     }
5106 
5107     if (AllConsecutive)
5108       continue;
5109 
5110     // Skip all indices, except for the last index per vector block.
5111     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5112       continue;
5113 
5114     // If we have a series of extracts which are not consecutive and hence
5115     // cannot re-use the source vector register directly, compute the shuffle
5116     // cost to extract the a vector with EltsPerVector elements.
5117     Cost += TTI.getShuffleCost(
5118         TargetTransformInfo::SK_PermuteSingleSrc,
5119         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5120   }
5121   return Cost;
5122 }
5123 
5124 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5125 /// operations operands.
5126 static void
5127 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5128                       ArrayRef<int> ReusesIndices,
5129                       const function_ref<bool(Instruction *)> IsAltOp,
5130                       SmallVectorImpl<int> &Mask,
5131                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5132                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5133   unsigned Sz = VL.size();
5134   Mask.assign(Sz, UndefMaskElem);
5135   SmallVector<int> OrderMask;
5136   if (!ReorderIndices.empty())
5137     inversePermutation(ReorderIndices, OrderMask);
5138   for (unsigned I = 0; I < Sz; ++I) {
5139     unsigned Idx = I;
5140     if (!ReorderIndices.empty())
5141       Idx = OrderMask[I];
5142     auto *OpInst = cast<Instruction>(VL[Idx]);
5143     if (IsAltOp(OpInst)) {
5144       Mask[I] = Sz + Idx;
5145       if (AltScalars)
5146         AltScalars->push_back(OpInst);
5147     } else {
5148       Mask[I] = Idx;
5149       if (OpScalars)
5150         OpScalars->push_back(OpInst);
5151     }
5152   }
5153   if (!ReusesIndices.empty()) {
5154     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5155     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5156       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5157     });
5158     Mask.swap(NewMask);
5159   }
5160 }
5161 
5162 /// Checks if the specified instruction \p I is an alternate operation for the
5163 /// given \p MainOp and \p AltOp instructions.
5164 static bool isAlternateInstruction(const Instruction *I,
5165                                    const Instruction *MainOp,
5166                                    const Instruction *AltOp) {
5167   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5168     auto *AltCI0 = cast<CmpInst>(AltOp);
5169     auto *CI = cast<CmpInst>(I);
5170     CmpInst::Predicate P0 = CI0->getPredicate();
5171     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5172     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5173     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5174     CmpInst::Predicate CurrentPred = CI->getPredicate();
5175     if (P0 == AltP0Swapped)
5176       return I == AltCI0 ||
5177              (I != MainOp &&
5178               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5179                                    CI->getOperand(0), CI->getOperand(1)));
5180     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5181   }
5182   return I->getOpcode() == AltOp->getOpcode();
5183 }
5184 
5185 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5186                                       ArrayRef<Value *> VectorizedVals) {
5187   ArrayRef<Value*> VL = E->Scalars;
5188 
5189   Type *ScalarTy = VL[0]->getType();
5190   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5191     ScalarTy = SI->getValueOperand()->getType();
5192   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5193     ScalarTy = CI->getOperand(0)->getType();
5194   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5195     ScalarTy = IE->getOperand(1)->getType();
5196   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5197   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5198 
5199   // If we have computed a smaller type for the expression, update VecTy so
5200   // that the costs will be accurate.
5201   if (MinBWs.count(VL[0]))
5202     VecTy = FixedVectorType::get(
5203         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5204   unsigned EntryVF = E->getVectorFactor();
5205   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5206 
5207   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5208   // FIXME: it tries to fix a problem with MSVC buildbots.
5209   TargetTransformInfo &TTIRef = *TTI;
5210   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5211                                VectorizedVals, E](InstructionCost &Cost) {
5212     DenseMap<Value *, int> ExtractVectorsTys;
5213     SmallPtrSet<Value *, 4> CheckedExtracts;
5214     for (auto *V : VL) {
5215       if (isa<UndefValue>(V))
5216         continue;
5217       // If all users of instruction are going to be vectorized and this
5218       // instruction itself is not going to be vectorized, consider this
5219       // instruction as dead and remove its cost from the final cost of the
5220       // vectorized tree.
5221       // Also, avoid adjusting the cost for extractelements with multiple uses
5222       // in different graph entries.
5223       const TreeEntry *VE = getTreeEntry(V);
5224       if (!CheckedExtracts.insert(V).second ||
5225           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5226           (VE && VE != E))
5227         continue;
5228       auto *EE = cast<ExtractElementInst>(V);
5229       Optional<unsigned> EEIdx = getExtractIndex(EE);
5230       if (!EEIdx)
5231         continue;
5232       unsigned Idx = *EEIdx;
5233       if (TTIRef.getNumberOfParts(VecTy) !=
5234           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5235         auto It =
5236             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5237         It->getSecond() = std::min<int>(It->second, Idx);
5238       }
5239       // Take credit for instruction that will become dead.
5240       if (EE->hasOneUse()) {
5241         Instruction *Ext = EE->user_back();
5242         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5243             all_of(Ext->users(),
5244                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5245           // Use getExtractWithExtendCost() to calculate the cost of
5246           // extractelement/ext pair.
5247           Cost -=
5248               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5249                                               EE->getVectorOperandType(), Idx);
5250           // Add back the cost of s|zext which is subtracted separately.
5251           Cost += TTIRef.getCastInstrCost(
5252               Ext->getOpcode(), Ext->getType(), EE->getType(),
5253               TTI::getCastContextHint(Ext), CostKind, Ext);
5254           continue;
5255         }
5256       }
5257       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5258                                         EE->getVectorOperandType(), Idx);
5259     }
5260     // Add a cost for subvector extracts/inserts if required.
5261     for (const auto &Data : ExtractVectorsTys) {
5262       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5263       unsigned NumElts = VecTy->getNumElements();
5264       if (Data.second % NumElts == 0)
5265         continue;
5266       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5267         unsigned Idx = (Data.second / NumElts) * NumElts;
5268         unsigned EENumElts = EEVTy->getNumElements();
5269         if (Idx + NumElts <= EENumElts) {
5270           Cost +=
5271               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5272                                     EEVTy, None, Idx, VecTy);
5273         } else {
5274           // Need to round up the subvector type vectorization factor to avoid a
5275           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5276           // <= EENumElts.
5277           auto *SubVT =
5278               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5279           Cost +=
5280               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5281                                     EEVTy, None, Idx, SubVT);
5282         }
5283       } else {
5284         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5285                                       VecTy, None, 0, EEVTy);
5286       }
5287     }
5288   };
5289   if (E->State == TreeEntry::NeedToGather) {
5290     if (allConstant(VL))
5291       return 0;
5292     if (isa<InsertElementInst>(VL[0]))
5293       return InstructionCost::getInvalid();
5294     SmallVector<int> Mask;
5295     SmallVector<const TreeEntry *> Entries;
5296     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5297         isGatherShuffledEntry(E, Mask, Entries);
5298     if (Shuffle.hasValue()) {
5299       InstructionCost GatherCost = 0;
5300       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5301         // Perfect match in the graph, will reuse the previously vectorized
5302         // node. Cost is 0.
5303         LLVM_DEBUG(
5304             dbgs()
5305             << "SLP: perfect diamond match for gather bundle that starts with "
5306             << *VL.front() << ".\n");
5307         if (NeedToShuffleReuses)
5308           GatherCost =
5309               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5310                                   FinalVecTy, E->ReuseShuffleIndices);
5311       } else {
5312         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5313                           << " entries for bundle that starts with "
5314                           << *VL.front() << ".\n");
5315         // Detected that instead of gather we can emit a shuffle of single/two
5316         // previously vectorized nodes. Add the cost of the permutation rather
5317         // than gather.
5318         ::addMask(Mask, E->ReuseShuffleIndices);
5319         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5320       }
5321       return GatherCost;
5322     }
5323     if ((E->getOpcode() == Instruction::ExtractElement ||
5324          all_of(E->Scalars,
5325                 [](Value *V) {
5326                   return isa<ExtractElementInst, UndefValue>(V);
5327                 })) &&
5328         allSameType(VL)) {
5329       // Check that gather of extractelements can be represented as just a
5330       // shuffle of a single/two vectors the scalars are extracted from.
5331       SmallVector<int> Mask;
5332       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5333           isFixedVectorShuffle(VL, Mask);
5334       if (ShuffleKind.hasValue()) {
5335         // Found the bunch of extractelement instructions that must be gathered
5336         // into a vector and can be represented as a permutation elements in a
5337         // single input vector or of 2 input vectors.
5338         InstructionCost Cost =
5339             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5340         AdjustExtractsCost(Cost);
5341         if (NeedToShuffleReuses)
5342           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5343                                       FinalVecTy, E->ReuseShuffleIndices);
5344         return Cost;
5345       }
5346     }
5347     if (isSplat(VL)) {
5348       // Found the broadcasting of the single scalar, calculate the cost as the
5349       // broadcast.
5350       assert(VecTy == FinalVecTy &&
5351              "No reused scalars expected for broadcast.");
5352       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5353                                  /*Mask=*/None, /*Index=*/0,
5354                                  /*SubTp=*/nullptr, /*Args=*/VL);
5355     }
5356     InstructionCost ReuseShuffleCost = 0;
5357     if (NeedToShuffleReuses)
5358       ReuseShuffleCost = TTI->getShuffleCost(
5359           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5360     // Improve gather cost for gather of loads, if we can group some of the
5361     // loads into vector loads.
5362     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5363         !E->isAltShuffle()) {
5364       BoUpSLP::ValueSet VectorizedLoads;
5365       unsigned StartIdx = 0;
5366       unsigned VF = VL.size() / 2;
5367       unsigned VectorizedCnt = 0;
5368       unsigned ScatterVectorizeCnt = 0;
5369       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5370       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5371         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5372              Cnt += VF) {
5373           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5374           if (!VectorizedLoads.count(Slice.front()) &&
5375               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5376             SmallVector<Value *> PointerOps;
5377             OrdersType CurrentOrder;
5378             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5379                                               *SE, CurrentOrder, PointerOps);
5380             switch (LS) {
5381             case LoadsState::Vectorize:
5382             case LoadsState::ScatterVectorize:
5383               // Mark the vectorized loads so that we don't vectorize them
5384               // again.
5385               if (LS == LoadsState::Vectorize)
5386                 ++VectorizedCnt;
5387               else
5388                 ++ScatterVectorizeCnt;
5389               VectorizedLoads.insert(Slice.begin(), Slice.end());
5390               // If we vectorized initial block, no need to try to vectorize it
5391               // again.
5392               if (Cnt == StartIdx)
5393                 StartIdx += VF;
5394               break;
5395             case LoadsState::Gather:
5396               break;
5397             }
5398           }
5399         }
5400         // Check if the whole array was vectorized already - exit.
5401         if (StartIdx >= VL.size())
5402           break;
5403         // Found vectorizable parts - exit.
5404         if (!VectorizedLoads.empty())
5405           break;
5406       }
5407       if (!VectorizedLoads.empty()) {
5408         InstructionCost GatherCost = 0;
5409         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5410         bool NeedInsertSubvectorAnalysis =
5411             !NumParts || (VL.size() / VF) > NumParts;
5412         // Get the cost for gathered loads.
5413         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5414           if (VectorizedLoads.contains(VL[I]))
5415             continue;
5416           GatherCost += getGatherCost(VL.slice(I, VF));
5417         }
5418         // The cost for vectorized loads.
5419         InstructionCost ScalarsCost = 0;
5420         for (Value *V : VectorizedLoads) {
5421           auto *LI = cast<LoadInst>(V);
5422           ScalarsCost += TTI->getMemoryOpCost(
5423               Instruction::Load, LI->getType(), LI->getAlign(),
5424               LI->getPointerAddressSpace(), CostKind, LI);
5425         }
5426         auto *LI = cast<LoadInst>(E->getMainOp());
5427         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5428         Align Alignment = LI->getAlign();
5429         GatherCost +=
5430             VectorizedCnt *
5431             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5432                                  LI->getPointerAddressSpace(), CostKind, LI);
5433         GatherCost += ScatterVectorizeCnt *
5434                       TTI->getGatherScatterOpCost(
5435                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5436                           /*VariableMask=*/false, Alignment, CostKind, LI);
5437         if (NeedInsertSubvectorAnalysis) {
5438           // Add the cost for the subvectors insert.
5439           for (int I = VF, E = VL.size(); I < E; I += VF)
5440             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5441                                               None, I, LoadTy);
5442         }
5443         return ReuseShuffleCost + GatherCost - ScalarsCost;
5444       }
5445     }
5446     return ReuseShuffleCost + getGatherCost(VL);
5447   }
5448   InstructionCost CommonCost = 0;
5449   SmallVector<int> Mask;
5450   if (!E->ReorderIndices.empty()) {
5451     SmallVector<int> NewMask;
5452     if (E->getOpcode() == Instruction::Store) {
5453       // For stores the order is actually a mask.
5454       NewMask.resize(E->ReorderIndices.size());
5455       copy(E->ReorderIndices, NewMask.begin());
5456     } else {
5457       inversePermutation(E->ReorderIndices, NewMask);
5458     }
5459     ::addMask(Mask, NewMask);
5460   }
5461   if (NeedToShuffleReuses)
5462     ::addMask(Mask, E->ReuseShuffleIndices);
5463   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5464     CommonCost =
5465         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5466   assert((E->State == TreeEntry::Vectorize ||
5467           E->State == TreeEntry::ScatterVectorize) &&
5468          "Unhandled state");
5469   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5470   Instruction *VL0 = E->getMainOp();
5471   unsigned ShuffleOrOp =
5472       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5473   switch (ShuffleOrOp) {
5474     case Instruction::PHI:
5475       return 0;
5476 
5477     case Instruction::ExtractValue:
5478     case Instruction::ExtractElement: {
5479       // The common cost of removal ExtractElement/ExtractValue instructions +
5480       // the cost of shuffles, if required to resuffle the original vector.
5481       if (NeedToShuffleReuses) {
5482         unsigned Idx = 0;
5483         for (unsigned I : E->ReuseShuffleIndices) {
5484           if (ShuffleOrOp == Instruction::ExtractElement) {
5485             auto *EE = cast<ExtractElementInst>(VL[I]);
5486             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5487                                                   EE->getVectorOperandType(),
5488                                                   *getExtractIndex(EE));
5489           } else {
5490             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5491                                                   VecTy, Idx);
5492             ++Idx;
5493           }
5494         }
5495         Idx = EntryVF;
5496         for (Value *V : VL) {
5497           if (ShuffleOrOp == Instruction::ExtractElement) {
5498             auto *EE = cast<ExtractElementInst>(V);
5499             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5500                                                   EE->getVectorOperandType(),
5501                                                   *getExtractIndex(EE));
5502           } else {
5503             --Idx;
5504             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5505                                                   VecTy, Idx);
5506           }
5507         }
5508       }
5509       if (ShuffleOrOp == Instruction::ExtractValue) {
5510         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5511           auto *EI = cast<Instruction>(VL[I]);
5512           // Take credit for instruction that will become dead.
5513           if (EI->hasOneUse()) {
5514             Instruction *Ext = EI->user_back();
5515             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5516                 all_of(Ext->users(),
5517                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5518               // Use getExtractWithExtendCost() to calculate the cost of
5519               // extractelement/ext pair.
5520               CommonCost -= TTI->getExtractWithExtendCost(
5521                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5522               // Add back the cost of s|zext which is subtracted separately.
5523               CommonCost += TTI->getCastInstrCost(
5524                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5525                   TTI::getCastContextHint(Ext), CostKind, Ext);
5526               continue;
5527             }
5528           }
5529           CommonCost -=
5530               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5531         }
5532       } else {
5533         AdjustExtractsCost(CommonCost);
5534       }
5535       return CommonCost;
5536     }
5537     case Instruction::InsertElement: {
5538       assert(E->ReuseShuffleIndices.empty() &&
5539              "Unique insertelements only are expected.");
5540       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5541 
5542       unsigned const NumElts = SrcVecTy->getNumElements();
5543       unsigned const NumScalars = VL.size();
5544       APInt DemandedElts = APInt::getZero(NumElts);
5545       // TODO: Add support for Instruction::InsertValue.
5546       SmallVector<int> Mask;
5547       if (!E->ReorderIndices.empty()) {
5548         inversePermutation(E->ReorderIndices, Mask);
5549         Mask.append(NumElts - NumScalars, UndefMaskElem);
5550       } else {
5551         Mask.assign(NumElts, UndefMaskElem);
5552         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5553       }
5554       unsigned Offset = *getInsertIndex(VL0);
5555       bool IsIdentity = true;
5556       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5557       Mask.swap(PrevMask);
5558       for (unsigned I = 0; I < NumScalars; ++I) {
5559         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5560         DemandedElts.setBit(InsertIdx);
5561         IsIdentity &= InsertIdx - Offset == I;
5562         Mask[InsertIdx - Offset] = I;
5563       }
5564       assert(Offset < NumElts && "Failed to find vector index offset");
5565 
5566       InstructionCost Cost = 0;
5567       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5568                                             /*Insert*/ true, /*Extract*/ false);
5569 
5570       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5571         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5572         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5573         Cost += TTI->getShuffleCost(
5574             TargetTransformInfo::SK_PermuteSingleSrc,
5575             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5576       } else if (!IsIdentity) {
5577         auto *FirstInsert =
5578             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5579               return !is_contained(E->Scalars,
5580                                    cast<Instruction>(V)->getOperand(0));
5581             }));
5582         if (isUndefVector(FirstInsert->getOperand(0))) {
5583           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5584         } else {
5585           SmallVector<int> InsertMask(NumElts);
5586           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5587           for (unsigned I = 0; I < NumElts; I++) {
5588             if (Mask[I] != UndefMaskElem)
5589               InsertMask[Offset + I] = NumElts + I;
5590           }
5591           Cost +=
5592               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5593         }
5594       }
5595 
5596       return Cost;
5597     }
5598     case Instruction::ZExt:
5599     case Instruction::SExt:
5600     case Instruction::FPToUI:
5601     case Instruction::FPToSI:
5602     case Instruction::FPExt:
5603     case Instruction::PtrToInt:
5604     case Instruction::IntToPtr:
5605     case Instruction::SIToFP:
5606     case Instruction::UIToFP:
5607     case Instruction::Trunc:
5608     case Instruction::FPTrunc:
5609     case Instruction::BitCast: {
5610       Type *SrcTy = VL0->getOperand(0)->getType();
5611       InstructionCost ScalarEltCost =
5612           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5613                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5614       if (NeedToShuffleReuses) {
5615         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5616       }
5617 
5618       // Calculate the cost of this instruction.
5619       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5620 
5621       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5622       InstructionCost VecCost = 0;
5623       // Check if the values are candidates to demote.
5624       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5625         VecCost = CommonCost + TTI->getCastInstrCost(
5626                                    E->getOpcode(), VecTy, SrcVecTy,
5627                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5628       }
5629       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5630       return VecCost - ScalarCost;
5631     }
5632     case Instruction::FCmp:
5633     case Instruction::ICmp:
5634     case Instruction::Select: {
5635       // Calculate the cost of this instruction.
5636       InstructionCost ScalarEltCost =
5637           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5638                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5639       if (NeedToShuffleReuses) {
5640         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5641       }
5642       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5643       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5644 
5645       // Check if all entries in VL are either compares or selects with compares
5646       // as condition that have the same predicates.
5647       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5648       bool First = true;
5649       for (auto *V : VL) {
5650         CmpInst::Predicate CurrentPred;
5651         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5652         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5653              !match(V, MatchCmp)) ||
5654             (!First && VecPred != CurrentPred)) {
5655           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5656           break;
5657         }
5658         First = false;
5659         VecPred = CurrentPred;
5660       }
5661 
5662       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5663           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5664       // Check if it is possible and profitable to use min/max for selects in
5665       // VL.
5666       //
5667       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5668       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5669         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5670                                           {VecTy, VecTy});
5671         InstructionCost IntrinsicCost =
5672             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5673         // If the selects are the only uses of the compares, they will be dead
5674         // and we can adjust the cost by removing their cost.
5675         if (IntrinsicAndUse.second)
5676           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5677                                                    MaskTy, VecPred, CostKind);
5678         VecCost = std::min(VecCost, IntrinsicCost);
5679       }
5680       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5681       return CommonCost + VecCost - ScalarCost;
5682     }
5683     case Instruction::FNeg:
5684     case Instruction::Add:
5685     case Instruction::FAdd:
5686     case Instruction::Sub:
5687     case Instruction::FSub:
5688     case Instruction::Mul:
5689     case Instruction::FMul:
5690     case Instruction::UDiv:
5691     case Instruction::SDiv:
5692     case Instruction::FDiv:
5693     case Instruction::URem:
5694     case Instruction::SRem:
5695     case Instruction::FRem:
5696     case Instruction::Shl:
5697     case Instruction::LShr:
5698     case Instruction::AShr:
5699     case Instruction::And:
5700     case Instruction::Or:
5701     case Instruction::Xor: {
5702       // Certain instructions can be cheaper to vectorize if they have a
5703       // constant second vector operand.
5704       TargetTransformInfo::OperandValueKind Op1VK =
5705           TargetTransformInfo::OK_AnyValue;
5706       TargetTransformInfo::OperandValueKind Op2VK =
5707           TargetTransformInfo::OK_UniformConstantValue;
5708       TargetTransformInfo::OperandValueProperties Op1VP =
5709           TargetTransformInfo::OP_None;
5710       TargetTransformInfo::OperandValueProperties Op2VP =
5711           TargetTransformInfo::OP_PowerOf2;
5712 
5713       // If all operands are exactly the same ConstantInt then set the
5714       // operand kind to OK_UniformConstantValue.
5715       // If instead not all operands are constants, then set the operand kind
5716       // to OK_AnyValue. If all operands are constants but not the same,
5717       // then set the operand kind to OK_NonUniformConstantValue.
5718       ConstantInt *CInt0 = nullptr;
5719       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5720         const Instruction *I = cast<Instruction>(VL[i]);
5721         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5722         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5723         if (!CInt) {
5724           Op2VK = TargetTransformInfo::OK_AnyValue;
5725           Op2VP = TargetTransformInfo::OP_None;
5726           break;
5727         }
5728         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5729             !CInt->getValue().isPowerOf2())
5730           Op2VP = TargetTransformInfo::OP_None;
5731         if (i == 0) {
5732           CInt0 = CInt;
5733           continue;
5734         }
5735         if (CInt0 != CInt)
5736           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5737       }
5738 
5739       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5740       InstructionCost ScalarEltCost =
5741           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5742                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5743       if (NeedToShuffleReuses) {
5744         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5745       }
5746       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5747       InstructionCost VecCost =
5748           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5749                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5750       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5751       return CommonCost + VecCost - ScalarCost;
5752     }
5753     case Instruction::GetElementPtr: {
5754       TargetTransformInfo::OperandValueKind Op1VK =
5755           TargetTransformInfo::OK_AnyValue;
5756       TargetTransformInfo::OperandValueKind Op2VK =
5757           TargetTransformInfo::OK_UniformConstantValue;
5758 
5759       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5760           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5761       if (NeedToShuffleReuses) {
5762         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5763       }
5764       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5765       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5766           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5767       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5768       return CommonCost + VecCost - ScalarCost;
5769     }
5770     case Instruction::Load: {
5771       // Cost of wide load - cost of scalar loads.
5772       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5773       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5774           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5775       if (NeedToShuffleReuses) {
5776         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5777       }
5778       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5779       InstructionCost VecLdCost;
5780       if (E->State == TreeEntry::Vectorize) {
5781         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5782                                          CostKind, VL0);
5783       } else {
5784         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5785         Align CommonAlignment = Alignment;
5786         for (Value *V : VL)
5787           CommonAlignment =
5788               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5789         VecLdCost = TTI->getGatherScatterOpCost(
5790             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5791             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5792       }
5793       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5794       return CommonCost + VecLdCost - ScalarLdCost;
5795     }
5796     case Instruction::Store: {
5797       // We know that we can merge the stores. Calculate the cost.
5798       bool IsReorder = !E->ReorderIndices.empty();
5799       auto *SI =
5800           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5801       Align Alignment = SI->getAlign();
5802       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5803           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5804       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5805       InstructionCost VecStCost = TTI->getMemoryOpCost(
5806           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5807       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5808       return CommonCost + VecStCost - ScalarStCost;
5809     }
5810     case Instruction::Call: {
5811       CallInst *CI = cast<CallInst>(VL0);
5812       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5813 
5814       // Calculate the cost of the scalar and vector calls.
5815       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5816       InstructionCost ScalarEltCost =
5817           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5818       if (NeedToShuffleReuses) {
5819         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5820       }
5821       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5822 
5823       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5824       InstructionCost VecCallCost =
5825           std::min(VecCallCosts.first, VecCallCosts.second);
5826 
5827       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5828                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5829                         << " for " << *CI << "\n");
5830 
5831       return CommonCost + VecCallCost - ScalarCallCost;
5832     }
5833     case Instruction::ShuffleVector: {
5834       assert(E->isAltShuffle() &&
5835              ((Instruction::isBinaryOp(E->getOpcode()) &&
5836                Instruction::isBinaryOp(E->getAltOpcode())) ||
5837               (Instruction::isCast(E->getOpcode()) &&
5838                Instruction::isCast(E->getAltOpcode())) ||
5839               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5840              "Invalid Shuffle Vector Operand");
5841       InstructionCost ScalarCost = 0;
5842       if (NeedToShuffleReuses) {
5843         for (unsigned Idx : E->ReuseShuffleIndices) {
5844           Instruction *I = cast<Instruction>(VL[Idx]);
5845           CommonCost -= TTI->getInstructionCost(I, CostKind);
5846         }
5847         for (Value *V : VL) {
5848           Instruction *I = cast<Instruction>(V);
5849           CommonCost += TTI->getInstructionCost(I, CostKind);
5850         }
5851       }
5852       for (Value *V : VL) {
5853         Instruction *I = cast<Instruction>(V);
5854         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5855         ScalarCost += TTI->getInstructionCost(I, CostKind);
5856       }
5857       // VecCost is equal to sum of the cost of creating 2 vectors
5858       // and the cost of creating shuffle.
5859       InstructionCost VecCost = 0;
5860       // Try to find the previous shuffle node with the same operands and same
5861       // main/alternate ops.
5862       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5863         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5864           if (TE.get() == E)
5865             break;
5866           if (TE->isAltShuffle() &&
5867               ((TE->getOpcode() == E->getOpcode() &&
5868                 TE->getAltOpcode() == E->getAltOpcode()) ||
5869                (TE->getOpcode() == E->getAltOpcode() &&
5870                 TE->getAltOpcode() == E->getOpcode())) &&
5871               TE->hasEqualOperands(*E))
5872             return true;
5873         }
5874         return false;
5875       };
5876       if (TryFindNodeWithEqualOperands()) {
5877         LLVM_DEBUG({
5878           dbgs() << "SLP: diamond match for alternate node found.\n";
5879           E->dump();
5880         });
5881         // No need to add new vector costs here since we're going to reuse
5882         // same main/alternate vector ops, just do different shuffling.
5883       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5884         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5885         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5886                                                CostKind);
5887       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5888         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5889                                           Builder.getInt1Ty(),
5890                                           CI0->getPredicate(), CostKind, VL0);
5891         VecCost += TTI->getCmpSelInstrCost(
5892             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5893             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5894             E->getAltOp());
5895       } else {
5896         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5897         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5898         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5899         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5900         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5901                                         TTI::CastContextHint::None, CostKind);
5902         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5903                                          TTI::CastContextHint::None, CostKind);
5904       }
5905 
5906       SmallVector<int> Mask;
5907       buildShuffleEntryMask(
5908           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5909           [E](Instruction *I) {
5910             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5911             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5912           },
5913           Mask);
5914       CommonCost =
5915           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5916       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5917       return CommonCost + VecCost - ScalarCost;
5918     }
5919     default:
5920       llvm_unreachable("Unknown instruction");
5921   }
5922 }
5923 
5924 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5925   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5926                     << VectorizableTree.size() << " is fully vectorizable .\n");
5927 
5928   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5929     SmallVector<int> Mask;
5930     return TE->State == TreeEntry::NeedToGather &&
5931            !any_of(TE->Scalars,
5932                    [this](Value *V) { return EphValues.contains(V); }) &&
5933            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5934             TE->Scalars.size() < Limit ||
5935             ((TE->getOpcode() == Instruction::ExtractElement ||
5936               all_of(TE->Scalars,
5937                      [](Value *V) {
5938                        return isa<ExtractElementInst, UndefValue>(V);
5939                      })) &&
5940              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5941             (TE->State == TreeEntry::NeedToGather &&
5942              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5943   };
5944 
5945   // We only handle trees of heights 1 and 2.
5946   if (VectorizableTree.size() == 1 &&
5947       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5948        (ForReduction &&
5949         AreVectorizableGathers(VectorizableTree[0].get(),
5950                                VectorizableTree[0]->Scalars.size()) &&
5951         VectorizableTree[0]->getVectorFactor() > 2)))
5952     return true;
5953 
5954   if (VectorizableTree.size() != 2)
5955     return false;
5956 
5957   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5958   // with the second gather nodes if they have less scalar operands rather than
5959   // the initial tree element (may be profitable to shuffle the second gather)
5960   // or they are extractelements, which form shuffle.
5961   SmallVector<int> Mask;
5962   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5963       AreVectorizableGathers(VectorizableTree[1].get(),
5964                              VectorizableTree[0]->Scalars.size()))
5965     return true;
5966 
5967   // Gathering cost would be too much for tiny trees.
5968   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5969       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5970        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5971     return false;
5972 
5973   return true;
5974 }
5975 
5976 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5977                                        TargetTransformInfo *TTI,
5978                                        bool MustMatchOrInst) {
5979   // Look past the root to find a source value. Arbitrarily follow the
5980   // path through operand 0 of any 'or'. Also, peek through optional
5981   // shift-left-by-multiple-of-8-bits.
5982   Value *ZextLoad = Root;
5983   const APInt *ShAmtC;
5984   bool FoundOr = false;
5985   while (!isa<ConstantExpr>(ZextLoad) &&
5986          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5987           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5988            ShAmtC->urem(8) == 0))) {
5989     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5990     ZextLoad = BinOp->getOperand(0);
5991     if (BinOp->getOpcode() == Instruction::Or)
5992       FoundOr = true;
5993   }
5994   // Check if the input is an extended load of the required or/shift expression.
5995   Value *Load;
5996   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5997       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5998     return false;
5999 
6000   // Require that the total load bit width is a legal integer type.
6001   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6002   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6003   Type *SrcTy = Load->getType();
6004   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6005   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6006     return false;
6007 
6008   // Everything matched - assume that we can fold the whole sequence using
6009   // load combining.
6010   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6011              << *(cast<Instruction>(Root)) << "\n");
6012 
6013   return true;
6014 }
6015 
6016 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6017   if (RdxKind != RecurKind::Or)
6018     return false;
6019 
6020   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6021   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6022   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6023                                     /* MatchOr */ false);
6024 }
6025 
6026 bool BoUpSLP::isLoadCombineCandidate() const {
6027   // Peek through a final sequence of stores and check if all operations are
6028   // likely to be load-combined.
6029   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6030   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6031     Value *X;
6032     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6033         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6034       return false;
6035   }
6036   return true;
6037 }
6038 
6039 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6040   // No need to vectorize inserts of gathered values.
6041   if (VectorizableTree.size() == 2 &&
6042       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6043       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6044     return true;
6045 
6046   // We can vectorize the tree if its size is greater than or equal to the
6047   // minimum size specified by the MinTreeSize command line option.
6048   if (VectorizableTree.size() >= MinTreeSize)
6049     return false;
6050 
6051   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6052   // can vectorize it if we can prove it fully vectorizable.
6053   if (isFullyVectorizableTinyTree(ForReduction))
6054     return false;
6055 
6056   assert(VectorizableTree.empty()
6057              ? ExternalUses.empty()
6058              : true && "We shouldn't have any external users");
6059 
6060   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6061   // vectorizable.
6062   return true;
6063 }
6064 
6065 InstructionCost BoUpSLP::getSpillCost() const {
6066   // Walk from the bottom of the tree to the top, tracking which values are
6067   // live. When we see a call instruction that is not part of our tree,
6068   // query TTI to see if there is a cost to keeping values live over it
6069   // (for example, if spills and fills are required).
6070   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6071   InstructionCost Cost = 0;
6072 
6073   SmallPtrSet<Instruction*, 4> LiveValues;
6074   Instruction *PrevInst = nullptr;
6075 
6076   // The entries in VectorizableTree are not necessarily ordered by their
6077   // position in basic blocks. Collect them and order them by dominance so later
6078   // instructions are guaranteed to be visited first. For instructions in
6079   // different basic blocks, we only scan to the beginning of the block, so
6080   // their order does not matter, as long as all instructions in a basic block
6081   // are grouped together. Using dominance ensures a deterministic order.
6082   SmallVector<Instruction *, 16> OrderedScalars;
6083   for (const auto &TEPtr : VectorizableTree) {
6084     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6085     if (!Inst)
6086       continue;
6087     OrderedScalars.push_back(Inst);
6088   }
6089   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6090     auto *NodeA = DT->getNode(A->getParent());
6091     auto *NodeB = DT->getNode(B->getParent());
6092     assert(NodeA && "Should only process reachable instructions");
6093     assert(NodeB && "Should only process reachable instructions");
6094     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6095            "Different nodes should have different DFS numbers");
6096     if (NodeA != NodeB)
6097       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6098     return B->comesBefore(A);
6099   });
6100 
6101   for (Instruction *Inst : OrderedScalars) {
6102     if (!PrevInst) {
6103       PrevInst = Inst;
6104       continue;
6105     }
6106 
6107     // Update LiveValues.
6108     LiveValues.erase(PrevInst);
6109     for (auto &J : PrevInst->operands()) {
6110       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6111         LiveValues.insert(cast<Instruction>(&*J));
6112     }
6113 
6114     LLVM_DEBUG({
6115       dbgs() << "SLP: #LV: " << LiveValues.size();
6116       for (auto *X : LiveValues)
6117         dbgs() << " " << X->getName();
6118       dbgs() << ", Looking at ";
6119       Inst->dump();
6120     });
6121 
6122     // Now find the sequence of instructions between PrevInst and Inst.
6123     unsigned NumCalls = 0;
6124     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6125                                  PrevInstIt =
6126                                      PrevInst->getIterator().getReverse();
6127     while (InstIt != PrevInstIt) {
6128       if (PrevInstIt == PrevInst->getParent()->rend()) {
6129         PrevInstIt = Inst->getParent()->rbegin();
6130         continue;
6131       }
6132 
6133       // Debug information does not impact spill cost.
6134       if ((isa<CallInst>(&*PrevInstIt) &&
6135            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6136           &*PrevInstIt != PrevInst)
6137         NumCalls++;
6138 
6139       ++PrevInstIt;
6140     }
6141 
6142     if (NumCalls) {
6143       SmallVector<Type*, 4> V;
6144       for (auto *II : LiveValues) {
6145         auto *ScalarTy = II->getType();
6146         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6147           ScalarTy = VectorTy->getElementType();
6148         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6149       }
6150       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6151     }
6152 
6153     PrevInst = Inst;
6154   }
6155 
6156   return Cost;
6157 }
6158 
6159 /// Check if two insertelement instructions are from the same buildvector.
6160 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6161                                             InsertElementInst *V) {
6162   // Instructions must be from the same basic blocks.
6163   if (VU->getParent() != V->getParent())
6164     return false;
6165   // Checks if 2 insertelements are from the same buildvector.
6166   if (VU->getType() != V->getType())
6167     return false;
6168   // Multiple used inserts are separate nodes.
6169   if (!VU->hasOneUse() && !V->hasOneUse())
6170     return false;
6171   auto *IE1 = VU;
6172   auto *IE2 = V;
6173   // Go through the vector operand of insertelement instructions trying to find
6174   // either VU as the original vector for IE2 or V as the original vector for
6175   // IE1.
6176   do {
6177     if (IE2 == VU || IE1 == V)
6178       return true;
6179     if (IE1) {
6180       if (IE1 != VU && !IE1->hasOneUse())
6181         IE1 = nullptr;
6182       else
6183         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6184     }
6185     if (IE2) {
6186       if (IE2 != V && !IE2->hasOneUse())
6187         IE2 = nullptr;
6188       else
6189         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6190     }
6191   } while (IE1 || IE2);
6192   return false;
6193 }
6194 
6195 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6196   InstructionCost Cost = 0;
6197   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6198                     << VectorizableTree.size() << ".\n");
6199 
6200   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6201 
6202   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6203     TreeEntry &TE = *VectorizableTree[I];
6204 
6205     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6206     Cost += C;
6207     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6208                       << " for bundle that starts with " << *TE.Scalars[0]
6209                       << ".\n"
6210                       << "SLP: Current total cost = " << Cost << "\n");
6211   }
6212 
6213   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6214   InstructionCost ExtractCost = 0;
6215   SmallVector<unsigned> VF;
6216   SmallVector<SmallVector<int>> ShuffleMask;
6217   SmallVector<Value *> FirstUsers;
6218   SmallVector<APInt> DemandedElts;
6219   for (ExternalUser &EU : ExternalUses) {
6220     // We only add extract cost once for the same scalar.
6221     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6222         !ExtractCostCalculated.insert(EU.Scalar).second)
6223       continue;
6224 
6225     // Uses by ephemeral values are free (because the ephemeral value will be
6226     // removed prior to code generation, and so the extraction will be
6227     // removed as well).
6228     if (EphValues.count(EU.User))
6229       continue;
6230 
6231     // No extract cost for vector "scalar"
6232     if (isa<FixedVectorType>(EU.Scalar->getType()))
6233       continue;
6234 
6235     // Already counted the cost for external uses when tried to adjust the cost
6236     // for extractelements, no need to add it again.
6237     if (isa<ExtractElementInst>(EU.Scalar))
6238       continue;
6239 
6240     // If found user is an insertelement, do not calculate extract cost but try
6241     // to detect it as a final shuffled/identity match.
6242     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6243       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6244         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6245         if (InsertIdx) {
6246           auto *It = find_if(FirstUsers, [VU](Value *V) {
6247             return areTwoInsertFromSameBuildVector(VU,
6248                                                    cast<InsertElementInst>(V));
6249           });
6250           int VecId = -1;
6251           if (It == FirstUsers.end()) {
6252             VF.push_back(FTy->getNumElements());
6253             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6254             // Find the insertvector, vectorized in tree, if any.
6255             Value *Base = VU;
6256             while (isa<InsertElementInst>(Base)) {
6257               // Build the mask for the vectorized insertelement instructions.
6258               if (const TreeEntry *E = getTreeEntry(Base)) {
6259                 VU = cast<InsertElementInst>(Base);
6260                 do {
6261                   int Idx = E->findLaneForValue(Base);
6262                   ShuffleMask.back()[Idx] = Idx;
6263                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6264                 } while (E == getTreeEntry(Base));
6265                 break;
6266               }
6267               Base = cast<InsertElementInst>(Base)->getOperand(0);
6268             }
6269             FirstUsers.push_back(VU);
6270             DemandedElts.push_back(APInt::getZero(VF.back()));
6271             VecId = FirstUsers.size() - 1;
6272           } else {
6273             VecId = std::distance(FirstUsers.begin(), It);
6274           }
6275           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6276           DemandedElts[VecId].setBit(*InsertIdx);
6277           continue;
6278         }
6279       }
6280     }
6281 
6282     // If we plan to rewrite the tree in a smaller type, we will need to sign
6283     // extend the extracted value back to the original type. Here, we account
6284     // for the extract and the added cost of the sign extend if needed.
6285     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6286     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6287     if (MinBWs.count(ScalarRoot)) {
6288       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6289       auto Extend =
6290           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6291       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6292       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6293                                                    VecTy, EU.Lane);
6294     } else {
6295       ExtractCost +=
6296           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6297     }
6298   }
6299 
6300   InstructionCost SpillCost = getSpillCost();
6301   Cost += SpillCost + ExtractCost;
6302   if (FirstUsers.size() == 1) {
6303     int Limit = ShuffleMask.front().size() * 2;
6304     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6305         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6306       InstructionCost C = TTI->getShuffleCost(
6307           TTI::SK_PermuteSingleSrc,
6308           cast<FixedVectorType>(FirstUsers.front()->getType()),
6309           ShuffleMask.front());
6310       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6311                         << " for final shuffle of insertelement external users "
6312                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6313                         << "SLP: Current total cost = " << Cost << "\n");
6314       Cost += C;
6315     }
6316     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6317         cast<FixedVectorType>(FirstUsers.front()->getType()),
6318         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6319     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6320                       << " for insertelements gather.\n"
6321                       << "SLP: Current total cost = " << Cost << "\n");
6322     Cost -= InsertCost;
6323   } else if (FirstUsers.size() >= 2) {
6324     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6325     // Combined masks of the first 2 vectors.
6326     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6327     copy(ShuffleMask.front(), CombinedMask.begin());
6328     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6329     auto *VecTy = FixedVectorType::get(
6330         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6331         MaxVF);
6332     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6333       if (ShuffleMask[1][I] != UndefMaskElem) {
6334         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6335         CombinedDemandedElts.setBit(I);
6336       }
6337     }
6338     InstructionCost C =
6339         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6340     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6341                       << " for final shuffle of vector node and external "
6342                          "insertelement users "
6343                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6344                       << "SLP: Current total cost = " << Cost << "\n");
6345     Cost += C;
6346     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6347         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6348     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6349                       << " for insertelements gather.\n"
6350                       << "SLP: Current total cost = " << Cost << "\n");
6351     Cost -= InsertCost;
6352     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6353       // Other elements - permutation of 2 vectors (the initial one and the
6354       // next Ith incoming vector).
6355       unsigned VF = ShuffleMask[I].size();
6356       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6357         int Mask = ShuffleMask[I][Idx];
6358         if (Mask != UndefMaskElem)
6359           CombinedMask[Idx] = MaxVF + Mask;
6360         else if (CombinedMask[Idx] != UndefMaskElem)
6361           CombinedMask[Idx] = Idx;
6362       }
6363       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6364         if (CombinedMask[Idx] != UndefMaskElem)
6365           CombinedMask[Idx] = Idx;
6366       InstructionCost C =
6367           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6368       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6369                         << " for final shuffle of vector node and external "
6370                            "insertelement users "
6371                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6372                         << "SLP: Current total cost = " << Cost << "\n");
6373       Cost += C;
6374       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6375           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6376           /*Insert*/ true, /*Extract*/ false);
6377       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6378                         << " for insertelements gather.\n"
6379                         << "SLP: Current total cost = " << Cost << "\n");
6380       Cost -= InsertCost;
6381     }
6382   }
6383 
6384 #ifndef NDEBUG
6385   SmallString<256> Str;
6386   {
6387     raw_svector_ostream OS(Str);
6388     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6389        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6390        << "SLP: Total Cost = " << Cost << ".\n";
6391   }
6392   LLVM_DEBUG(dbgs() << Str);
6393   if (ViewSLPTree)
6394     ViewGraph(this, "SLP" + F->getName(), false, Str);
6395 #endif
6396 
6397   return Cost;
6398 }
6399 
6400 Optional<TargetTransformInfo::ShuffleKind>
6401 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6402                                SmallVectorImpl<const TreeEntry *> &Entries) {
6403   // TODO: currently checking only for Scalars in the tree entry, need to count
6404   // reused elements too for better cost estimation.
6405   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6406   Entries.clear();
6407   // Build a lists of values to tree entries.
6408   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6409   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6410     if (EntryPtr.get() == TE)
6411       break;
6412     if (EntryPtr->State != TreeEntry::NeedToGather)
6413       continue;
6414     for (Value *V : EntryPtr->Scalars)
6415       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6416   }
6417   // Find all tree entries used by the gathered values. If no common entries
6418   // found - not a shuffle.
6419   // Here we build a set of tree nodes for each gathered value and trying to
6420   // find the intersection between these sets. If we have at least one common
6421   // tree node for each gathered value - we have just a permutation of the
6422   // single vector. If we have 2 different sets, we're in situation where we
6423   // have a permutation of 2 input vectors.
6424   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6425   DenseMap<Value *, int> UsedValuesEntry;
6426   for (Value *V : TE->Scalars) {
6427     if (isa<UndefValue>(V))
6428       continue;
6429     // Build a list of tree entries where V is used.
6430     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6431     auto It = ValueToTEs.find(V);
6432     if (It != ValueToTEs.end())
6433       VToTEs = It->second;
6434     if (const TreeEntry *VTE = getTreeEntry(V))
6435       VToTEs.insert(VTE);
6436     if (VToTEs.empty())
6437       return None;
6438     if (UsedTEs.empty()) {
6439       // The first iteration, just insert the list of nodes to vector.
6440       UsedTEs.push_back(VToTEs);
6441     } else {
6442       // Need to check if there are any previously used tree nodes which use V.
6443       // If there are no such nodes, consider that we have another one input
6444       // vector.
6445       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6446       unsigned Idx = 0;
6447       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6448         // Do we have a non-empty intersection of previously listed tree entries
6449         // and tree entries using current V?
6450         set_intersect(VToTEs, Set);
6451         if (!VToTEs.empty()) {
6452           // Yes, write the new subset and continue analysis for the next
6453           // scalar.
6454           Set.swap(VToTEs);
6455           break;
6456         }
6457         VToTEs = SavedVToTEs;
6458         ++Idx;
6459       }
6460       // No non-empty intersection found - need to add a second set of possible
6461       // source vectors.
6462       if (Idx == UsedTEs.size()) {
6463         // If the number of input vectors is greater than 2 - not a permutation,
6464         // fallback to the regular gather.
6465         if (UsedTEs.size() == 2)
6466           return None;
6467         UsedTEs.push_back(SavedVToTEs);
6468         Idx = UsedTEs.size() - 1;
6469       }
6470       UsedValuesEntry.try_emplace(V, Idx);
6471     }
6472   }
6473 
6474   if (UsedTEs.empty()) {
6475     assert(all_of(TE->Scalars, UndefValue::classof) &&
6476            "Expected vector of undefs only.");
6477     return None;
6478   }
6479 
6480   unsigned VF = 0;
6481   if (UsedTEs.size() == 1) {
6482     // Try to find the perfect match in another gather node at first.
6483     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6484       return EntryPtr->isSame(TE->Scalars);
6485     });
6486     if (It != UsedTEs.front().end()) {
6487       Entries.push_back(*It);
6488       std::iota(Mask.begin(), Mask.end(), 0);
6489       return TargetTransformInfo::SK_PermuteSingleSrc;
6490     }
6491     // No perfect match, just shuffle, so choose the first tree node.
6492     Entries.push_back(*UsedTEs.front().begin());
6493   } else {
6494     // Try to find nodes with the same vector factor.
6495     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6496     DenseMap<int, const TreeEntry *> VFToTE;
6497     for (const TreeEntry *TE : UsedTEs.front())
6498       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6499     for (const TreeEntry *TE : UsedTEs.back()) {
6500       auto It = VFToTE.find(TE->getVectorFactor());
6501       if (It != VFToTE.end()) {
6502         VF = It->first;
6503         Entries.push_back(It->second);
6504         Entries.push_back(TE);
6505         break;
6506       }
6507     }
6508     // No 2 source vectors with the same vector factor - give up and do regular
6509     // gather.
6510     if (Entries.empty())
6511       return None;
6512   }
6513 
6514   // Build a shuffle mask for better cost estimation and vector emission.
6515   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6516     Value *V = TE->Scalars[I];
6517     if (isa<UndefValue>(V))
6518       continue;
6519     unsigned Idx = UsedValuesEntry.lookup(V);
6520     const TreeEntry *VTE = Entries[Idx];
6521     int FoundLane = VTE->findLaneForValue(V);
6522     Mask[I] = Idx * VF + FoundLane;
6523     // Extra check required by isSingleSourceMaskImpl function (called by
6524     // ShuffleVectorInst::isSingleSourceMask).
6525     if (Mask[I] >= 2 * E)
6526       return None;
6527   }
6528   switch (Entries.size()) {
6529   case 1:
6530     return TargetTransformInfo::SK_PermuteSingleSrc;
6531   case 2:
6532     return TargetTransformInfo::SK_PermuteTwoSrc;
6533   default:
6534     break;
6535   }
6536   return None;
6537 }
6538 
6539 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6540                                        const APInt &ShuffledIndices,
6541                                        bool NeedToShuffle) const {
6542   InstructionCost Cost =
6543       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6544                                     /*Extract*/ false);
6545   if (NeedToShuffle)
6546     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6547   return Cost;
6548 }
6549 
6550 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6551   // Find the type of the operands in VL.
6552   Type *ScalarTy = VL[0]->getType();
6553   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6554     ScalarTy = SI->getValueOperand()->getType();
6555   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6556   bool DuplicateNonConst = false;
6557   // Find the cost of inserting/extracting values from the vector.
6558   // Check if the same elements are inserted several times and count them as
6559   // shuffle candidates.
6560   APInt ShuffledElements = APInt::getZero(VL.size());
6561   DenseSet<Value *> UniqueElements;
6562   // Iterate in reverse order to consider insert elements with the high cost.
6563   for (unsigned I = VL.size(); I > 0; --I) {
6564     unsigned Idx = I - 1;
6565     // No need to shuffle duplicates for constants.
6566     if (isConstant(VL[Idx])) {
6567       ShuffledElements.setBit(Idx);
6568       continue;
6569     }
6570     if (!UniqueElements.insert(VL[Idx]).second) {
6571       DuplicateNonConst = true;
6572       ShuffledElements.setBit(Idx);
6573     }
6574   }
6575   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6576 }
6577 
6578 // Perform operand reordering on the instructions in VL and return the reordered
6579 // operands in Left and Right.
6580 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6581                                              SmallVectorImpl<Value *> &Left,
6582                                              SmallVectorImpl<Value *> &Right,
6583                                              const DataLayout &DL,
6584                                              ScalarEvolution &SE,
6585                                              const BoUpSLP &R) {
6586   if (VL.empty())
6587     return;
6588   VLOperands Ops(VL, DL, SE, R);
6589   // Reorder the operands in place.
6590   Ops.reorder();
6591   Left = Ops.getVL(0);
6592   Right = Ops.getVL(1);
6593 }
6594 
6595 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6596   // Get the basic block this bundle is in. All instructions in the bundle
6597   // should be in this block.
6598   auto *Front = E->getMainOp();
6599   auto *BB = Front->getParent();
6600   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6601     auto *I = cast<Instruction>(V);
6602     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6603   }));
6604 
6605   auto &&FindLastInst = [E, Front]() {
6606     Instruction *LastInst = Front;
6607     for (Value *V : E->Scalars) {
6608       auto *I = dyn_cast<Instruction>(V);
6609       if (!I)
6610         continue;
6611       if (LastInst->comesBefore(I))
6612         LastInst = I;
6613     }
6614     return LastInst;
6615   };
6616 
6617   auto &&FindFirstInst = [E, Front]() {
6618     Instruction *FirstInst = Front;
6619     for (Value *V : E->Scalars) {
6620       auto *I = dyn_cast<Instruction>(V);
6621       if (!I)
6622         continue;
6623       if (I->comesBefore(FirstInst))
6624         FirstInst = I;
6625     }
6626     return FirstInst;
6627   };
6628 
6629   // Set the insert point to the beginning of the basic block if the entry
6630   // should not be scheduled.
6631   if (E->State != TreeEntry::NeedToGather &&
6632       doesNotNeedToSchedule(E->Scalars)) {
6633     BasicBlock::iterator InsertPt;
6634     if (all_of(E->Scalars, isUsedOutsideBlock))
6635       InsertPt = FindLastInst()->getIterator();
6636     else
6637       InsertPt = FindFirstInst()->getIterator();
6638     Builder.SetInsertPoint(BB, InsertPt);
6639     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6640     return;
6641   }
6642 
6643   // The last instruction in the bundle in program order.
6644   Instruction *LastInst = nullptr;
6645 
6646   // Find the last instruction. The common case should be that BB has been
6647   // scheduled, and the last instruction is VL.back(). So we start with
6648   // VL.back() and iterate over schedule data until we reach the end of the
6649   // bundle. The end of the bundle is marked by null ScheduleData.
6650   if (BlocksSchedules.count(BB)) {
6651     Value *V = E->isOneOf(E->Scalars.back());
6652     if (doesNotNeedToBeScheduled(V))
6653       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6654     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6655     if (Bundle && Bundle->isPartOfBundle())
6656       for (; Bundle; Bundle = Bundle->NextInBundle)
6657         if (Bundle->OpValue == Bundle->Inst)
6658           LastInst = Bundle->Inst;
6659   }
6660 
6661   // LastInst can still be null at this point if there's either not an entry
6662   // for BB in BlocksSchedules or there's no ScheduleData available for
6663   // VL.back(). This can be the case if buildTree_rec aborts for various
6664   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6665   // size is reached, etc.). ScheduleData is initialized in the scheduling
6666   // "dry-run".
6667   //
6668   // If this happens, we can still find the last instruction by brute force. We
6669   // iterate forwards from Front (inclusive) until we either see all
6670   // instructions in the bundle or reach the end of the block. If Front is the
6671   // last instruction in program order, LastInst will be set to Front, and we
6672   // will visit all the remaining instructions in the block.
6673   //
6674   // One of the reasons we exit early from buildTree_rec is to place an upper
6675   // bound on compile-time. Thus, taking an additional compile-time hit here is
6676   // not ideal. However, this should be exceedingly rare since it requires that
6677   // we both exit early from buildTree_rec and that the bundle be out-of-order
6678   // (causing us to iterate all the way to the end of the block).
6679   if (!LastInst)
6680     LastInst = FindLastInst();
6681   assert(LastInst && "Failed to find last instruction in bundle");
6682 
6683   // Set the insertion point after the last instruction in the bundle. Set the
6684   // debug location to Front.
6685   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6686   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6687 }
6688 
6689 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6690   // List of instructions/lanes from current block and/or the blocks which are
6691   // part of the current loop. These instructions will be inserted at the end to
6692   // make it possible to optimize loops and hoist invariant instructions out of
6693   // the loops body with better chances for success.
6694   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6695   SmallSet<int, 4> PostponedIndices;
6696   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6697   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6698     SmallPtrSet<BasicBlock *, 4> Visited;
6699     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6700       InsertBB = InsertBB->getSinglePredecessor();
6701     return InsertBB && InsertBB == InstBB;
6702   };
6703   for (int I = 0, E = VL.size(); I < E; ++I) {
6704     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6705       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6706            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6707           PostponedIndices.insert(I).second)
6708         PostponedInsts.emplace_back(Inst, I);
6709   }
6710 
6711   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6712     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6713     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6714     if (!InsElt)
6715       return Vec;
6716     GatherShuffleSeq.insert(InsElt);
6717     CSEBlocks.insert(InsElt->getParent());
6718     // Add to our 'need-to-extract' list.
6719     if (TreeEntry *Entry = getTreeEntry(V)) {
6720       // Find which lane we need to extract.
6721       unsigned FoundLane = Entry->findLaneForValue(V);
6722       ExternalUses.emplace_back(V, InsElt, FoundLane);
6723     }
6724     return Vec;
6725   };
6726   Value *Val0 =
6727       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6728   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6729   Value *Vec = PoisonValue::get(VecTy);
6730   SmallVector<int> NonConsts;
6731   // Insert constant values at first.
6732   for (int I = 0, E = VL.size(); I < E; ++I) {
6733     if (PostponedIndices.contains(I))
6734       continue;
6735     if (!isConstant(VL[I])) {
6736       NonConsts.push_back(I);
6737       continue;
6738     }
6739     Vec = CreateInsertElement(Vec, VL[I], I);
6740   }
6741   // Insert non-constant values.
6742   for (int I : NonConsts)
6743     Vec = CreateInsertElement(Vec, VL[I], I);
6744   // Append instructions, which are/may be part of the loop, in the end to make
6745   // it possible to hoist non-loop-based instructions.
6746   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6747     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6748 
6749   return Vec;
6750 }
6751 
6752 namespace {
6753 /// Merges shuffle masks and emits final shuffle instruction, if required.
6754 class ShuffleInstructionBuilder {
6755   IRBuilderBase &Builder;
6756   const unsigned VF = 0;
6757   bool IsFinalized = false;
6758   SmallVector<int, 4> Mask;
6759   /// Holds all of the instructions that we gathered.
6760   SetVector<Instruction *> &GatherShuffleSeq;
6761   /// A list of blocks that we are going to CSE.
6762   SetVector<BasicBlock *> &CSEBlocks;
6763 
6764 public:
6765   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6766                             SetVector<Instruction *> &GatherShuffleSeq,
6767                             SetVector<BasicBlock *> &CSEBlocks)
6768       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6769         CSEBlocks(CSEBlocks) {}
6770 
6771   /// Adds a mask, inverting it before applying.
6772   void addInversedMask(ArrayRef<unsigned> SubMask) {
6773     if (SubMask.empty())
6774       return;
6775     SmallVector<int, 4> NewMask;
6776     inversePermutation(SubMask, NewMask);
6777     addMask(NewMask);
6778   }
6779 
6780   /// Functions adds masks, merging them into  single one.
6781   void addMask(ArrayRef<unsigned> SubMask) {
6782     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6783     addMask(NewMask);
6784   }
6785 
6786   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6787 
6788   Value *finalize(Value *V) {
6789     IsFinalized = true;
6790     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6791     if (VF == ValueVF && Mask.empty())
6792       return V;
6793     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6794     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6795     addMask(NormalizedMask);
6796 
6797     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6798       return V;
6799     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6800     if (auto *I = dyn_cast<Instruction>(Vec)) {
6801       GatherShuffleSeq.insert(I);
6802       CSEBlocks.insert(I->getParent());
6803     }
6804     return Vec;
6805   }
6806 
6807   ~ShuffleInstructionBuilder() {
6808     assert((IsFinalized || Mask.empty()) &&
6809            "Shuffle construction must be finalized.");
6810   }
6811 };
6812 } // namespace
6813 
6814 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6815   const unsigned VF = VL.size();
6816   InstructionsState S = getSameOpcode(VL);
6817   if (S.getOpcode()) {
6818     if (TreeEntry *E = getTreeEntry(S.OpValue))
6819       if (E->isSame(VL)) {
6820         Value *V = vectorizeTree(E);
6821         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6822           if (!E->ReuseShuffleIndices.empty()) {
6823             // Reshuffle to get only unique values.
6824             // If some of the scalars are duplicated in the vectorization tree
6825             // entry, we do not vectorize them but instead generate a mask for
6826             // the reuses. But if there are several users of the same entry,
6827             // they may have different vectorization factors. This is especially
6828             // important for PHI nodes. In this case, we need to adapt the
6829             // resulting instruction for the user vectorization factor and have
6830             // to reshuffle it again to take only unique elements of the vector.
6831             // Without this code the function incorrectly returns reduced vector
6832             // instruction with the same elements, not with the unique ones.
6833 
6834             // block:
6835             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6836             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6837             // ... (use %2)
6838             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6839             // br %block
6840             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6841             SmallSet<int, 4> UsedIdxs;
6842             int Pos = 0;
6843             int Sz = VL.size();
6844             for (int Idx : E->ReuseShuffleIndices) {
6845               if (Idx != Sz && Idx != UndefMaskElem &&
6846                   UsedIdxs.insert(Idx).second)
6847                 UniqueIdxs[Idx] = Pos;
6848               ++Pos;
6849             }
6850             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6851                                             "less than original vector size.");
6852             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6853             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6854           } else {
6855             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6856                    "Expected vectorization factor less "
6857                    "than original vector size.");
6858             SmallVector<int> UniformMask(VF, 0);
6859             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6860             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6861           }
6862           if (auto *I = dyn_cast<Instruction>(V)) {
6863             GatherShuffleSeq.insert(I);
6864             CSEBlocks.insert(I->getParent());
6865           }
6866         }
6867         return V;
6868       }
6869   }
6870 
6871   // Can't vectorize this, so simply build a new vector with each lane
6872   // corresponding to the requested value.
6873   return createBuildVector(VL);
6874 }
6875 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6876   unsigned VF = VL.size();
6877   // Exploit possible reuse of values across lanes.
6878   SmallVector<int> ReuseShuffleIndicies;
6879   SmallVector<Value *> UniqueValues;
6880   if (VL.size() > 2) {
6881     DenseMap<Value *, unsigned> UniquePositions;
6882     unsigned NumValues =
6883         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6884                                     return !isa<UndefValue>(V);
6885                                   }).base());
6886     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6887     int UniqueVals = 0;
6888     for (Value *V : VL.drop_back(VL.size() - VF)) {
6889       if (isa<UndefValue>(V)) {
6890         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6891         continue;
6892       }
6893       if (isConstant(V)) {
6894         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6895         UniqueValues.emplace_back(V);
6896         continue;
6897       }
6898       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6899       ReuseShuffleIndicies.emplace_back(Res.first->second);
6900       if (Res.second) {
6901         UniqueValues.emplace_back(V);
6902         ++UniqueVals;
6903       }
6904     }
6905     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6906       // Emit pure splat vector.
6907       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6908                                   UndefMaskElem);
6909     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6910       ReuseShuffleIndicies.clear();
6911       UniqueValues.clear();
6912       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6913     }
6914     UniqueValues.append(VF - UniqueValues.size(),
6915                         PoisonValue::get(VL[0]->getType()));
6916     VL = UniqueValues;
6917   }
6918 
6919   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6920                                            CSEBlocks);
6921   Value *Vec = gather(VL);
6922   if (!ReuseShuffleIndicies.empty()) {
6923     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6924     Vec = ShuffleBuilder.finalize(Vec);
6925   }
6926   return Vec;
6927 }
6928 
6929 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6930   IRBuilder<>::InsertPointGuard Guard(Builder);
6931 
6932   if (E->VectorizedValue) {
6933     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6934     return E->VectorizedValue;
6935   }
6936 
6937   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6938   unsigned VF = E->getVectorFactor();
6939   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6940                                            CSEBlocks);
6941   if (E->State == TreeEntry::NeedToGather) {
6942     if (E->getMainOp())
6943       setInsertPointAfterBundle(E);
6944     Value *Vec;
6945     SmallVector<int> Mask;
6946     SmallVector<const TreeEntry *> Entries;
6947     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6948         isGatherShuffledEntry(E, Mask, Entries);
6949     if (Shuffle.hasValue()) {
6950       assert((Entries.size() == 1 || Entries.size() == 2) &&
6951              "Expected shuffle of 1 or 2 entries.");
6952       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6953                                         Entries.back()->VectorizedValue, Mask);
6954       if (auto *I = dyn_cast<Instruction>(Vec)) {
6955         GatherShuffleSeq.insert(I);
6956         CSEBlocks.insert(I->getParent());
6957       }
6958     } else {
6959       Vec = gather(E->Scalars);
6960     }
6961     if (NeedToShuffleReuses) {
6962       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6963       Vec = ShuffleBuilder.finalize(Vec);
6964     }
6965     E->VectorizedValue = Vec;
6966     return Vec;
6967   }
6968 
6969   assert((E->State == TreeEntry::Vectorize ||
6970           E->State == TreeEntry::ScatterVectorize) &&
6971          "Unhandled state");
6972   unsigned ShuffleOrOp =
6973       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6974   Instruction *VL0 = E->getMainOp();
6975   Type *ScalarTy = VL0->getType();
6976   if (auto *Store = dyn_cast<StoreInst>(VL0))
6977     ScalarTy = Store->getValueOperand()->getType();
6978   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6979     ScalarTy = IE->getOperand(1)->getType();
6980   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6981   switch (ShuffleOrOp) {
6982     case Instruction::PHI: {
6983       assert(
6984           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6985           "PHI reordering is free.");
6986       auto *PH = cast<PHINode>(VL0);
6987       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6988       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6989       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6990       Value *V = NewPhi;
6991 
6992       // Adjust insertion point once all PHI's have been generated.
6993       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6994       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6995 
6996       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6997       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6998       V = ShuffleBuilder.finalize(V);
6999 
7000       E->VectorizedValue = V;
7001 
7002       // PHINodes may have multiple entries from the same block. We want to
7003       // visit every block once.
7004       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7005 
7006       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7007         ValueList Operands;
7008         BasicBlock *IBB = PH->getIncomingBlock(i);
7009 
7010         if (!VisitedBBs.insert(IBB).second) {
7011           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7012           continue;
7013         }
7014 
7015         Builder.SetInsertPoint(IBB->getTerminator());
7016         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7017         Value *Vec = vectorizeTree(E->getOperand(i));
7018         NewPhi->addIncoming(Vec, IBB);
7019       }
7020 
7021       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7022              "Invalid number of incoming values");
7023       return V;
7024     }
7025 
7026     case Instruction::ExtractElement: {
7027       Value *V = E->getSingleOperand(0);
7028       Builder.SetInsertPoint(VL0);
7029       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7030       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7031       V = ShuffleBuilder.finalize(V);
7032       E->VectorizedValue = V;
7033       return V;
7034     }
7035     case Instruction::ExtractValue: {
7036       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7037       Builder.SetInsertPoint(LI);
7038       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7039       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7040       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7041       Value *NewV = propagateMetadata(V, E->Scalars);
7042       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7043       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7044       NewV = ShuffleBuilder.finalize(NewV);
7045       E->VectorizedValue = NewV;
7046       return NewV;
7047     }
7048     case Instruction::InsertElement: {
7049       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7050       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7051       Value *V = vectorizeTree(E->getOperand(1));
7052 
7053       // Create InsertVector shuffle if necessary
7054       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7055         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7056       }));
7057       const unsigned NumElts =
7058           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7059       const unsigned NumScalars = E->Scalars.size();
7060 
7061       unsigned Offset = *getInsertIndex(VL0);
7062       assert(Offset < NumElts && "Failed to find vector index offset");
7063 
7064       // Create shuffle to resize vector
7065       SmallVector<int> Mask;
7066       if (!E->ReorderIndices.empty()) {
7067         inversePermutation(E->ReorderIndices, Mask);
7068         Mask.append(NumElts - NumScalars, UndefMaskElem);
7069       } else {
7070         Mask.assign(NumElts, UndefMaskElem);
7071         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7072       }
7073       // Create InsertVector shuffle if necessary
7074       bool IsIdentity = true;
7075       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7076       Mask.swap(PrevMask);
7077       for (unsigned I = 0; I < NumScalars; ++I) {
7078         Value *Scalar = E->Scalars[PrevMask[I]];
7079         unsigned InsertIdx = *getInsertIndex(Scalar);
7080         IsIdentity &= InsertIdx - Offset == I;
7081         Mask[InsertIdx - Offset] = I;
7082       }
7083       if (!IsIdentity || NumElts != NumScalars) {
7084         V = Builder.CreateShuffleVector(V, Mask);
7085         if (auto *I = dyn_cast<Instruction>(V)) {
7086           GatherShuffleSeq.insert(I);
7087           CSEBlocks.insert(I->getParent());
7088         }
7089       }
7090 
7091       if ((!IsIdentity || Offset != 0 ||
7092            !isUndefVector(FirstInsert->getOperand(0))) &&
7093           NumElts != NumScalars) {
7094         SmallVector<int> InsertMask(NumElts);
7095         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7096         for (unsigned I = 0; I < NumElts; I++) {
7097           if (Mask[I] != UndefMaskElem)
7098             InsertMask[Offset + I] = NumElts + I;
7099         }
7100 
7101         V = Builder.CreateShuffleVector(
7102             FirstInsert->getOperand(0), V, InsertMask,
7103             cast<Instruction>(E->Scalars.back())->getName());
7104         if (auto *I = dyn_cast<Instruction>(V)) {
7105           GatherShuffleSeq.insert(I);
7106           CSEBlocks.insert(I->getParent());
7107         }
7108       }
7109 
7110       ++NumVectorInstructions;
7111       E->VectorizedValue = V;
7112       return V;
7113     }
7114     case Instruction::ZExt:
7115     case Instruction::SExt:
7116     case Instruction::FPToUI:
7117     case Instruction::FPToSI:
7118     case Instruction::FPExt:
7119     case Instruction::PtrToInt:
7120     case Instruction::IntToPtr:
7121     case Instruction::SIToFP:
7122     case Instruction::UIToFP:
7123     case Instruction::Trunc:
7124     case Instruction::FPTrunc:
7125     case Instruction::BitCast: {
7126       setInsertPointAfterBundle(E);
7127 
7128       Value *InVec = vectorizeTree(E->getOperand(0));
7129 
7130       if (E->VectorizedValue) {
7131         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7132         return E->VectorizedValue;
7133       }
7134 
7135       auto *CI = cast<CastInst>(VL0);
7136       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7137       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7138       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7139       V = ShuffleBuilder.finalize(V);
7140 
7141       E->VectorizedValue = V;
7142       ++NumVectorInstructions;
7143       return V;
7144     }
7145     case Instruction::FCmp:
7146     case Instruction::ICmp: {
7147       setInsertPointAfterBundle(E);
7148 
7149       Value *L = vectorizeTree(E->getOperand(0));
7150       Value *R = vectorizeTree(E->getOperand(1));
7151 
7152       if (E->VectorizedValue) {
7153         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7154         return E->VectorizedValue;
7155       }
7156 
7157       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7158       Value *V = Builder.CreateCmp(P0, L, R);
7159       propagateIRFlags(V, E->Scalars, VL0);
7160       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7161       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7162       V = ShuffleBuilder.finalize(V);
7163 
7164       E->VectorizedValue = V;
7165       ++NumVectorInstructions;
7166       return V;
7167     }
7168     case Instruction::Select: {
7169       setInsertPointAfterBundle(E);
7170 
7171       Value *Cond = vectorizeTree(E->getOperand(0));
7172       Value *True = vectorizeTree(E->getOperand(1));
7173       Value *False = vectorizeTree(E->getOperand(2));
7174 
7175       if (E->VectorizedValue) {
7176         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7177         return E->VectorizedValue;
7178       }
7179 
7180       Value *V = Builder.CreateSelect(Cond, True, False);
7181       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7182       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7183       V = ShuffleBuilder.finalize(V);
7184 
7185       E->VectorizedValue = V;
7186       ++NumVectorInstructions;
7187       return V;
7188     }
7189     case Instruction::FNeg: {
7190       setInsertPointAfterBundle(E);
7191 
7192       Value *Op = vectorizeTree(E->getOperand(0));
7193 
7194       if (E->VectorizedValue) {
7195         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7196         return E->VectorizedValue;
7197       }
7198 
7199       Value *V = Builder.CreateUnOp(
7200           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7201       propagateIRFlags(V, E->Scalars, VL0);
7202       if (auto *I = dyn_cast<Instruction>(V))
7203         V = propagateMetadata(I, E->Scalars);
7204 
7205       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7206       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7207       V = ShuffleBuilder.finalize(V);
7208 
7209       E->VectorizedValue = V;
7210       ++NumVectorInstructions;
7211 
7212       return V;
7213     }
7214     case Instruction::Add:
7215     case Instruction::FAdd:
7216     case Instruction::Sub:
7217     case Instruction::FSub:
7218     case Instruction::Mul:
7219     case Instruction::FMul:
7220     case Instruction::UDiv:
7221     case Instruction::SDiv:
7222     case Instruction::FDiv:
7223     case Instruction::URem:
7224     case Instruction::SRem:
7225     case Instruction::FRem:
7226     case Instruction::Shl:
7227     case Instruction::LShr:
7228     case Instruction::AShr:
7229     case Instruction::And:
7230     case Instruction::Or:
7231     case Instruction::Xor: {
7232       setInsertPointAfterBundle(E);
7233 
7234       Value *LHS = vectorizeTree(E->getOperand(0));
7235       Value *RHS = vectorizeTree(E->getOperand(1));
7236 
7237       if (E->VectorizedValue) {
7238         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7239         return E->VectorizedValue;
7240       }
7241 
7242       Value *V = Builder.CreateBinOp(
7243           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7244           RHS);
7245       propagateIRFlags(V, E->Scalars, VL0);
7246       if (auto *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::Load: {
7259       // Loads are inserted at the head of the tree because we don't want to
7260       // sink them all the way down past store instructions.
7261       setInsertPointAfterBundle(E);
7262 
7263       LoadInst *LI = cast<LoadInst>(VL0);
7264       Instruction *NewLI;
7265       unsigned AS = LI->getPointerAddressSpace();
7266       Value *PO = LI->getPointerOperand();
7267       if (E->State == TreeEntry::Vectorize) {
7268         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7269         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7270 
7271         // The pointer operand uses an in-tree scalar so we add the new BitCast
7272         // or LoadInst to ExternalUses list to make sure that an extract will
7273         // be generated in the future.
7274         if (TreeEntry *Entry = getTreeEntry(PO)) {
7275           // Find which lane we need to extract.
7276           unsigned FoundLane = Entry->findLaneForValue(PO);
7277           ExternalUses.emplace_back(
7278               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7279         }
7280       } else {
7281         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7282         Value *VecPtr = vectorizeTree(E->getOperand(0));
7283         // Use the minimum alignment of the gathered loads.
7284         Align CommonAlignment = LI->getAlign();
7285         for (Value *V : E->Scalars)
7286           CommonAlignment =
7287               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7288         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7289       }
7290       Value *V = propagateMetadata(NewLI, E->Scalars);
7291 
7292       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7293       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7294       V = ShuffleBuilder.finalize(V);
7295       E->VectorizedValue = V;
7296       ++NumVectorInstructions;
7297       return V;
7298     }
7299     case Instruction::Store: {
7300       auto *SI = cast<StoreInst>(VL0);
7301       unsigned AS = SI->getPointerAddressSpace();
7302 
7303       setInsertPointAfterBundle(E);
7304 
7305       Value *VecValue = vectorizeTree(E->getOperand(0));
7306       ShuffleBuilder.addMask(E->ReorderIndices);
7307       VecValue = ShuffleBuilder.finalize(VecValue);
7308 
7309       Value *ScalarPtr = SI->getPointerOperand();
7310       Value *VecPtr = Builder.CreateBitCast(
7311           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7312       StoreInst *ST =
7313           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7314 
7315       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7316       // StoreInst to ExternalUses to make sure that an extract will be
7317       // generated in the future.
7318       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7319         // Find which lane we need to extract.
7320         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7321         ExternalUses.push_back(ExternalUser(
7322             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7323             FoundLane));
7324       }
7325 
7326       Value *V = propagateMetadata(ST, E->Scalars);
7327 
7328       E->VectorizedValue = V;
7329       ++NumVectorInstructions;
7330       return V;
7331     }
7332     case Instruction::GetElementPtr: {
7333       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7334       setInsertPointAfterBundle(E);
7335 
7336       Value *Op0 = vectorizeTree(E->getOperand(0));
7337 
7338       SmallVector<Value *> OpVecs;
7339       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7340         Value *OpVec = vectorizeTree(E->getOperand(J));
7341         OpVecs.push_back(OpVec);
7342       }
7343 
7344       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7345       if (Instruction *I = dyn_cast<Instruction>(V))
7346         V = propagateMetadata(I, E->Scalars);
7347 
7348       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7349       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7350       V = ShuffleBuilder.finalize(V);
7351 
7352       E->VectorizedValue = V;
7353       ++NumVectorInstructions;
7354 
7355       return V;
7356     }
7357     case Instruction::Call: {
7358       CallInst *CI = cast<CallInst>(VL0);
7359       setInsertPointAfterBundle(E);
7360 
7361       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7362       if (Function *FI = CI->getCalledFunction())
7363         IID = FI->getIntrinsicID();
7364 
7365       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7366 
7367       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7368       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7369                           VecCallCosts.first <= VecCallCosts.second;
7370 
7371       Value *ScalarArg = nullptr;
7372       std::vector<Value *> OpVecs;
7373       SmallVector<Type *, 2> TysForDecl =
7374           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7375       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7376         ValueList OpVL;
7377         // Some intrinsics have scalar arguments. This argument should not be
7378         // vectorized.
7379         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7380           CallInst *CEI = cast<CallInst>(VL0);
7381           ScalarArg = CEI->getArgOperand(j);
7382           OpVecs.push_back(CEI->getArgOperand(j));
7383           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7384             TysForDecl.push_back(ScalarArg->getType());
7385           continue;
7386         }
7387 
7388         Value *OpVec = vectorizeTree(E->getOperand(j));
7389         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7390         OpVecs.push_back(OpVec);
7391       }
7392 
7393       Function *CF;
7394       if (!UseIntrinsic) {
7395         VFShape Shape =
7396             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7397                                   VecTy->getNumElements())),
7398                          false /*HasGlobalPred*/);
7399         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7400       } else {
7401         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7402       }
7403 
7404       SmallVector<OperandBundleDef, 1> OpBundles;
7405       CI->getOperandBundlesAsDefs(OpBundles);
7406       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7407 
7408       // The scalar argument uses an in-tree scalar so we add the new vectorized
7409       // call to ExternalUses list to make sure that an extract will be
7410       // generated in the future.
7411       if (ScalarArg) {
7412         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7413           // Find which lane we need to extract.
7414           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7415           ExternalUses.push_back(
7416               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7417         }
7418       }
7419 
7420       propagateIRFlags(V, E->Scalars, VL0);
7421       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7422       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7423       V = ShuffleBuilder.finalize(V);
7424 
7425       E->VectorizedValue = V;
7426       ++NumVectorInstructions;
7427       return V;
7428     }
7429     case Instruction::ShuffleVector: {
7430       assert(E->isAltShuffle() &&
7431              ((Instruction::isBinaryOp(E->getOpcode()) &&
7432                Instruction::isBinaryOp(E->getAltOpcode())) ||
7433               (Instruction::isCast(E->getOpcode()) &&
7434                Instruction::isCast(E->getAltOpcode())) ||
7435               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7436              "Invalid Shuffle Vector Operand");
7437 
7438       Value *LHS = nullptr, *RHS = nullptr;
7439       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7440         setInsertPointAfterBundle(E);
7441         LHS = vectorizeTree(E->getOperand(0));
7442         RHS = vectorizeTree(E->getOperand(1));
7443       } else {
7444         setInsertPointAfterBundle(E);
7445         LHS = vectorizeTree(E->getOperand(0));
7446       }
7447 
7448       if (E->VectorizedValue) {
7449         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7450         return E->VectorizedValue;
7451       }
7452 
7453       Value *V0, *V1;
7454       if (Instruction::isBinaryOp(E->getOpcode())) {
7455         V0 = Builder.CreateBinOp(
7456             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7457         V1 = Builder.CreateBinOp(
7458             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7459       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7460         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7461         auto *AltCI = cast<CmpInst>(E->getAltOp());
7462         CmpInst::Predicate AltPred = AltCI->getPredicate();
7463         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7464       } else {
7465         V0 = Builder.CreateCast(
7466             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7467         V1 = Builder.CreateCast(
7468             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7469       }
7470       // Add V0 and V1 to later analysis to try to find and remove matching
7471       // instruction, if any.
7472       for (Value *V : {V0, V1}) {
7473         if (auto *I = dyn_cast<Instruction>(V)) {
7474           GatherShuffleSeq.insert(I);
7475           CSEBlocks.insert(I->getParent());
7476         }
7477       }
7478 
7479       // Create shuffle to take alternate operations from the vector.
7480       // Also, gather up main and alt scalar ops to propagate IR flags to
7481       // each vector operation.
7482       ValueList OpScalars, AltScalars;
7483       SmallVector<int> Mask;
7484       buildShuffleEntryMask(
7485           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7486           [E](Instruction *I) {
7487             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7488             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7489           },
7490           Mask, &OpScalars, &AltScalars);
7491 
7492       propagateIRFlags(V0, OpScalars);
7493       propagateIRFlags(V1, AltScalars);
7494 
7495       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7496       if (auto *I = dyn_cast<Instruction>(V)) {
7497         V = propagateMetadata(I, E->Scalars);
7498         GatherShuffleSeq.insert(I);
7499         CSEBlocks.insert(I->getParent());
7500       }
7501       V = ShuffleBuilder.finalize(V);
7502 
7503       E->VectorizedValue = V;
7504       ++NumVectorInstructions;
7505 
7506       return V;
7507     }
7508     default:
7509     llvm_unreachable("unknown inst");
7510   }
7511   return nullptr;
7512 }
7513 
7514 Value *BoUpSLP::vectorizeTree() {
7515   ExtraValueToDebugLocsMap ExternallyUsedValues;
7516   return vectorizeTree(ExternallyUsedValues);
7517 }
7518 
7519 Value *
7520 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7521   // All blocks must be scheduled before any instructions are inserted.
7522   for (auto &BSIter : BlocksSchedules) {
7523     scheduleBlock(BSIter.second.get());
7524   }
7525 
7526   Builder.SetInsertPoint(&F->getEntryBlock().front());
7527   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7528 
7529   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7530   // vectorized root. InstCombine will then rewrite the entire expression. We
7531   // sign extend the extracted values below.
7532   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7533   if (MinBWs.count(ScalarRoot)) {
7534     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7535       // If current instr is a phi and not the last phi, insert it after the
7536       // last phi node.
7537       if (isa<PHINode>(I))
7538         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7539       else
7540         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7541     }
7542     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7543     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7544     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7545     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7546     VectorizableTree[0]->VectorizedValue = Trunc;
7547   }
7548 
7549   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7550                     << " values .\n");
7551 
7552   // Extract all of the elements with the external uses.
7553   for (const auto &ExternalUse : ExternalUses) {
7554     Value *Scalar = ExternalUse.Scalar;
7555     llvm::User *User = ExternalUse.User;
7556 
7557     // Skip users that we already RAUW. This happens when one instruction
7558     // has multiple uses of the same value.
7559     if (User && !is_contained(Scalar->users(), User))
7560       continue;
7561     TreeEntry *E = getTreeEntry(Scalar);
7562     assert(E && "Invalid scalar");
7563     assert(E->State != TreeEntry::NeedToGather &&
7564            "Extracting from a gather list");
7565 
7566     Value *Vec = E->VectorizedValue;
7567     assert(Vec && "Can't find vectorizable value");
7568 
7569     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7570     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7571       if (Scalar->getType() != Vec->getType()) {
7572         Value *Ex;
7573         // "Reuse" the existing extract to improve final codegen.
7574         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7575           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7576                                             ES->getOperand(1));
7577         } else {
7578           Ex = Builder.CreateExtractElement(Vec, Lane);
7579         }
7580         // If necessary, sign-extend or zero-extend ScalarRoot
7581         // to the larger type.
7582         if (!MinBWs.count(ScalarRoot))
7583           return Ex;
7584         if (MinBWs[ScalarRoot].second)
7585           return Builder.CreateSExt(Ex, Scalar->getType());
7586         return Builder.CreateZExt(Ex, Scalar->getType());
7587       }
7588       assert(isa<FixedVectorType>(Scalar->getType()) &&
7589              isa<InsertElementInst>(Scalar) &&
7590              "In-tree scalar of vector type is not insertelement?");
7591       return Vec;
7592     };
7593     // If User == nullptr, the Scalar is used as extra arg. Generate
7594     // ExtractElement instruction and update the record for this scalar in
7595     // ExternallyUsedValues.
7596     if (!User) {
7597       assert(ExternallyUsedValues.count(Scalar) &&
7598              "Scalar with nullptr as an external user must be registered in "
7599              "ExternallyUsedValues map");
7600       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7601         Builder.SetInsertPoint(VecI->getParent(),
7602                                std::next(VecI->getIterator()));
7603       } else {
7604         Builder.SetInsertPoint(&F->getEntryBlock().front());
7605       }
7606       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7607       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7608       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7609       auto It = ExternallyUsedValues.find(Scalar);
7610       assert(It != ExternallyUsedValues.end() &&
7611              "Externally used scalar is not found in ExternallyUsedValues");
7612       NewInstLocs.append(It->second);
7613       ExternallyUsedValues.erase(Scalar);
7614       // Required to update internally referenced instructions.
7615       Scalar->replaceAllUsesWith(NewInst);
7616       continue;
7617     }
7618 
7619     // Generate extracts for out-of-tree users.
7620     // Find the insertion point for the extractelement lane.
7621     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7622       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7623         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7624           if (PH->getIncomingValue(i) == Scalar) {
7625             Instruction *IncomingTerminator =
7626                 PH->getIncomingBlock(i)->getTerminator();
7627             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7628               Builder.SetInsertPoint(VecI->getParent(),
7629                                      std::next(VecI->getIterator()));
7630             } else {
7631               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7632             }
7633             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7634             CSEBlocks.insert(PH->getIncomingBlock(i));
7635             PH->setOperand(i, NewInst);
7636           }
7637         }
7638       } else {
7639         Builder.SetInsertPoint(cast<Instruction>(User));
7640         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7641         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7642         User->replaceUsesOfWith(Scalar, NewInst);
7643       }
7644     } else {
7645       Builder.SetInsertPoint(&F->getEntryBlock().front());
7646       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7647       CSEBlocks.insert(&F->getEntryBlock());
7648       User->replaceUsesOfWith(Scalar, NewInst);
7649     }
7650 
7651     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7652   }
7653 
7654   // For each vectorized value:
7655   for (auto &TEPtr : VectorizableTree) {
7656     TreeEntry *Entry = TEPtr.get();
7657 
7658     // No need to handle users of gathered values.
7659     if (Entry->State == TreeEntry::NeedToGather)
7660       continue;
7661 
7662     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7663 
7664     // For each lane:
7665     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7666       Value *Scalar = Entry->Scalars[Lane];
7667 
7668 #ifndef NDEBUG
7669       Type *Ty = Scalar->getType();
7670       if (!Ty->isVoidTy()) {
7671         for (User *U : Scalar->users()) {
7672           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7673 
7674           // It is legal to delete users in the ignorelist.
7675           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7676                   (isa_and_nonnull<Instruction>(U) &&
7677                    isDeleted(cast<Instruction>(U)))) &&
7678                  "Deleting out-of-tree value");
7679         }
7680       }
7681 #endif
7682       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7683       eraseInstruction(cast<Instruction>(Scalar));
7684     }
7685   }
7686 
7687   Builder.ClearInsertionPoint();
7688   InstrElementSize.clear();
7689 
7690   return VectorizableTree[0]->VectorizedValue;
7691 }
7692 
7693 void BoUpSLP::optimizeGatherSequence() {
7694   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7695                     << " gather sequences instructions.\n");
7696   // LICM InsertElementInst sequences.
7697   for (Instruction *I : GatherShuffleSeq) {
7698     if (isDeleted(I))
7699       continue;
7700 
7701     // Check if this block is inside a loop.
7702     Loop *L = LI->getLoopFor(I->getParent());
7703     if (!L)
7704       continue;
7705 
7706     // Check if it has a preheader.
7707     BasicBlock *PreHeader = L->getLoopPreheader();
7708     if (!PreHeader)
7709       continue;
7710 
7711     // If the vector or the element that we insert into it are
7712     // instructions that are defined in this basic block then we can't
7713     // hoist this instruction.
7714     if (any_of(I->operands(), [L](Value *V) {
7715           auto *OpI = dyn_cast<Instruction>(V);
7716           return OpI && L->contains(OpI);
7717         }))
7718       continue;
7719 
7720     // We can hoist this instruction. Move it to the pre-header.
7721     I->moveBefore(PreHeader->getTerminator());
7722   }
7723 
7724   // Make a list of all reachable blocks in our CSE queue.
7725   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7726   CSEWorkList.reserve(CSEBlocks.size());
7727   for (BasicBlock *BB : CSEBlocks)
7728     if (DomTreeNode *N = DT->getNode(BB)) {
7729       assert(DT->isReachableFromEntry(N));
7730       CSEWorkList.push_back(N);
7731     }
7732 
7733   // Sort blocks by domination. This ensures we visit a block after all blocks
7734   // dominating it are visited.
7735   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7736     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7737            "Different nodes should have different DFS numbers");
7738     return A->getDFSNumIn() < B->getDFSNumIn();
7739   });
7740 
7741   // Less defined shuffles can be replaced by the more defined copies.
7742   // Between two shuffles one is less defined if it has the same vector operands
7743   // and its mask indeces are the same as in the first one or undefs. E.g.
7744   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7745   // poison, <0, 0, 0, 0>.
7746   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7747                                            SmallVectorImpl<int> &NewMask) {
7748     if (I1->getType() != I2->getType())
7749       return false;
7750     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7751     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7752     if (!SI1 || !SI2)
7753       return I1->isIdenticalTo(I2);
7754     if (SI1->isIdenticalTo(SI2))
7755       return true;
7756     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7757       if (SI1->getOperand(I) != SI2->getOperand(I))
7758         return false;
7759     // Check if the second instruction is more defined than the first one.
7760     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7761     ArrayRef<int> SM1 = SI1->getShuffleMask();
7762     // Count trailing undefs in the mask to check the final number of used
7763     // registers.
7764     unsigned LastUndefsCnt = 0;
7765     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7766       if (SM1[I] == UndefMaskElem)
7767         ++LastUndefsCnt;
7768       else
7769         LastUndefsCnt = 0;
7770       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7771           NewMask[I] != SM1[I])
7772         return false;
7773       if (NewMask[I] == UndefMaskElem)
7774         NewMask[I] = SM1[I];
7775     }
7776     // Check if the last undefs actually change the final number of used vector
7777     // registers.
7778     return SM1.size() - LastUndefsCnt > 1 &&
7779            TTI->getNumberOfParts(SI1->getType()) ==
7780                TTI->getNumberOfParts(
7781                    FixedVectorType::get(SI1->getType()->getElementType(),
7782                                         SM1.size() - LastUndefsCnt));
7783   };
7784   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7785   // instructions. TODO: We can further optimize this scan if we split the
7786   // instructions into different buckets based on the insert lane.
7787   SmallVector<Instruction *, 16> Visited;
7788   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7789     assert(*I &&
7790            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7791            "Worklist not sorted properly!");
7792     BasicBlock *BB = (*I)->getBlock();
7793     // For all instructions in blocks containing gather sequences:
7794     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7795       if (isDeleted(&In))
7796         continue;
7797       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7798           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7799         continue;
7800 
7801       // Check if we can replace this instruction with any of the
7802       // visited instructions.
7803       bool Replaced = false;
7804       for (Instruction *&V : Visited) {
7805         SmallVector<int> NewMask;
7806         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7807             DT->dominates(V->getParent(), In.getParent())) {
7808           In.replaceAllUsesWith(V);
7809           eraseInstruction(&In);
7810           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7811             if (!NewMask.empty())
7812               SI->setShuffleMask(NewMask);
7813           Replaced = true;
7814           break;
7815         }
7816         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7817             GatherShuffleSeq.contains(V) &&
7818             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7819             DT->dominates(In.getParent(), V->getParent())) {
7820           In.moveAfter(V);
7821           V->replaceAllUsesWith(&In);
7822           eraseInstruction(V);
7823           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7824             if (!NewMask.empty())
7825               SI->setShuffleMask(NewMask);
7826           V = &In;
7827           Replaced = true;
7828           break;
7829         }
7830       }
7831       if (!Replaced) {
7832         assert(!is_contained(Visited, &In));
7833         Visited.push_back(&In);
7834       }
7835     }
7836   }
7837   CSEBlocks.clear();
7838   GatherShuffleSeq.clear();
7839 }
7840 
7841 BoUpSLP::ScheduleData *
7842 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7843   ScheduleData *Bundle = nullptr;
7844   ScheduleData *PrevInBundle = nullptr;
7845   for (Value *V : VL) {
7846     if (doesNotNeedToBeScheduled(V))
7847       continue;
7848     ScheduleData *BundleMember = getScheduleData(V);
7849     assert(BundleMember &&
7850            "no ScheduleData for bundle member "
7851            "(maybe not in same basic block)");
7852     assert(BundleMember->isSchedulingEntity() &&
7853            "bundle member already part of other bundle");
7854     if (PrevInBundle) {
7855       PrevInBundle->NextInBundle = BundleMember;
7856     } else {
7857       Bundle = BundleMember;
7858     }
7859 
7860     // Group the instructions to a bundle.
7861     BundleMember->FirstInBundle = Bundle;
7862     PrevInBundle = BundleMember;
7863   }
7864   assert(Bundle && "Failed to find schedule bundle");
7865   return Bundle;
7866 }
7867 
7868 // Groups the instructions to a bundle (which is then a single scheduling entity)
7869 // and schedules instructions until the bundle gets ready.
7870 Optional<BoUpSLP::ScheduleData *>
7871 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7872                                             const InstructionsState &S) {
7873   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7874   // instructions.
7875   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7876       doesNotNeedToSchedule(VL))
7877     return nullptr;
7878 
7879   // Initialize the instruction bundle.
7880   Instruction *OldScheduleEnd = ScheduleEnd;
7881   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7882 
7883   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7884                                                          ScheduleData *Bundle) {
7885     // The scheduling region got new instructions at the lower end (or it is a
7886     // new region for the first bundle). This makes it necessary to
7887     // recalculate all dependencies.
7888     // It is seldom that this needs to be done a second time after adding the
7889     // initial bundle to the region.
7890     if (ScheduleEnd != OldScheduleEnd) {
7891       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7892         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7893       ReSchedule = true;
7894     }
7895     if (Bundle) {
7896       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7897                         << " in block " << BB->getName() << "\n");
7898       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7899     }
7900 
7901     if (ReSchedule) {
7902       resetSchedule();
7903       initialFillReadyList(ReadyInsts);
7904     }
7905 
7906     // Now try to schedule the new bundle or (if no bundle) just calculate
7907     // dependencies. As soon as the bundle is "ready" it means that there are no
7908     // cyclic dependencies and we can schedule it. Note that's important that we
7909     // don't "schedule" the bundle yet (see cancelScheduling).
7910     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7911            !ReadyInsts.empty()) {
7912       ScheduleData *Picked = ReadyInsts.pop_back_val();
7913       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7914              "must be ready to schedule");
7915       schedule(Picked, ReadyInsts);
7916     }
7917   };
7918 
7919   // Make sure that the scheduling region contains all
7920   // instructions of the bundle.
7921   for (Value *V : VL) {
7922     if (doesNotNeedToBeScheduled(V))
7923       continue;
7924     if (!extendSchedulingRegion(V, S)) {
7925       // If the scheduling region got new instructions at the lower end (or it
7926       // is a new region for the first bundle). This makes it necessary to
7927       // recalculate all dependencies.
7928       // Otherwise the compiler may crash trying to incorrectly calculate
7929       // dependencies and emit instruction in the wrong order at the actual
7930       // scheduling.
7931       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7932       return None;
7933     }
7934   }
7935 
7936   bool ReSchedule = false;
7937   for (Value *V : VL) {
7938     if (doesNotNeedToBeScheduled(V))
7939       continue;
7940     ScheduleData *BundleMember = getScheduleData(V);
7941     assert(BundleMember &&
7942            "no ScheduleData for bundle member (maybe not in same basic block)");
7943 
7944     // Make sure we don't leave the pieces of the bundle in the ready list when
7945     // whole bundle might not be ready.
7946     ReadyInsts.remove(BundleMember);
7947 
7948     if (!BundleMember->IsScheduled)
7949       continue;
7950     // A bundle member was scheduled as single instruction before and now
7951     // needs to be scheduled as part of the bundle. We just get rid of the
7952     // existing schedule.
7953     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7954                       << " was already scheduled\n");
7955     ReSchedule = true;
7956   }
7957 
7958   auto *Bundle = buildBundle(VL);
7959   TryScheduleBundleImpl(ReSchedule, Bundle);
7960   if (!Bundle->isReady()) {
7961     cancelScheduling(VL, S.OpValue);
7962     return None;
7963   }
7964   return Bundle;
7965 }
7966 
7967 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7968                                                 Value *OpValue) {
7969   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7970       doesNotNeedToSchedule(VL))
7971     return;
7972 
7973   if (doesNotNeedToBeScheduled(OpValue))
7974     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7975   ScheduleData *Bundle = getScheduleData(OpValue);
7976   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7977   assert(!Bundle->IsScheduled &&
7978          "Can't cancel bundle which is already scheduled");
7979   assert(Bundle->isSchedulingEntity() &&
7980          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7981          "tried to unbundle something which is not a bundle");
7982 
7983   // Remove the bundle from the ready list.
7984   if (Bundle->isReady())
7985     ReadyInsts.remove(Bundle);
7986 
7987   // Un-bundle: make single instructions out of the bundle.
7988   ScheduleData *BundleMember = Bundle;
7989   while (BundleMember) {
7990     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7991     BundleMember->FirstInBundle = BundleMember;
7992     ScheduleData *Next = BundleMember->NextInBundle;
7993     BundleMember->NextInBundle = nullptr;
7994     BundleMember->TE = nullptr;
7995     if (BundleMember->unscheduledDepsInBundle() == 0) {
7996       ReadyInsts.insert(BundleMember);
7997     }
7998     BundleMember = Next;
7999   }
8000 }
8001 
8002 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8003   // Allocate a new ScheduleData for the instruction.
8004   if (ChunkPos >= ChunkSize) {
8005     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8006     ChunkPos = 0;
8007   }
8008   return &(ScheduleDataChunks.back()[ChunkPos++]);
8009 }
8010 
8011 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8012                                                       const InstructionsState &S) {
8013   if (getScheduleData(V, isOneOf(S, V)))
8014     return true;
8015   Instruction *I = dyn_cast<Instruction>(V);
8016   assert(I && "bundle member must be an instruction");
8017   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8018          !doesNotNeedToBeScheduled(I) &&
8019          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8020          "be scheduled");
8021   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8022     ScheduleData *ISD = getScheduleData(I);
8023     if (!ISD)
8024       return false;
8025     assert(isInSchedulingRegion(ISD) &&
8026            "ScheduleData not in scheduling region");
8027     ScheduleData *SD = allocateScheduleDataChunks();
8028     SD->Inst = I;
8029     SD->init(SchedulingRegionID, S.OpValue);
8030     ExtraScheduleDataMap[I][S.OpValue] = SD;
8031     return true;
8032   };
8033   if (CheckScheduleForI(I))
8034     return true;
8035   if (!ScheduleStart) {
8036     // It's the first instruction in the new region.
8037     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8038     ScheduleStart = I;
8039     ScheduleEnd = I->getNextNode();
8040     if (isOneOf(S, I) != I)
8041       CheckScheduleForI(I);
8042     assert(ScheduleEnd && "tried to vectorize a terminator?");
8043     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8044     return true;
8045   }
8046   // Search up and down at the same time, because we don't know if the new
8047   // instruction is above or below the existing scheduling region.
8048   BasicBlock::reverse_iterator UpIter =
8049       ++ScheduleStart->getIterator().getReverse();
8050   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8051   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8052   BasicBlock::iterator LowerEnd = BB->end();
8053   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8054          &*DownIter != I) {
8055     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8056       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8057       return false;
8058     }
8059 
8060     ++UpIter;
8061     ++DownIter;
8062   }
8063   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8064     assert(I->getParent() == ScheduleStart->getParent() &&
8065            "Instruction is in wrong basic block.");
8066     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8067     ScheduleStart = I;
8068     if (isOneOf(S, I) != I)
8069       CheckScheduleForI(I);
8070     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8071                       << "\n");
8072     return true;
8073   }
8074   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8075          "Expected to reach top of the basic block or instruction down the "
8076          "lower end.");
8077   assert(I->getParent() == ScheduleEnd->getParent() &&
8078          "Instruction is in wrong basic block.");
8079   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8080                    nullptr);
8081   ScheduleEnd = I->getNextNode();
8082   if (isOneOf(S, I) != I)
8083     CheckScheduleForI(I);
8084   assert(ScheduleEnd && "tried to vectorize a terminator?");
8085   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8086   return true;
8087 }
8088 
8089 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8090                                                 Instruction *ToI,
8091                                                 ScheduleData *PrevLoadStore,
8092                                                 ScheduleData *NextLoadStore) {
8093   ScheduleData *CurrentLoadStore = PrevLoadStore;
8094   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8095     // No need to allocate data for non-schedulable instructions.
8096     if (doesNotNeedToBeScheduled(I))
8097       continue;
8098     ScheduleData *SD = ScheduleDataMap.lookup(I);
8099     if (!SD) {
8100       SD = allocateScheduleDataChunks();
8101       ScheduleDataMap[I] = SD;
8102       SD->Inst = I;
8103     }
8104     assert(!isInSchedulingRegion(SD) &&
8105            "new ScheduleData already in scheduling region");
8106     SD->init(SchedulingRegionID, I);
8107 
8108     if (I->mayReadOrWriteMemory() &&
8109         (!isa<IntrinsicInst>(I) ||
8110          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8111           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8112               Intrinsic::pseudoprobe))) {
8113       // Update the linked list of memory accessing instructions.
8114       if (CurrentLoadStore) {
8115         CurrentLoadStore->NextLoadStore = SD;
8116       } else {
8117         FirstLoadStoreInRegion = SD;
8118       }
8119       CurrentLoadStore = SD;
8120     }
8121 
8122     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8123         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8124       RegionHasStackSave = true;
8125   }
8126   if (NextLoadStore) {
8127     if (CurrentLoadStore)
8128       CurrentLoadStore->NextLoadStore = NextLoadStore;
8129   } else {
8130     LastLoadStoreInRegion = CurrentLoadStore;
8131   }
8132 }
8133 
8134 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8135                                                      bool InsertInReadyList,
8136                                                      BoUpSLP *SLP) {
8137   assert(SD->isSchedulingEntity());
8138 
8139   SmallVector<ScheduleData *, 10> WorkList;
8140   WorkList.push_back(SD);
8141 
8142   while (!WorkList.empty()) {
8143     ScheduleData *SD = WorkList.pop_back_val();
8144     for (ScheduleData *BundleMember = SD; BundleMember;
8145          BundleMember = BundleMember->NextInBundle) {
8146       assert(isInSchedulingRegion(BundleMember));
8147       if (BundleMember->hasValidDependencies())
8148         continue;
8149 
8150       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8151                  << "\n");
8152       BundleMember->Dependencies = 0;
8153       BundleMember->resetUnscheduledDeps();
8154 
8155       // Handle def-use chain dependencies.
8156       if (BundleMember->OpValue != BundleMember->Inst) {
8157         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8158           BundleMember->Dependencies++;
8159           ScheduleData *DestBundle = UseSD->FirstInBundle;
8160           if (!DestBundle->IsScheduled)
8161             BundleMember->incrementUnscheduledDeps(1);
8162           if (!DestBundle->hasValidDependencies())
8163             WorkList.push_back(DestBundle);
8164         }
8165       } else {
8166         for (User *U : BundleMember->Inst->users()) {
8167           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8168             BundleMember->Dependencies++;
8169             ScheduleData *DestBundle = UseSD->FirstInBundle;
8170             if (!DestBundle->IsScheduled)
8171               BundleMember->incrementUnscheduledDeps(1);
8172             if (!DestBundle->hasValidDependencies())
8173               WorkList.push_back(DestBundle);
8174           }
8175         }
8176       }
8177 
8178       auto makeControlDependent = [&](Instruction *I) {
8179         auto *DepDest = getScheduleData(I);
8180         assert(DepDest && "must be in schedule window");
8181         DepDest->ControlDependencies.push_back(BundleMember);
8182         BundleMember->Dependencies++;
8183         ScheduleData *DestBundle = DepDest->FirstInBundle;
8184         if (!DestBundle->IsScheduled)
8185           BundleMember->incrementUnscheduledDeps(1);
8186         if (!DestBundle->hasValidDependencies())
8187           WorkList.push_back(DestBundle);
8188       };
8189 
8190       // Any instruction which isn't safe to speculate at the begining of the
8191       // block is control dependend on any early exit or non-willreturn call
8192       // which proceeds it.
8193       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8194         for (Instruction *I = BundleMember->Inst->getNextNode();
8195              I != ScheduleEnd; I = I->getNextNode()) {
8196           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8197             continue;
8198 
8199           // Add the dependency
8200           makeControlDependent(I);
8201 
8202           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8203             // Everything past here must be control dependent on I.
8204             break;
8205         }
8206       }
8207 
8208       if (RegionHasStackSave) {
8209         // If we have an inalloc alloca instruction, it needs to be scheduled
8210         // after any preceeding stacksave.  We also need to prevent any alloca
8211         // from reordering above a preceeding stackrestore.
8212         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8213             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8214           for (Instruction *I = BundleMember->Inst->getNextNode();
8215                I != ScheduleEnd; I = I->getNextNode()) {
8216             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8217                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8218               // Any allocas past here must be control dependent on I, and I
8219               // must be memory dependend on BundleMember->Inst.
8220               break;
8221 
8222             if (!isa<AllocaInst>(I))
8223               continue;
8224 
8225             // Add the dependency
8226             makeControlDependent(I);
8227           }
8228         }
8229 
8230         // In addition to the cases handle just above, we need to prevent
8231         // allocas from moving below a stacksave.  The stackrestore case
8232         // is currently thought to be conservatism.
8233         if (isa<AllocaInst>(BundleMember->Inst)) {
8234           for (Instruction *I = BundleMember->Inst->getNextNode();
8235                I != ScheduleEnd; I = I->getNextNode()) {
8236             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8237                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8238               continue;
8239 
8240             // Add the dependency
8241             makeControlDependent(I);
8242             break;
8243           }
8244         }
8245       }
8246 
8247       // Handle the memory dependencies (if any).
8248       ScheduleData *DepDest = BundleMember->NextLoadStore;
8249       if (!DepDest)
8250         continue;
8251       Instruction *SrcInst = BundleMember->Inst;
8252       assert(SrcInst->mayReadOrWriteMemory() &&
8253              "NextLoadStore list for non memory effecting bundle?");
8254       MemoryLocation SrcLoc = getLocation(SrcInst);
8255       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8256       unsigned numAliased = 0;
8257       unsigned DistToSrc = 1;
8258 
8259       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8260         assert(isInSchedulingRegion(DepDest));
8261 
8262         // We have two limits to reduce the complexity:
8263         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8264         //    SLP->isAliased (which is the expensive part in this loop).
8265         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8266         //    the whole loop (even if the loop is fast, it's quadratic).
8267         //    It's important for the loop break condition (see below) to
8268         //    check this limit even between two read-only instructions.
8269         if (DistToSrc >= MaxMemDepDistance ||
8270             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8271              (numAliased >= AliasedCheckLimit ||
8272               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8273 
8274           // We increment the counter only if the locations are aliased
8275           // (instead of counting all alias checks). This gives a better
8276           // balance between reduced runtime and accurate dependencies.
8277           numAliased++;
8278 
8279           DepDest->MemoryDependencies.push_back(BundleMember);
8280           BundleMember->Dependencies++;
8281           ScheduleData *DestBundle = DepDest->FirstInBundle;
8282           if (!DestBundle->IsScheduled) {
8283             BundleMember->incrementUnscheduledDeps(1);
8284           }
8285           if (!DestBundle->hasValidDependencies()) {
8286             WorkList.push_back(DestBundle);
8287           }
8288         }
8289 
8290         // Example, explaining the loop break condition: Let's assume our
8291         // starting instruction is i0 and MaxMemDepDistance = 3.
8292         //
8293         //                      +--------v--v--v
8294         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8295         //             +--------^--^--^
8296         //
8297         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8298         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8299         // Previously we already added dependencies from i3 to i6,i7,i8
8300         // (because of MaxMemDepDistance). As we added a dependency from
8301         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8302         // and we can abort this loop at i6.
8303         if (DistToSrc >= 2 * MaxMemDepDistance)
8304           break;
8305         DistToSrc++;
8306       }
8307     }
8308     if (InsertInReadyList && SD->isReady()) {
8309       ReadyInsts.insert(SD);
8310       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8311                         << "\n");
8312     }
8313   }
8314 }
8315 
8316 void BoUpSLP::BlockScheduling::resetSchedule() {
8317   assert(ScheduleStart &&
8318          "tried to reset schedule on block which has not been scheduled");
8319   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8320     doForAllOpcodes(I, [&](ScheduleData *SD) {
8321       assert(isInSchedulingRegion(SD) &&
8322              "ScheduleData not in scheduling region");
8323       SD->IsScheduled = false;
8324       SD->resetUnscheduledDeps();
8325     });
8326   }
8327   ReadyInsts.clear();
8328 }
8329 
8330 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8331   if (!BS->ScheduleStart)
8332     return;
8333 
8334   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8335 
8336   // A key point - if we got here, pre-scheduling was able to find a valid
8337   // scheduling of the sub-graph of the scheduling window which consists
8338   // of all vector bundles and their transitive users.  As such, we do not
8339   // need to reschedule anything *outside of* that subgraph.
8340 
8341   BS->resetSchedule();
8342 
8343   // For the real scheduling we use a more sophisticated ready-list: it is
8344   // sorted by the original instruction location. This lets the final schedule
8345   // be as  close as possible to the original instruction order.
8346   // WARNING: If changing this order causes a correctness issue, that means
8347   // there is some missing dependence edge in the schedule data graph.
8348   struct ScheduleDataCompare {
8349     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8350       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8351     }
8352   };
8353   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8354 
8355   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8356   // and fill the ready-list with initial instructions.
8357   int Idx = 0;
8358   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8359        I = I->getNextNode()) {
8360     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8361       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8362       (void)SDTE;
8363       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8364               SD->isPartOfBundle() ==
8365                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8366              "scheduler and vectorizer bundle mismatch");
8367       SD->FirstInBundle->SchedulingPriority = Idx++;
8368 
8369       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8370         BS->calculateDependencies(SD, false, this);
8371     });
8372   }
8373   BS->initialFillReadyList(ReadyInsts);
8374 
8375   Instruction *LastScheduledInst = BS->ScheduleEnd;
8376 
8377   // Do the "real" scheduling.
8378   while (!ReadyInsts.empty()) {
8379     ScheduleData *picked = *ReadyInsts.begin();
8380     ReadyInsts.erase(ReadyInsts.begin());
8381 
8382     // Move the scheduled instruction(s) to their dedicated places, if not
8383     // there yet.
8384     for (ScheduleData *BundleMember = picked; BundleMember;
8385          BundleMember = BundleMember->NextInBundle) {
8386       Instruction *pickedInst = BundleMember->Inst;
8387       if (pickedInst->getNextNode() != LastScheduledInst)
8388         pickedInst->moveBefore(LastScheduledInst);
8389       LastScheduledInst = pickedInst;
8390     }
8391 
8392     BS->schedule(picked, ReadyInsts);
8393   }
8394 
8395   // Check that we didn't break any of our invariants.
8396 #ifdef EXPENSIVE_CHECKS
8397   BS->verify();
8398 #endif
8399 
8400 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8401   // Check that all schedulable entities got scheduled
8402   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8403     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8404       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8405         assert(SD->IsScheduled && "must be scheduled at this point");
8406       }
8407     });
8408   }
8409 #endif
8410 
8411   // Avoid duplicate scheduling of the block.
8412   BS->ScheduleStart = nullptr;
8413 }
8414 
8415 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8416   // If V is a store, just return the width of the stored value (or value
8417   // truncated just before storing) without traversing the expression tree.
8418   // This is the common case.
8419   if (auto *Store = dyn_cast<StoreInst>(V)) {
8420     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8421       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8422     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8423   }
8424 
8425   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8426     return getVectorElementSize(IEI->getOperand(1));
8427 
8428   auto E = InstrElementSize.find(V);
8429   if (E != InstrElementSize.end())
8430     return E->second;
8431 
8432   // If V is not a store, we can traverse the expression tree to find loads
8433   // that feed it. The type of the loaded value may indicate a more suitable
8434   // width than V's type. We want to base the vector element size on the width
8435   // of memory operations where possible.
8436   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8437   SmallPtrSet<Instruction *, 16> Visited;
8438   if (auto *I = dyn_cast<Instruction>(V)) {
8439     Worklist.emplace_back(I, I->getParent());
8440     Visited.insert(I);
8441   }
8442 
8443   // Traverse the expression tree in bottom-up order looking for loads. If we
8444   // encounter an instruction we don't yet handle, we give up.
8445   auto Width = 0u;
8446   while (!Worklist.empty()) {
8447     Instruction *I;
8448     BasicBlock *Parent;
8449     std::tie(I, Parent) = Worklist.pop_back_val();
8450 
8451     // We should only be looking at scalar instructions here. If the current
8452     // instruction has a vector type, skip.
8453     auto *Ty = I->getType();
8454     if (isa<VectorType>(Ty))
8455       continue;
8456 
8457     // If the current instruction is a load, update MaxWidth to reflect the
8458     // width of the loaded value.
8459     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8460         isa<ExtractValueInst>(I))
8461       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8462 
8463     // Otherwise, we need to visit the operands of the instruction. We only
8464     // handle the interesting cases from buildTree here. If an operand is an
8465     // instruction we haven't yet visited and from the same basic block as the
8466     // user or the use is a PHI node, we add it to the worklist.
8467     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8468              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8469              isa<UnaryOperator>(I)) {
8470       for (Use &U : I->operands())
8471         if (auto *J = dyn_cast<Instruction>(U.get()))
8472           if (Visited.insert(J).second &&
8473               (isa<PHINode>(I) || J->getParent() == Parent))
8474             Worklist.emplace_back(J, J->getParent());
8475     } else {
8476       break;
8477     }
8478   }
8479 
8480   // If we didn't encounter a memory access in the expression tree, or if we
8481   // gave up for some reason, just return the width of V. Otherwise, return the
8482   // maximum width we found.
8483   if (!Width) {
8484     if (auto *CI = dyn_cast<CmpInst>(V))
8485       V = CI->getOperand(0);
8486     Width = DL->getTypeSizeInBits(V->getType());
8487   }
8488 
8489   for (Instruction *I : Visited)
8490     InstrElementSize[I] = Width;
8491 
8492   return Width;
8493 }
8494 
8495 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8496 // smaller type with a truncation. We collect the values that will be demoted
8497 // in ToDemote and additional roots that require investigating in Roots.
8498 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8499                                   SmallVectorImpl<Value *> &ToDemote,
8500                                   SmallVectorImpl<Value *> &Roots) {
8501   // We can always demote constants.
8502   if (isa<Constant>(V)) {
8503     ToDemote.push_back(V);
8504     return true;
8505   }
8506 
8507   // If the value is not an instruction in the expression with only one use, it
8508   // cannot be demoted.
8509   auto *I = dyn_cast<Instruction>(V);
8510   if (!I || !I->hasOneUse() || !Expr.count(I))
8511     return false;
8512 
8513   switch (I->getOpcode()) {
8514 
8515   // We can always demote truncations and extensions. Since truncations can
8516   // seed additional demotion, we save the truncated value.
8517   case Instruction::Trunc:
8518     Roots.push_back(I->getOperand(0));
8519     break;
8520   case Instruction::ZExt:
8521   case Instruction::SExt:
8522     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8523         isa<InsertElementInst>(I->getOperand(0)))
8524       return false;
8525     break;
8526 
8527   // We can demote certain binary operations if we can demote both of their
8528   // operands.
8529   case Instruction::Add:
8530   case Instruction::Sub:
8531   case Instruction::Mul:
8532   case Instruction::And:
8533   case Instruction::Or:
8534   case Instruction::Xor:
8535     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8536         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8537       return false;
8538     break;
8539 
8540   // We can demote selects if we can demote their true and false values.
8541   case Instruction::Select: {
8542     SelectInst *SI = cast<SelectInst>(I);
8543     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8544         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8545       return false;
8546     break;
8547   }
8548 
8549   // We can demote phis if we can demote all their incoming operands. Note that
8550   // we don't need to worry about cycles since we ensure single use above.
8551   case Instruction::PHI: {
8552     PHINode *PN = cast<PHINode>(I);
8553     for (Value *IncValue : PN->incoming_values())
8554       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8555         return false;
8556     break;
8557   }
8558 
8559   // Otherwise, conservatively give up.
8560   default:
8561     return false;
8562   }
8563 
8564   // Record the value that we can demote.
8565   ToDemote.push_back(V);
8566   return true;
8567 }
8568 
8569 void BoUpSLP::computeMinimumValueSizes() {
8570   // If there are no external uses, the expression tree must be rooted by a
8571   // store. We can't demote in-memory values, so there is nothing to do here.
8572   if (ExternalUses.empty())
8573     return;
8574 
8575   // We only attempt to truncate integer expressions.
8576   auto &TreeRoot = VectorizableTree[0]->Scalars;
8577   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8578   if (!TreeRootIT)
8579     return;
8580 
8581   // If the expression is not rooted by a store, these roots should have
8582   // external uses. We will rely on InstCombine to rewrite the expression in
8583   // the narrower type. However, InstCombine only rewrites single-use values.
8584   // This means that if a tree entry other than a root is used externally, it
8585   // must have multiple uses and InstCombine will not rewrite it. The code
8586   // below ensures that only the roots are used externally.
8587   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8588   for (auto &EU : ExternalUses)
8589     if (!Expr.erase(EU.Scalar))
8590       return;
8591   if (!Expr.empty())
8592     return;
8593 
8594   // Collect the scalar values of the vectorizable expression. We will use this
8595   // context to determine which values can be demoted. If we see a truncation,
8596   // we mark it as seeding another demotion.
8597   for (auto &EntryPtr : VectorizableTree)
8598     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8599 
8600   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8601   // have a single external user that is not in the vectorizable tree.
8602   for (auto *Root : TreeRoot)
8603     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8604       return;
8605 
8606   // Conservatively determine if we can actually truncate the roots of the
8607   // expression. Collect the values that can be demoted in ToDemote and
8608   // additional roots that require investigating in Roots.
8609   SmallVector<Value *, 32> ToDemote;
8610   SmallVector<Value *, 4> Roots;
8611   for (auto *Root : TreeRoot)
8612     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8613       return;
8614 
8615   // The maximum bit width required to represent all the values that can be
8616   // demoted without loss of precision. It would be safe to truncate the roots
8617   // of the expression to this width.
8618   auto MaxBitWidth = 8u;
8619 
8620   // We first check if all the bits of the roots are demanded. If they're not,
8621   // we can truncate the roots to this narrower type.
8622   for (auto *Root : TreeRoot) {
8623     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8624     MaxBitWidth = std::max<unsigned>(
8625         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8626   }
8627 
8628   // True if the roots can be zero-extended back to their original type, rather
8629   // than sign-extended. We know that if the leading bits are not demanded, we
8630   // can safely zero-extend. So we initialize IsKnownPositive to True.
8631   bool IsKnownPositive = true;
8632 
8633   // If all the bits of the roots are demanded, we can try a little harder to
8634   // compute a narrower type. This can happen, for example, if the roots are
8635   // getelementptr indices. InstCombine promotes these indices to the pointer
8636   // width. Thus, all their bits are technically demanded even though the
8637   // address computation might be vectorized in a smaller type.
8638   //
8639   // We start by looking at each entry that can be demoted. We compute the
8640   // maximum bit width required to store the scalar by using ValueTracking to
8641   // compute the number of high-order bits we can truncate.
8642   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8643       llvm::all_of(TreeRoot, [](Value *R) {
8644         assert(R->hasOneUse() && "Root should have only one use!");
8645         return isa<GetElementPtrInst>(R->user_back());
8646       })) {
8647     MaxBitWidth = 8u;
8648 
8649     // Determine if the sign bit of all the roots is known to be zero. If not,
8650     // IsKnownPositive is set to False.
8651     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8652       KnownBits Known = computeKnownBits(R, *DL);
8653       return Known.isNonNegative();
8654     });
8655 
8656     // Determine the maximum number of bits required to store the scalar
8657     // values.
8658     for (auto *Scalar : ToDemote) {
8659       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8660       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8661       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8662     }
8663 
8664     // If we can't prove that the sign bit is zero, we must add one to the
8665     // maximum bit width to account for the unknown sign bit. This preserves
8666     // the existing sign bit so we can safely sign-extend the root back to the
8667     // original type. Otherwise, if we know the sign bit is zero, we will
8668     // zero-extend the root instead.
8669     //
8670     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8671     //        one to the maximum bit width will yield a larger-than-necessary
8672     //        type. In general, we need to add an extra bit only if we can't
8673     //        prove that the upper bit of the original type is equal to the
8674     //        upper bit of the proposed smaller type. If these two bits are the
8675     //        same (either zero or one) we know that sign-extending from the
8676     //        smaller type will result in the same value. Here, since we can't
8677     //        yet prove this, we are just making the proposed smaller type
8678     //        larger to ensure correctness.
8679     if (!IsKnownPositive)
8680       ++MaxBitWidth;
8681   }
8682 
8683   // Round MaxBitWidth up to the next power-of-two.
8684   if (!isPowerOf2_64(MaxBitWidth))
8685     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8686 
8687   // If the maximum bit width we compute is less than the with of the roots'
8688   // type, we can proceed with the narrowing. Otherwise, do nothing.
8689   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8690     return;
8691 
8692   // If we can truncate the root, we must collect additional values that might
8693   // be demoted as a result. That is, those seeded by truncations we will
8694   // modify.
8695   while (!Roots.empty())
8696     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8697 
8698   // Finally, map the values we can demote to the maximum bit with we computed.
8699   for (auto *Scalar : ToDemote)
8700     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8701 }
8702 
8703 namespace {
8704 
8705 /// The SLPVectorizer Pass.
8706 struct SLPVectorizer : public FunctionPass {
8707   SLPVectorizerPass Impl;
8708 
8709   /// Pass identification, replacement for typeid
8710   static char ID;
8711 
8712   explicit SLPVectorizer() : FunctionPass(ID) {
8713     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8714   }
8715 
8716   bool doInitialization(Module &M) override { return false; }
8717 
8718   bool runOnFunction(Function &F) override {
8719     if (skipFunction(F))
8720       return false;
8721 
8722     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8723     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8724     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8725     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8726     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8727     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8728     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8729     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8730     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8731     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8732 
8733     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8734   }
8735 
8736   void getAnalysisUsage(AnalysisUsage &AU) const override {
8737     FunctionPass::getAnalysisUsage(AU);
8738     AU.addRequired<AssumptionCacheTracker>();
8739     AU.addRequired<ScalarEvolutionWrapperPass>();
8740     AU.addRequired<AAResultsWrapperPass>();
8741     AU.addRequired<TargetTransformInfoWrapperPass>();
8742     AU.addRequired<LoopInfoWrapperPass>();
8743     AU.addRequired<DominatorTreeWrapperPass>();
8744     AU.addRequired<DemandedBitsWrapperPass>();
8745     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8746     AU.addRequired<InjectTLIMappingsLegacy>();
8747     AU.addPreserved<LoopInfoWrapperPass>();
8748     AU.addPreserved<DominatorTreeWrapperPass>();
8749     AU.addPreserved<AAResultsWrapperPass>();
8750     AU.addPreserved<GlobalsAAWrapperPass>();
8751     AU.setPreservesCFG();
8752   }
8753 };
8754 
8755 } // end anonymous namespace
8756 
8757 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8758   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8759   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8760   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8761   auto *AA = &AM.getResult<AAManager>(F);
8762   auto *LI = &AM.getResult<LoopAnalysis>(F);
8763   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8764   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8765   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8766   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8767 
8768   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8769   if (!Changed)
8770     return PreservedAnalyses::all();
8771 
8772   PreservedAnalyses PA;
8773   PA.preserveSet<CFGAnalyses>();
8774   return PA;
8775 }
8776 
8777 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8778                                 TargetTransformInfo *TTI_,
8779                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8780                                 LoopInfo *LI_, DominatorTree *DT_,
8781                                 AssumptionCache *AC_, DemandedBits *DB_,
8782                                 OptimizationRemarkEmitter *ORE_) {
8783   if (!RunSLPVectorization)
8784     return false;
8785   SE = SE_;
8786   TTI = TTI_;
8787   TLI = TLI_;
8788   AA = AA_;
8789   LI = LI_;
8790   DT = DT_;
8791   AC = AC_;
8792   DB = DB_;
8793   DL = &F.getParent()->getDataLayout();
8794 
8795   Stores.clear();
8796   GEPs.clear();
8797   bool Changed = false;
8798 
8799   // If the target claims to have no vector registers don't attempt
8800   // vectorization.
8801   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8802     LLVM_DEBUG(
8803         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8804     return false;
8805   }
8806 
8807   // Don't vectorize when the attribute NoImplicitFloat is used.
8808   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8809     return false;
8810 
8811   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8812 
8813   // Use the bottom up slp vectorizer to construct chains that start with
8814   // store instructions.
8815   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8816 
8817   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8818   // delete instructions.
8819 
8820   // Update DFS numbers now so that we can use them for ordering.
8821   DT->updateDFSNumbers();
8822 
8823   // Scan the blocks in the function in post order.
8824   for (auto BB : post_order(&F.getEntryBlock())) {
8825     collectSeedInstructions(BB);
8826 
8827     // Vectorize trees that end at stores.
8828     if (!Stores.empty()) {
8829       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8830                         << " underlying objects.\n");
8831       Changed |= vectorizeStoreChains(R);
8832     }
8833 
8834     // Vectorize trees that end at reductions.
8835     Changed |= vectorizeChainsInBlock(BB, R);
8836 
8837     // Vectorize the index computations of getelementptr instructions. This
8838     // is primarily intended to catch gather-like idioms ending at
8839     // non-consecutive loads.
8840     if (!GEPs.empty()) {
8841       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8842                         << " underlying objects.\n");
8843       Changed |= vectorizeGEPIndices(BB, R);
8844     }
8845   }
8846 
8847   if (Changed) {
8848     R.optimizeGatherSequence();
8849     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8850   }
8851   return Changed;
8852 }
8853 
8854 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8855                                             unsigned Idx) {
8856   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8857                     << "\n");
8858   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8859   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8860   unsigned VF = Chain.size();
8861 
8862   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8863     return false;
8864 
8865   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8866                     << "\n");
8867 
8868   R.buildTree(Chain);
8869   if (R.isTreeTinyAndNotFullyVectorizable())
8870     return false;
8871   if (R.isLoadCombineCandidate())
8872     return false;
8873   R.reorderTopToBottom();
8874   R.reorderBottomToTop();
8875   R.buildExternalUses();
8876 
8877   R.computeMinimumValueSizes();
8878 
8879   InstructionCost Cost = R.getTreeCost();
8880 
8881   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8882   if (Cost < -SLPCostThreshold) {
8883     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8884 
8885     using namespace ore;
8886 
8887     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8888                                         cast<StoreInst>(Chain[0]))
8889                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8890                      << " and with tree size "
8891                      << NV("TreeSize", R.getTreeSize()));
8892 
8893     R.vectorizeTree();
8894     return true;
8895   }
8896 
8897   return false;
8898 }
8899 
8900 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8901                                         BoUpSLP &R) {
8902   // We may run into multiple chains that merge into a single chain. We mark the
8903   // stores that we vectorized so that we don't visit the same store twice.
8904   BoUpSLP::ValueSet VectorizedStores;
8905   bool Changed = false;
8906 
8907   int E = Stores.size();
8908   SmallBitVector Tails(E, false);
8909   int MaxIter = MaxStoreLookup.getValue();
8910   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8911       E, std::make_pair(E, INT_MAX));
8912   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8913   int IterCnt;
8914   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8915                                   &CheckedPairs,
8916                                   &ConsecutiveChain](int K, int Idx) {
8917     if (IterCnt >= MaxIter)
8918       return true;
8919     if (CheckedPairs[Idx].test(K))
8920       return ConsecutiveChain[K].second == 1 &&
8921              ConsecutiveChain[K].first == Idx;
8922     ++IterCnt;
8923     CheckedPairs[Idx].set(K);
8924     CheckedPairs[K].set(Idx);
8925     Optional<int> Diff = getPointersDiff(
8926         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8927         Stores[Idx]->getValueOperand()->getType(),
8928         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8929     if (!Diff || *Diff == 0)
8930       return false;
8931     int Val = *Diff;
8932     if (Val < 0) {
8933       if (ConsecutiveChain[Idx].second > -Val) {
8934         Tails.set(K);
8935         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8936       }
8937       return false;
8938     }
8939     if (ConsecutiveChain[K].second <= Val)
8940       return false;
8941 
8942     Tails.set(Idx);
8943     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8944     return Val == 1;
8945   };
8946   // Do a quadratic search on all of the given stores in reverse order and find
8947   // all of the pairs of stores that follow each other.
8948   for (int Idx = E - 1; Idx >= 0; --Idx) {
8949     // If a store has multiple consecutive store candidates, search according
8950     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8951     // This is because usually pairing with immediate succeeding or preceding
8952     // candidate create the best chance to find slp vectorization opportunity.
8953     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8954     IterCnt = 0;
8955     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8956       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8957           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8958         break;
8959   }
8960 
8961   // Tracks if we tried to vectorize stores starting from the given tail
8962   // already.
8963   SmallBitVector TriedTails(E, false);
8964   // For stores that start but don't end a link in the chain:
8965   for (int Cnt = E; Cnt > 0; --Cnt) {
8966     int I = Cnt - 1;
8967     if (ConsecutiveChain[I].first == E || Tails.test(I))
8968       continue;
8969     // We found a store instr that starts a chain. Now follow the chain and try
8970     // to vectorize it.
8971     BoUpSLP::ValueList Operands;
8972     // Collect the chain into a list.
8973     while (I != E && !VectorizedStores.count(Stores[I])) {
8974       Operands.push_back(Stores[I]);
8975       Tails.set(I);
8976       if (ConsecutiveChain[I].second != 1) {
8977         // Mark the new end in the chain and go back, if required. It might be
8978         // required if the original stores come in reversed order, for example.
8979         if (ConsecutiveChain[I].first != E &&
8980             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8981             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8982           TriedTails.set(I);
8983           Tails.reset(ConsecutiveChain[I].first);
8984           if (Cnt < ConsecutiveChain[I].first + 2)
8985             Cnt = ConsecutiveChain[I].first + 2;
8986         }
8987         break;
8988       }
8989       // Move to the next value in the chain.
8990       I = ConsecutiveChain[I].first;
8991     }
8992     assert(!Operands.empty() && "Expected non-empty list of stores.");
8993 
8994     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8995     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8996     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8997 
8998     unsigned MinVF = R.getMinVF(EltSize);
8999     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
9000                               MaxElts);
9001 
9002     // FIXME: Is division-by-2 the correct step? Should we assert that the
9003     // register size is a power-of-2?
9004     unsigned StartIdx = 0;
9005     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9006       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9007         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9008         if (!VectorizedStores.count(Slice.front()) &&
9009             !VectorizedStores.count(Slice.back()) &&
9010             vectorizeStoreChain(Slice, R, Cnt)) {
9011           // Mark the vectorized stores so that we don't vectorize them again.
9012           VectorizedStores.insert(Slice.begin(), Slice.end());
9013           Changed = true;
9014           // If we vectorized initial block, no need to try to vectorize it
9015           // again.
9016           if (Cnt == StartIdx)
9017             StartIdx += Size;
9018           Cnt += Size;
9019           continue;
9020         }
9021         ++Cnt;
9022       }
9023       // Check if the whole array was vectorized already - exit.
9024       if (StartIdx >= Operands.size())
9025         break;
9026     }
9027   }
9028 
9029   return Changed;
9030 }
9031 
9032 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9033   // Initialize the collections. We will make a single pass over the block.
9034   Stores.clear();
9035   GEPs.clear();
9036 
9037   // Visit the store and getelementptr instructions in BB and organize them in
9038   // Stores and GEPs according to the underlying objects of their pointer
9039   // operands.
9040   for (Instruction &I : *BB) {
9041     // Ignore store instructions that are volatile or have a pointer operand
9042     // that doesn't point to a scalar type.
9043     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9044       if (!SI->isSimple())
9045         continue;
9046       if (!isValidElementType(SI->getValueOperand()->getType()))
9047         continue;
9048       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9049     }
9050 
9051     // Ignore getelementptr instructions that have more than one index, a
9052     // constant index, or a pointer operand that doesn't point to a scalar
9053     // type.
9054     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9055       auto Idx = GEP->idx_begin()->get();
9056       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9057         continue;
9058       if (!isValidElementType(Idx->getType()))
9059         continue;
9060       if (GEP->getType()->isVectorTy())
9061         continue;
9062       GEPs[GEP->getPointerOperand()].push_back(GEP);
9063     }
9064   }
9065 }
9066 
9067 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9068   if (!A || !B)
9069     return false;
9070   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9071     return false;
9072   Value *VL[] = {A, B};
9073   return tryToVectorizeList(VL, R);
9074 }
9075 
9076 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9077                                            bool LimitForRegisterSize) {
9078   if (VL.size() < 2)
9079     return false;
9080 
9081   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9082                     << VL.size() << ".\n");
9083 
9084   // Check that all of the parts are instructions of the same type,
9085   // we permit an alternate opcode via InstructionsState.
9086   InstructionsState S = getSameOpcode(VL);
9087   if (!S.getOpcode())
9088     return false;
9089 
9090   Instruction *I0 = cast<Instruction>(S.OpValue);
9091   // Make sure invalid types (including vector type) are rejected before
9092   // determining vectorization factor for scalar instructions.
9093   for (Value *V : VL) {
9094     Type *Ty = V->getType();
9095     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9096       // NOTE: the following will give user internal llvm type name, which may
9097       // not be useful.
9098       R.getORE()->emit([&]() {
9099         std::string type_str;
9100         llvm::raw_string_ostream rso(type_str);
9101         Ty->print(rso);
9102         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9103                << "Cannot SLP vectorize list: type "
9104                << rso.str() + " is unsupported by vectorizer";
9105       });
9106       return false;
9107     }
9108   }
9109 
9110   unsigned Sz = R.getVectorElementSize(I0);
9111   unsigned MinVF = R.getMinVF(Sz);
9112   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9113   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9114   if (MaxVF < 2) {
9115     R.getORE()->emit([&]() {
9116       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9117              << "Cannot SLP vectorize list: vectorization factor "
9118              << "less than 2 is not supported";
9119     });
9120     return false;
9121   }
9122 
9123   bool Changed = false;
9124   bool CandidateFound = false;
9125   InstructionCost MinCost = SLPCostThreshold.getValue();
9126   Type *ScalarTy = VL[0]->getType();
9127   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9128     ScalarTy = IE->getOperand(1)->getType();
9129 
9130   unsigned NextInst = 0, MaxInst = VL.size();
9131   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9132     // No actual vectorization should happen, if number of parts is the same as
9133     // provided vectorization factor (i.e. the scalar type is used for vector
9134     // code during codegen).
9135     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9136     if (TTI->getNumberOfParts(VecTy) == VF)
9137       continue;
9138     for (unsigned I = NextInst; I < MaxInst; ++I) {
9139       unsigned OpsWidth = 0;
9140 
9141       if (I + VF > MaxInst)
9142         OpsWidth = MaxInst - I;
9143       else
9144         OpsWidth = VF;
9145 
9146       if (!isPowerOf2_32(OpsWidth))
9147         continue;
9148 
9149       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9150           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9151         break;
9152 
9153       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9154       // Check that a previous iteration of this loop did not delete the Value.
9155       if (llvm::any_of(Ops, [&R](Value *V) {
9156             auto *I = dyn_cast<Instruction>(V);
9157             return I && R.isDeleted(I);
9158           }))
9159         continue;
9160 
9161       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9162                         << "\n");
9163 
9164       R.buildTree(Ops);
9165       if (R.isTreeTinyAndNotFullyVectorizable())
9166         continue;
9167       R.reorderTopToBottom();
9168       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9169       R.buildExternalUses();
9170 
9171       R.computeMinimumValueSizes();
9172       InstructionCost Cost = R.getTreeCost();
9173       CandidateFound = true;
9174       MinCost = std::min(MinCost, Cost);
9175 
9176       if (Cost < -SLPCostThreshold) {
9177         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9178         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9179                                                     cast<Instruction>(Ops[0]))
9180                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9181                                  << " and with tree size "
9182                                  << ore::NV("TreeSize", R.getTreeSize()));
9183 
9184         R.vectorizeTree();
9185         // Move to the next bundle.
9186         I += VF - 1;
9187         NextInst = I + 1;
9188         Changed = true;
9189       }
9190     }
9191   }
9192 
9193   if (!Changed && CandidateFound) {
9194     R.getORE()->emit([&]() {
9195       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9196              << "List vectorization was possible but not beneficial with cost "
9197              << ore::NV("Cost", MinCost) << " >= "
9198              << ore::NV("Treshold", -SLPCostThreshold);
9199     });
9200   } else if (!Changed) {
9201     R.getORE()->emit([&]() {
9202       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9203              << "Cannot SLP vectorize list: vectorization was impossible"
9204              << " with available vectorization factors";
9205     });
9206   }
9207   return Changed;
9208 }
9209 
9210 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9211   if (!I)
9212     return false;
9213 
9214   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9215     return false;
9216 
9217   Value *P = I->getParent();
9218 
9219   // Vectorize in current basic block only.
9220   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9221   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9222   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9223     return false;
9224 
9225   // Try to vectorize V.
9226   if (tryToVectorizePair(Op0, Op1, R))
9227     return true;
9228 
9229   auto *A = dyn_cast<BinaryOperator>(Op0);
9230   auto *B = dyn_cast<BinaryOperator>(Op1);
9231   // Try to skip B.
9232   if (B && B->hasOneUse()) {
9233     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9234     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9235     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9236       return true;
9237     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9238       return true;
9239   }
9240 
9241   // Try to skip A.
9242   if (A && A->hasOneUse()) {
9243     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9244     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9245     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9246       return true;
9247     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9248       return true;
9249   }
9250   return false;
9251 }
9252 
9253 namespace {
9254 
9255 /// Model horizontal reductions.
9256 ///
9257 /// A horizontal reduction is a tree of reduction instructions that has values
9258 /// that can be put into a vector as its leaves. For example:
9259 ///
9260 /// mul mul mul mul
9261 ///  \  /    \  /
9262 ///   +       +
9263 ///    \     /
9264 ///       +
9265 /// This tree has "mul" as its leaf values and "+" as its reduction
9266 /// instructions. A reduction can feed into a store or a binary operation
9267 /// feeding a phi.
9268 ///    ...
9269 ///    \  /
9270 ///     +
9271 ///     |
9272 ///  phi +=
9273 ///
9274 ///  Or:
9275 ///    ...
9276 ///    \  /
9277 ///     +
9278 ///     |
9279 ///   *p =
9280 ///
9281 class HorizontalReduction {
9282   using ReductionOpsType = SmallVector<Value *, 16>;
9283   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9284   ReductionOpsListType ReductionOps;
9285   /// List of possibly reduced values.
9286   SmallVector<SmallVector<Value *>> ReducedVals;
9287   /// Maps reduced value to the corresponding reduction operation.
9288   DenseMap<Value *, Instruction *> ReducedValsToOps;
9289   // Use map vector to make stable output.
9290   MapVector<Instruction *, Value *> ExtraArgs;
9291   WeakTrackingVH ReductionRoot;
9292   /// The type of reduction operation.
9293   RecurKind RdxKind;
9294 
9295   static bool isCmpSelMinMax(Instruction *I) {
9296     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9297            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9298   }
9299 
9300   // And/or are potentially poison-safe logical patterns like:
9301   // select x, y, false
9302   // select x, true, y
9303   static bool isBoolLogicOp(Instruction *I) {
9304     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9305            match(I, m_LogicalOr(m_Value(), m_Value()));
9306   }
9307 
9308   /// Checks if instruction is associative and can be vectorized.
9309   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9310     if (Kind == RecurKind::None)
9311       return false;
9312 
9313     // Integer ops that map to select instructions or intrinsics are fine.
9314     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9315         isBoolLogicOp(I))
9316       return true;
9317 
9318     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9319       // FP min/max are associative except for NaN and -0.0. We do not
9320       // have to rule out -0.0 here because the intrinsic semantics do not
9321       // specify a fixed result for it.
9322       return I->getFastMathFlags().noNaNs();
9323     }
9324 
9325     return I->isAssociative();
9326   }
9327 
9328   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9329     // Poison-safe 'or' takes the form: select X, true, Y
9330     // To make that work with the normal operand processing, we skip the
9331     // true value operand.
9332     // TODO: Change the code and data structures to handle this without a hack.
9333     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9334       return I->getOperand(2);
9335     return I->getOperand(Index);
9336   }
9337 
9338   /// Creates reduction operation with the current opcode.
9339   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9340                          Value *RHS, const Twine &Name, bool UseSelect) {
9341     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9342     switch (Kind) {
9343     case RecurKind::Or:
9344       if (UseSelect &&
9345           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9346         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9347       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9348                                  Name);
9349     case RecurKind::And:
9350       if (UseSelect &&
9351           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9352         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9353       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9354                                  Name);
9355     case RecurKind::Add:
9356     case RecurKind::Mul:
9357     case RecurKind::Xor:
9358     case RecurKind::FAdd:
9359     case RecurKind::FMul:
9360       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9361                                  Name);
9362     case RecurKind::FMax:
9363       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9364     case RecurKind::FMin:
9365       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9366     case RecurKind::SMax:
9367       if (UseSelect) {
9368         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9369         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9370       }
9371       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9372     case RecurKind::SMin:
9373       if (UseSelect) {
9374         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9375         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9376       }
9377       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9378     case RecurKind::UMax:
9379       if (UseSelect) {
9380         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9381         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9382       }
9383       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9384     case RecurKind::UMin:
9385       if (UseSelect) {
9386         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9387         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9388       }
9389       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9390     default:
9391       llvm_unreachable("Unknown reduction operation.");
9392     }
9393   }
9394 
9395   /// Creates reduction operation with the current opcode with the IR flags
9396   /// from \p ReductionOps.
9397   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9398                          Value *RHS, const Twine &Name,
9399                          const ReductionOpsListType &ReductionOps) {
9400     bool UseSelect = ReductionOps.size() == 2 ||
9401                      // Logical or/and.
9402                      (ReductionOps.size() == 1 &&
9403                       isa<SelectInst>(ReductionOps.front().front()));
9404     assert((!UseSelect || ReductionOps.size() != 2 ||
9405             isa<SelectInst>(ReductionOps[1][0])) &&
9406            "Expected cmp + select pairs for reduction");
9407     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9408     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9409       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9410         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9411         propagateIRFlags(Op, ReductionOps[1]);
9412         return Op;
9413       }
9414     }
9415     propagateIRFlags(Op, ReductionOps[0]);
9416     return Op;
9417   }
9418 
9419   /// Creates reduction operation with the current opcode with the IR flags
9420   /// from \p I.
9421   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9422                          Value *RHS, const Twine &Name, Value *I) {
9423     auto *SelI = dyn_cast<SelectInst>(I);
9424     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9425     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9426       if (auto *Sel = dyn_cast<SelectInst>(Op))
9427         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9428     }
9429     propagateIRFlags(Op, I);
9430     return Op;
9431   }
9432 
9433   static RecurKind getRdxKind(Value *V) {
9434     auto *I = dyn_cast<Instruction>(V);
9435     if (!I)
9436       return RecurKind::None;
9437     if (match(I, m_Add(m_Value(), m_Value())))
9438       return RecurKind::Add;
9439     if (match(I, m_Mul(m_Value(), m_Value())))
9440       return RecurKind::Mul;
9441     if (match(I, m_And(m_Value(), m_Value())) ||
9442         match(I, m_LogicalAnd(m_Value(), m_Value())))
9443       return RecurKind::And;
9444     if (match(I, m_Or(m_Value(), m_Value())) ||
9445         match(I, m_LogicalOr(m_Value(), m_Value())))
9446       return RecurKind::Or;
9447     if (match(I, m_Xor(m_Value(), m_Value())))
9448       return RecurKind::Xor;
9449     if (match(I, m_FAdd(m_Value(), m_Value())))
9450       return RecurKind::FAdd;
9451     if (match(I, m_FMul(m_Value(), m_Value())))
9452       return RecurKind::FMul;
9453 
9454     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9455       return RecurKind::FMax;
9456     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9457       return RecurKind::FMin;
9458 
9459     // This matches either cmp+select or intrinsics. SLP is expected to handle
9460     // either form.
9461     // TODO: If we are canonicalizing to intrinsics, we can remove several
9462     //       special-case paths that deal with selects.
9463     if (match(I, m_SMax(m_Value(), m_Value())))
9464       return RecurKind::SMax;
9465     if (match(I, m_SMin(m_Value(), m_Value())))
9466       return RecurKind::SMin;
9467     if (match(I, m_UMax(m_Value(), m_Value())))
9468       return RecurKind::UMax;
9469     if (match(I, m_UMin(m_Value(), m_Value())))
9470       return RecurKind::UMin;
9471 
9472     if (auto *Select = dyn_cast<SelectInst>(I)) {
9473       // Try harder: look for min/max pattern based on instructions producing
9474       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9475       // During the intermediate stages of SLP, it's very common to have
9476       // pattern like this (since optimizeGatherSequence is run only once
9477       // at the end):
9478       // %1 = extractelement <2 x i32> %a, i32 0
9479       // %2 = extractelement <2 x i32> %a, i32 1
9480       // %cond = icmp sgt i32 %1, %2
9481       // %3 = extractelement <2 x i32> %a, i32 0
9482       // %4 = extractelement <2 x i32> %a, i32 1
9483       // %select = select i1 %cond, i32 %3, i32 %4
9484       CmpInst::Predicate Pred;
9485       Instruction *L1;
9486       Instruction *L2;
9487 
9488       Value *LHS = Select->getTrueValue();
9489       Value *RHS = Select->getFalseValue();
9490       Value *Cond = Select->getCondition();
9491 
9492       // TODO: Support inverse predicates.
9493       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9494         if (!isa<ExtractElementInst>(RHS) ||
9495             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9496           return RecurKind::None;
9497       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9498         if (!isa<ExtractElementInst>(LHS) ||
9499             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9500           return RecurKind::None;
9501       } else {
9502         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9503           return RecurKind::None;
9504         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9505             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9506             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9507           return RecurKind::None;
9508       }
9509 
9510       switch (Pred) {
9511       default:
9512         return RecurKind::None;
9513       case CmpInst::ICMP_SGT:
9514       case CmpInst::ICMP_SGE:
9515         return RecurKind::SMax;
9516       case CmpInst::ICMP_SLT:
9517       case CmpInst::ICMP_SLE:
9518         return RecurKind::SMin;
9519       case CmpInst::ICMP_UGT:
9520       case CmpInst::ICMP_UGE:
9521         return RecurKind::UMax;
9522       case CmpInst::ICMP_ULT:
9523       case CmpInst::ICMP_ULE:
9524         return RecurKind::UMin;
9525       }
9526     }
9527     return RecurKind::None;
9528   }
9529 
9530   /// Get the index of the first operand.
9531   static unsigned getFirstOperandIndex(Instruction *I) {
9532     return isCmpSelMinMax(I) ? 1 : 0;
9533   }
9534 
9535   /// Total number of operands in the reduction operation.
9536   static unsigned getNumberOfOperands(Instruction *I) {
9537     return isCmpSelMinMax(I) ? 3 : 2;
9538   }
9539 
9540   /// Checks if the instruction is in basic block \p BB.
9541   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9542   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9543     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9544       auto *Sel = cast<SelectInst>(I);
9545       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9546       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9547     }
9548     return I->getParent() == BB;
9549   }
9550 
9551   /// Expected number of uses for reduction operations/reduced values.
9552   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9553     if (IsCmpSelMinMax) {
9554       // SelectInst must be used twice while the condition op must have single
9555       // use only.
9556       if (auto *Sel = dyn_cast<SelectInst>(I))
9557         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9558       return I->hasNUses(2);
9559     }
9560 
9561     // Arithmetic reduction operation must be used once only.
9562     return I->hasOneUse();
9563   }
9564 
9565   /// Initializes the list of reduction operations.
9566   void initReductionOps(Instruction *I) {
9567     if (isCmpSelMinMax(I))
9568       ReductionOps.assign(2, ReductionOpsType());
9569     else
9570       ReductionOps.assign(1, ReductionOpsType());
9571   }
9572 
9573   /// Add all reduction operations for the reduction instruction \p I.
9574   void addReductionOps(Instruction *I) {
9575     if (isCmpSelMinMax(I)) {
9576       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9577       ReductionOps[1].emplace_back(I);
9578     } else {
9579       ReductionOps[0].emplace_back(I);
9580     }
9581   }
9582 
9583   static Value *getLHS(RecurKind Kind, Instruction *I) {
9584     if (Kind == RecurKind::None)
9585       return nullptr;
9586     return I->getOperand(getFirstOperandIndex(I));
9587   }
9588   static Value *getRHS(RecurKind Kind, Instruction *I) {
9589     if (Kind == RecurKind::None)
9590       return nullptr;
9591     return I->getOperand(getFirstOperandIndex(I) + 1);
9592   }
9593 
9594 public:
9595   HorizontalReduction() = default;
9596 
9597   /// Try to find a reduction tree.
9598   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9599                                  ScalarEvolution &SE, const DataLayout &DL,
9600                                  const TargetLibraryInfo &TLI) {
9601     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9602            "Phi needs to use the binary operator");
9603     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9604             isa<IntrinsicInst>(Inst)) &&
9605            "Expected binop, select, or intrinsic for reduction matching");
9606     RdxKind = getRdxKind(Inst);
9607 
9608     // We could have a initial reductions that is not an add.
9609     //  r *= v1 + v2 + v3 + v4
9610     // In such a case start looking for a tree rooted in the first '+'.
9611     if (Phi) {
9612       if (getLHS(RdxKind, Inst) == Phi) {
9613         Phi = nullptr;
9614         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9615         if (!Inst)
9616           return false;
9617         RdxKind = getRdxKind(Inst);
9618       } else if (getRHS(RdxKind, Inst) == Phi) {
9619         Phi = nullptr;
9620         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9621         if (!Inst)
9622           return false;
9623         RdxKind = getRdxKind(Inst);
9624       }
9625     }
9626 
9627     if (!isVectorizable(RdxKind, Inst))
9628       return false;
9629 
9630     // Analyze "regular" integer/FP types for reductions - no target-specific
9631     // types or pointers.
9632     Type *Ty = Inst->getType();
9633     if (!isValidElementType(Ty) || Ty->isPointerTy())
9634       return false;
9635 
9636     // Though the ultimate reduction may have multiple uses, its condition must
9637     // have only single use.
9638     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9639       if (!Sel->getCondition()->hasOneUse())
9640         return false;
9641 
9642     ReductionRoot = Inst;
9643 
9644     // Iterate through all the operands of the possible reduction tree and
9645     // gather all the reduced values, sorting them by their value id.
9646     BasicBlock *BB = Inst->getParent();
9647     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9648     SmallVector<Instruction *> Worklist(1, Inst);
9649     // Checks if the operands of the \p TreeN instruction are also reduction
9650     // operations or should be treated as reduced values or an extra argument,
9651     // which is not part of the reduction.
9652     auto &&CheckOperands = [this, IsCmpSelMinMax,
9653                             BB](Instruction *TreeN,
9654                                 SmallVectorImpl<Value *> &ExtraArgs,
9655                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9656                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9657       for (int I = getFirstOperandIndex(TreeN),
9658                End = getNumberOfOperands(TreeN);
9659            I < End; ++I) {
9660         Value *EdgeVal = getRdxOperand(TreeN, I);
9661         ReducedValsToOps.try_emplace(EdgeVal, TreeN);
9662         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9663         // Edge has wrong parent - mark as an extra argument.
9664         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9665             !hasSameParent(EdgeInst, BB)) {
9666           ExtraArgs.push_back(EdgeVal);
9667           continue;
9668         }
9669         // If the edge is not an instruction, or it is different from the main
9670         // reduction opcode or has too many uses - possible reduced value.
9671         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9672             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9673             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9674           PossibleReducedVals.push_back(EdgeVal);
9675           continue;
9676         }
9677         ReductionOps.push_back(EdgeInst);
9678       }
9679     };
9680     // Try to regroup reduced values so that it gets more profitable to try to
9681     // reduce them. Values are grouped by their value ids, instructions - by
9682     // instruction op id and/or alternate op id, plus do extra analysis for
9683     // loads (grouping them by the distabce between pointers) and cmp
9684     // instructions (grouping them by the predicate).
9685     MapVector<size_t, MapVector<size_t, SmallVector<Value *>>>
9686         PossibleReducedVals;
9687     initReductionOps(Inst);
9688     while (!Worklist.empty()) {
9689       Instruction *TreeN = Worklist.pop_back_val();
9690       SmallVector<Value *> Args;
9691       SmallVector<Value *> PossibleRedVals;
9692       SmallVector<Instruction *> PossibleReductionOps;
9693       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9694       // If too many extra args - mark the instruction itself as a reduction
9695       // value, not a reduction operation.
9696       if (Args.size() < 2) {
9697         addReductionOps(TreeN);
9698         // Add extra args.
9699         if (!Args.empty()) {
9700           assert(Args.size() == 1 && "Expected only single argument.");
9701           ExtraArgs[TreeN] = Args.front();
9702         }
9703         // Add reduction values. The values are sorted for better vectorization
9704         // results.
9705         for (Value *V : PossibleRedVals) {
9706           size_t Key, Idx;
9707           std::tie(Key, Idx) = generateKeySubkey(
9708               V, &TLI,
9709               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9710                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9711                   auto *RLI = cast<LoadInst>(LoadData.second.front());
9712                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9713                                       LI->getType(), LI->getPointerOperand(),
9714                                       DL, SE, /*StrictCheck=*/true))
9715                     return hash_value(RLI->getPointerOperand());
9716                 }
9717                 return hash_value(LI->getPointerOperand());
9718               },
9719               /*AllowAlternate=*/false);
9720           PossibleReducedVals[Key][Idx].push_back(V);
9721         }
9722         Worklist.append(PossibleReductionOps.begin(),
9723                         PossibleReductionOps.end());
9724       } else {
9725         size_t Key, Idx;
9726         std::tie(Key, Idx) = generateKeySubkey(
9727             TreeN, &TLI,
9728             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9729               for (const auto &LoadData : PossibleReducedVals[Key]) {
9730                 auto *RLI = cast<LoadInst>(LoadData.second.front());
9731                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9732                                     LI->getType(), LI->getPointerOperand(), DL,
9733                                     SE, /*StrictCheck=*/true))
9734                   return hash_value(RLI->getPointerOperand());
9735               }
9736               return hash_value(LI->getPointerOperand());
9737             },
9738             /*AllowAlternate=*/false);
9739         PossibleReducedVals[Key][Idx].push_back(TreeN);
9740       }
9741     }
9742     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9743     // Sort values by the total number of values kinds to start the reduction
9744     // from the longest possible reduced values sequences.
9745     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9746       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9747       stable_sort(PossibleRedVals, [](const auto &P1, const auto &P2) {
9748         return P1.second.size() > P2.second.size();
9749       });
9750       ReducedVals.emplace_back();
9751       for (auto &Data : PossibleRedVals)
9752         ReducedVals.back().append(Data.second.rbegin(), Data.second.rend());
9753     }
9754     // Sort the reduced values by number of same/alternate opcode and/or pointer
9755     // operand.
9756     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
9757       return P1.size() > P2.size();
9758     });
9759     return true;
9760   }
9761 
9762   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9763   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9764     // If there are a sufficient number of reduction values, reduce
9765     // to a nearby power-of-2. We can safely generate oversized
9766     // vectors and rely on the backend to split them to legal sizes.
9767     unsigned NumReducedVals = std::accumulate(
9768         ReducedVals.begin(), ReducedVals.end(), 0,
9769         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
9770     if (NumReducedVals < 4)
9771       return nullptr;
9772 
9773     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9774 
9775     // Track the reduced values in case if they are replaced by extractelement
9776     // because of the vectorization.
9777     DenseMap<Value *, WeakTrackingVH> TrackedVals;
9778     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9779     // The same extra argument may be used several times, so log each attempt
9780     // to use it.
9781     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9782       assert(Pair.first && "DebugLoc must be set.");
9783       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9784       TrackedVals.try_emplace(Pair.second, Pair.second);
9785     }
9786 
9787     // The compare instruction of a min/max is the insertion point for new
9788     // instructions and may be replaced with a new compare instruction.
9789     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9790       assert(isa<SelectInst>(RdxRootInst) &&
9791              "Expected min/max reduction to have select root instruction");
9792       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9793       assert(isa<Instruction>(ScalarCond) &&
9794              "Expected min/max reduction to have compare condition");
9795       return cast<Instruction>(ScalarCond);
9796     };
9797 
9798     // The reduction root is used as the insertion point for new instructions,
9799     // so set it as externally used to prevent it from being deleted.
9800     ExternallyUsedValues[ReductionRoot];
9801     SmallVector<Value *> IgnoreList;
9802     for (ReductionOpsType &RdxOps : ReductionOps)
9803       for (Value *RdxOp : RdxOps) {
9804         if (!RdxOp)
9805           continue;
9806         IgnoreList.push_back(RdxOp);
9807       }
9808 
9809     // Need to track reduced vals, they may be changed during vectorization of
9810     // subvectors.
9811     for (ArrayRef<Value *> Candidates : ReducedVals)
9812       for (Value *V : Candidates)
9813         TrackedVals.try_emplace(V, V);
9814 
9815     DenseMap<Value *, unsigned> VectorizedVals;
9816     Value *VectorizedTree = nullptr;
9817     // Try to vectorize elements based on their type.
9818     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9819       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
9820       InstructionsState S = getSameOpcode(OrigReducedVals);
9821       SmallVector<Value *> Candidates;
9822       DenseMap<Value *, Value *> TrackedToOrig;
9823       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
9824         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
9825         // Check if the reduction value was not overriden by the extractelement
9826         // instruction because of the vectorization and exclude it, if it is not
9827         // compatible with other values.
9828         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9829           if (isVectorLikeInstWithConstOps(Inst) &&
9830               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
9831             continue;
9832         Candidates.push_back(RdxVal);
9833         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
9834       }
9835       bool ShuffledExtracts = false;
9836       // Try to handle shuffled extractelements.
9837       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
9838           I + 1 < E) {
9839         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
9840         if (NextS.getOpcode() == Instruction::ExtractElement &&
9841             !NextS.isAltShuffle()) {
9842           SmallVector<Value *> CommonCandidates(Candidates);
9843           for (Value *RV : ReducedVals[I + 1]) {
9844             Value *RdxVal = TrackedVals.find(RV)->second;
9845             // Check if the reduction value was not overriden by the
9846             // extractelement instruction because of the vectorization and
9847             // exclude it, if it is not compatible with other values.
9848             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9849               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
9850                 continue;
9851             CommonCandidates.push_back(RdxVal);
9852             TrackedToOrig.try_emplace(RdxVal, RV);
9853           }
9854           SmallVector<int> Mask;
9855           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
9856             ++I;
9857             Candidates.swap(CommonCandidates);
9858             ShuffledExtracts = true;
9859           }
9860         }
9861       }
9862       unsigned NumReducedVals = Candidates.size();
9863       if (NumReducedVals < 4)
9864         continue;
9865 
9866       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9867       unsigned Start = 0;
9868       unsigned Pos = Start;
9869       // Restarts vectorization attempt with lower vector factor.
9870       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals]() {
9871         if (ReduxWidth == 4 || Pos >= NumReducedVals - ReduxWidth + 1) {
9872           ++Start;
9873           ReduxWidth = PowerOf2Floor(NumReducedVals - Start) * 2;
9874         }
9875         Pos = Start;
9876         ReduxWidth /= 2;
9877       };
9878       while (Pos < NumReducedVals - ReduxWidth + 1 && ReduxWidth >= 4) {
9879         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
9880         V.buildTree(VL, IgnoreList);
9881         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
9882           AdjustReducedVals();
9883           continue;
9884         }
9885         if (V.isLoadCombineReductionCandidate(RdxKind)) {
9886           AdjustReducedVals();
9887           continue;
9888         }
9889         V.reorderTopToBottom();
9890         // No need to reorder the root node at all.
9891         V.reorderBottomToTop(/*IgnoreReorder=*/true);
9892         // Keep extracted other reduction values, if they are used in the
9893         // vectorization trees.
9894         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
9895             ExternallyUsedValues);
9896         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
9897           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
9898             continue;
9899           for_each(ReducedVals[Cnt],
9900                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
9901                      if (isa<Instruction>(V))
9902                        LocalExternallyUsedValues[TrackedVals[V]];
9903                    });
9904         }
9905         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
9906           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
9907             continue;
9908           if (VectorizedVals.count(Candidates[Cnt]))
9909             continue;
9910           LocalExternallyUsedValues[Candidates[Cnt]];
9911         }
9912         V.buildExternalUses(LocalExternallyUsedValues);
9913 
9914         V.computeMinimumValueSizes();
9915 
9916         // Intersect the fast-math-flags from all reduction operations.
9917         FastMathFlags RdxFMF;
9918         RdxFMF.set();
9919         for (Value *RdxVal : VL) {
9920           if (auto *FPMO = dyn_cast<FPMathOperator>(
9921                   ReducedValsToOps.find(RdxVal)->second))
9922             RdxFMF &= FPMO->getFastMathFlags();
9923         }
9924         // Estimate cost.
9925         InstructionCost TreeCost = V.getTreeCost(VL);
9926         InstructionCost ReductionCost =
9927             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
9928         InstructionCost Cost = TreeCost + ReductionCost;
9929         if (!Cost.isValid()) {
9930           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9931           return nullptr;
9932         }
9933         if (Cost >= -SLPCostThreshold) {
9934           V.getORE()->emit([&]() {
9935             return OptimizationRemarkMissed(
9936                        SV_NAME, "HorSLPNotBeneficial",
9937                        ReducedValsToOps.find(VL[0])->second)
9938                    << "Vectorizing horizontal reduction is possible"
9939                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
9940                    << " and threshold "
9941                    << ore::NV("Threshold", -SLPCostThreshold);
9942           });
9943           AdjustReducedVals();
9944           continue;
9945         }
9946 
9947         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9948                           << Cost << ". (HorRdx)\n");
9949         V.getORE()->emit([&]() {
9950           return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9951                                     ReducedValsToOps.find(VL[0])->second)
9952                  << "Vectorized horizontal reduction with cost "
9953                  << ore::NV("Cost", Cost) << " and with tree size "
9954                  << ore::NV("TreeSize", V.getTreeSize());
9955         });
9956 
9957         Builder.setFastMathFlags(RdxFMF);
9958 
9959         // Vectorize a tree.
9960         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
9961 
9962         // Emit a reduction. If the root is a select (min/max idiom), the insert
9963         // point is the compare condition of that select.
9964         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9965         if (isCmpSelMinMax(RdxRootInst))
9966           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
9967         else
9968           Builder.SetInsertPoint(RdxRootInst);
9969 
9970         // To prevent poison from leaking across what used to be sequential,
9971         // safe, scalar boolean logic operations, the reduction operand must be
9972         // frozen.
9973         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9974           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9975 
9976         Value *ReducedSubTree =
9977             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9978 
9979         if (!VectorizedTree) {
9980           // Initialize the final value in the reduction.
9981           VectorizedTree = ReducedSubTree;
9982         } else {
9983           // Update the final value in the reduction.
9984           Builder.SetCurrentDebugLocation(
9985               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
9986           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9987                                     ReducedSubTree, "op.rdx", ReductionOps);
9988         }
9989         // Count vectorized reduced values to exclude them from final reduction.
9990         for (Value *V : VL)
9991           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
9992                 .first->getSecond();
9993         Pos += ReduxWidth;
9994         Start = Pos;
9995         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
9996       }
9997     }
9998     if (VectorizedTree) {
9999       // Finish the reduction.
10000       // Need to add extra arguments and not vectorized possible reduction
10001       // values.
10002       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10003         ArrayRef<Value *> Candidates = ReducedVals[I];
10004         for (Value *RdxVal : Candidates) {
10005           auto It = VectorizedVals.find(RdxVal);
10006           if (It != VectorizedVals.end()) {
10007             --It->getSecond();
10008             if (It->second == 0)
10009               VectorizedVals.erase(It);
10010             continue;
10011           }
10012           Instruction *RedOp = ReducedValsToOps.find(RdxVal)->second;
10013           Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10014           ReductionOpsListType Ops;
10015           if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10016             Ops.emplace_back().push_back(Sel->getCondition());
10017           Ops.emplace_back().push_back(RedOp);
10018           Value *StableRdxVal = RdxVal;
10019           auto TVIt = TrackedVals.find(RdxVal);
10020           if (TVIt != TrackedVals.end())
10021             StableRdxVal = TVIt->second;
10022 
10023           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10024                                     StableRdxVal, "op.rdx", RedOp);
10025         }
10026       }
10027       for (auto &Pair : ExternallyUsedValues) {
10028         // Add each externally used value to the final reduction.
10029         for (auto *I : Pair.second) {
10030           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10031           ReductionOpsListType Ops;
10032           if (auto *Sel = dyn_cast<SelectInst>(I))
10033             Ops.emplace_back().push_back(Sel->getCondition());
10034           Ops.emplace_back().push_back(I);
10035           Value *StableRdxVal = Pair.first;
10036           auto TVIt = TrackedVals.find(Pair.first);
10037           if (TVIt != TrackedVals.end())
10038             StableRdxVal = TVIt->second;
10039           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10040                                     StableRdxVal, "op.rdx", Ops);
10041         }
10042       }
10043 
10044       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10045 
10046       // The original scalar reduction is expected to have no remaining
10047       // uses outside the reduction tree itself.  Assert that we got this
10048       // correct, replace internal uses with undef, and mark for eventual
10049       // deletion.
10050 #ifndef NDEBUG
10051       SmallSet<Value *, 4> IgnoreSet;
10052       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
10053 #endif
10054       for (auto *Ignore : IgnoreList) {
10055 #ifndef NDEBUG
10056         for (auto *U : Ignore->users()) {
10057           assert(IgnoreSet.count(U));
10058         }
10059 #endif
10060         if (!Ignore->use_empty()) {
10061           Value *Undef = UndefValue::get(Ignore->getType());
10062           Ignore->replaceAllUsesWith(Undef);
10063         }
10064         V.eraseInstruction(cast<Instruction>(Ignore));
10065       }
10066     }
10067     return VectorizedTree;
10068   }
10069 
10070   unsigned numReductionValues() const { return ReducedVals.size(); }
10071 
10072 private:
10073   /// Calculate the cost of a reduction.
10074   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10075                                    Value *FirstReducedVal, unsigned ReduxWidth,
10076                                    FastMathFlags FMF) {
10077     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10078     Type *ScalarTy = FirstReducedVal->getType();
10079     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10080     InstructionCost VectorCost, ScalarCost;
10081     switch (RdxKind) {
10082     case RecurKind::Add:
10083     case RecurKind::Mul:
10084     case RecurKind::Or:
10085     case RecurKind::And:
10086     case RecurKind::Xor:
10087     case RecurKind::FAdd:
10088     case RecurKind::FMul: {
10089       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10090       VectorCost =
10091           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10092       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10093       break;
10094     }
10095     case RecurKind::FMax:
10096     case RecurKind::FMin: {
10097       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10098       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10099       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10100                                                /*IsUnsigned=*/false, CostKind);
10101       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10102       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10103                                            SclCondTy, RdxPred, CostKind) +
10104                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10105                                            SclCondTy, RdxPred, CostKind);
10106       break;
10107     }
10108     case RecurKind::SMax:
10109     case RecurKind::SMin:
10110     case RecurKind::UMax:
10111     case RecurKind::UMin: {
10112       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10113       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10114       bool IsUnsigned =
10115           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10116       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10117                                                CostKind);
10118       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10119       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10120                                            SclCondTy, RdxPred, CostKind) +
10121                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10122                                            SclCondTy, RdxPred, CostKind);
10123       break;
10124     }
10125     default:
10126       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10127     }
10128 
10129     // Scalar cost is repeated for N-1 elements.
10130     ScalarCost *= (ReduxWidth - 1);
10131     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10132                       << " for reduction that starts with " << *FirstReducedVal
10133                       << " (It is a splitting reduction)\n");
10134     return VectorCost - ScalarCost;
10135   }
10136 
10137   /// Emit a horizontal reduction of the vectorized value.
10138   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10139                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10140     assert(VectorizedValue && "Need to have a vectorized tree node");
10141     assert(isPowerOf2_32(ReduxWidth) &&
10142            "We only handle power-of-two reductions for now");
10143     assert(RdxKind != RecurKind::FMulAdd &&
10144            "A call to the llvm.fmuladd intrinsic is not handled yet");
10145 
10146     ++NumVectorInstructions;
10147     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10148   }
10149 };
10150 
10151 } // end anonymous namespace
10152 
10153 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10154   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10155     return cast<FixedVectorType>(IE->getType())->getNumElements();
10156 
10157   unsigned AggregateSize = 1;
10158   auto *IV = cast<InsertValueInst>(InsertInst);
10159   Type *CurrentType = IV->getType();
10160   do {
10161     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10162       for (auto *Elt : ST->elements())
10163         if (Elt != ST->getElementType(0)) // check homogeneity
10164           return None;
10165       AggregateSize *= ST->getNumElements();
10166       CurrentType = ST->getElementType(0);
10167     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10168       AggregateSize *= AT->getNumElements();
10169       CurrentType = AT->getElementType();
10170     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10171       AggregateSize *= VT->getNumElements();
10172       return AggregateSize;
10173     } else if (CurrentType->isSingleValueType()) {
10174       return AggregateSize;
10175     } else {
10176       return None;
10177     }
10178   } while (true);
10179 }
10180 
10181 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10182                                    TargetTransformInfo *TTI,
10183                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10184                                    SmallVectorImpl<Value *> &InsertElts,
10185                                    unsigned OperandOffset) {
10186   do {
10187     Value *InsertedOperand = LastInsertInst->getOperand(1);
10188     Optional<unsigned> OperandIndex =
10189         getInsertIndex(LastInsertInst, OperandOffset);
10190     if (!OperandIndex)
10191       return;
10192     if (isa<InsertElementInst>(InsertedOperand) ||
10193         isa<InsertValueInst>(InsertedOperand)) {
10194       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10195                              BuildVectorOpds, InsertElts, *OperandIndex);
10196 
10197     } else {
10198       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10199       InsertElts[*OperandIndex] = LastInsertInst;
10200     }
10201     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10202   } while (LastInsertInst != nullptr &&
10203            (isa<InsertValueInst>(LastInsertInst) ||
10204             isa<InsertElementInst>(LastInsertInst)) &&
10205            LastInsertInst->hasOneUse());
10206 }
10207 
10208 /// Recognize construction of vectors like
10209 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10210 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10211 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10212 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10213 ///  starting from the last insertelement or insertvalue instruction.
10214 ///
10215 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10216 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10217 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10218 ///
10219 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10220 ///
10221 /// \return true if it matches.
10222 static bool findBuildAggregate(Instruction *LastInsertInst,
10223                                TargetTransformInfo *TTI,
10224                                SmallVectorImpl<Value *> &BuildVectorOpds,
10225                                SmallVectorImpl<Value *> &InsertElts) {
10226 
10227   assert((isa<InsertElementInst>(LastInsertInst) ||
10228           isa<InsertValueInst>(LastInsertInst)) &&
10229          "Expected insertelement or insertvalue instruction!");
10230 
10231   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10232          "Expected empty result vectors!");
10233 
10234   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10235   if (!AggregateSize)
10236     return false;
10237   BuildVectorOpds.resize(*AggregateSize);
10238   InsertElts.resize(*AggregateSize);
10239 
10240   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10241   llvm::erase_value(BuildVectorOpds, nullptr);
10242   llvm::erase_value(InsertElts, nullptr);
10243   if (BuildVectorOpds.size() >= 2)
10244     return true;
10245 
10246   return false;
10247 }
10248 
10249 /// Try and get a reduction value from a phi node.
10250 ///
10251 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10252 /// if they come from either \p ParentBB or a containing loop latch.
10253 ///
10254 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10255 /// if not possible.
10256 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10257                                 BasicBlock *ParentBB, LoopInfo *LI) {
10258   // There are situations where the reduction value is not dominated by the
10259   // reduction phi. Vectorizing such cases has been reported to cause
10260   // miscompiles. See PR25787.
10261   auto DominatedReduxValue = [&](Value *R) {
10262     return isa<Instruction>(R) &&
10263            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10264   };
10265 
10266   Value *Rdx = nullptr;
10267 
10268   // Return the incoming value if it comes from the same BB as the phi node.
10269   if (P->getIncomingBlock(0) == ParentBB) {
10270     Rdx = P->getIncomingValue(0);
10271   } else if (P->getIncomingBlock(1) == ParentBB) {
10272     Rdx = P->getIncomingValue(1);
10273   }
10274 
10275   if (Rdx && DominatedReduxValue(Rdx))
10276     return Rdx;
10277 
10278   // Otherwise, check whether we have a loop latch to look at.
10279   Loop *BBL = LI->getLoopFor(ParentBB);
10280   if (!BBL)
10281     return nullptr;
10282   BasicBlock *BBLatch = BBL->getLoopLatch();
10283   if (!BBLatch)
10284     return nullptr;
10285 
10286   // There is a loop latch, return the incoming value if it comes from
10287   // that. This reduction pattern occasionally turns up.
10288   if (P->getIncomingBlock(0) == BBLatch) {
10289     Rdx = P->getIncomingValue(0);
10290   } else if (P->getIncomingBlock(1) == BBLatch) {
10291     Rdx = P->getIncomingValue(1);
10292   }
10293 
10294   if (Rdx && DominatedReduxValue(Rdx))
10295     return Rdx;
10296 
10297   return nullptr;
10298 }
10299 
10300 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10301   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10302     return true;
10303   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10304     return true;
10305   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10306     return true;
10307   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10308     return true;
10309   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10310     return true;
10311   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10312     return true;
10313   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10314     return true;
10315   return false;
10316 }
10317 
10318 /// Attempt to reduce a horizontal reduction.
10319 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10320 /// with reduction operators \a Root (or one of its operands) in a basic block
10321 /// \a BB, then check if it can be done. If horizontal reduction is not found
10322 /// and root instruction is a binary operation, vectorization of the operands is
10323 /// attempted.
10324 /// \returns true if a horizontal reduction was matched and reduced or operands
10325 /// of one of the binary instruction were vectorized.
10326 /// \returns false if a horizontal reduction was not matched (or not possible)
10327 /// or no vectorization of any binary operation feeding \a Root instruction was
10328 /// performed.
10329 static bool tryToVectorizeHorReductionOrInstOperands(
10330     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10331     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10332     const TargetLibraryInfo &TLI,
10333     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10334   if (!ShouldVectorizeHor)
10335     return false;
10336 
10337   if (!Root)
10338     return false;
10339 
10340   if (Root->getParent() != BB || isa<PHINode>(Root))
10341     return false;
10342   // Start analysis starting from Root instruction. If horizontal reduction is
10343   // found, try to vectorize it. If it is not a horizontal reduction or
10344   // vectorization is not possible or not effective, and currently analyzed
10345   // instruction is a binary operation, try to vectorize the operands, using
10346   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10347   // the same procedure considering each operand as a possible root of the
10348   // horizontal reduction.
10349   // Interrupt the process if the Root instruction itself was vectorized or all
10350   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10351   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10352   // CmpInsts so we can skip extra attempts in
10353   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10354   std::queue<std::pair<Instruction *, unsigned>> Stack;
10355   Stack.emplace(Root, 0);
10356   SmallPtrSet<Value *, 8> VisitedInstrs;
10357   SmallVector<WeakTrackingVH> PostponedInsts;
10358   bool Res = false;
10359   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10360                                                      Value *&B0,
10361                                                      Value *&B1) -> Value * {
10362     bool IsBinop = matchRdxBop(Inst, B0, B1);
10363     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10364     if (IsBinop || IsSelect) {
10365       HorizontalReduction HorRdx;
10366       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10367         return HorRdx.tryToReduce(R, TTI);
10368     }
10369     return nullptr;
10370   };
10371   while (!Stack.empty()) {
10372     Instruction *Inst;
10373     unsigned Level;
10374     std::tie(Inst, Level) = Stack.front();
10375     Stack.pop();
10376     // Do not try to analyze instruction that has already been vectorized.
10377     // This may happen when we vectorize instruction operands on a previous
10378     // iteration while stack was populated before that happened.
10379     if (R.isDeleted(Inst))
10380       continue;
10381     Value *B0 = nullptr, *B1 = nullptr;
10382     if (Value *V = TryToReduce(Inst, B0, B1)) {
10383       Res = true;
10384       // Set P to nullptr to avoid re-analysis of phi node in
10385       // matchAssociativeReduction function unless this is the root node.
10386       P = nullptr;
10387       if (auto *I = dyn_cast<Instruction>(V)) {
10388         // Try to find another reduction.
10389         Stack.emplace(I, Level);
10390         continue;
10391       }
10392     } else {
10393       bool IsBinop = B0 && B1;
10394       if (P && IsBinop) {
10395         Inst = dyn_cast<Instruction>(B0);
10396         if (Inst == P)
10397           Inst = dyn_cast<Instruction>(B1);
10398         if (!Inst) {
10399           // Set P to nullptr to avoid re-analysis of phi node in
10400           // matchAssociativeReduction function unless this is the root node.
10401           P = nullptr;
10402           continue;
10403         }
10404       }
10405       // Set P to nullptr to avoid re-analysis of phi node in
10406       // matchAssociativeReduction function unless this is the root node.
10407       P = nullptr;
10408       // Do not try to vectorize CmpInst operands, this is done separately.
10409       // Final attempt for binop args vectorization should happen after the loop
10410       // to try to find reductions.
10411       if (!isa<CmpInst>(Inst))
10412         PostponedInsts.push_back(Inst);
10413     }
10414 
10415     // Try to vectorize operands.
10416     // Continue analysis for the instruction from the same basic block only to
10417     // save compile time.
10418     if (++Level < RecursionMaxDepth)
10419       for (auto *Op : Inst->operand_values())
10420         if (VisitedInstrs.insert(Op).second)
10421           if (auto *I = dyn_cast<Instruction>(Op))
10422             // Do not try to vectorize CmpInst operands,  this is done
10423             // separately.
10424             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10425                 I->getParent() == BB)
10426               Stack.emplace(I, Level);
10427   }
10428   // Try to vectorized binops where reductions were not found.
10429   for (Value *V : PostponedInsts)
10430     if (auto *Inst = dyn_cast<Instruction>(V))
10431       if (!R.isDeleted(Inst))
10432         Res |= Vectorize(Inst, R);
10433   return Res;
10434 }
10435 
10436 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10437                                                  BasicBlock *BB, BoUpSLP &R,
10438                                                  TargetTransformInfo *TTI) {
10439   auto *I = dyn_cast_or_null<Instruction>(V);
10440   if (!I)
10441     return false;
10442 
10443   if (!isa<BinaryOperator>(I))
10444     P = nullptr;
10445   // Try to match and vectorize a horizontal reduction.
10446   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10447     return tryToVectorize(I, R);
10448   };
10449   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10450                                                   *TLI, ExtraVectorization);
10451 }
10452 
10453 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10454                                                  BasicBlock *BB, BoUpSLP &R) {
10455   const DataLayout &DL = BB->getModule()->getDataLayout();
10456   if (!R.canMapToVector(IVI->getType(), DL))
10457     return false;
10458 
10459   SmallVector<Value *, 16> BuildVectorOpds;
10460   SmallVector<Value *, 16> BuildVectorInsts;
10461   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10462     return false;
10463 
10464   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10465   // Aggregate value is unlikely to be processed in vector register.
10466   return tryToVectorizeList(BuildVectorOpds, R);
10467 }
10468 
10469 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10470                                                    BasicBlock *BB, BoUpSLP &R) {
10471   SmallVector<Value *, 16> BuildVectorInsts;
10472   SmallVector<Value *, 16> BuildVectorOpds;
10473   SmallVector<int> Mask;
10474   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10475       (llvm::all_of(
10476            BuildVectorOpds,
10477            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10478        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10479     return false;
10480 
10481   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10482   return tryToVectorizeList(BuildVectorInsts, R);
10483 }
10484 
10485 template <typename T>
10486 static bool
10487 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10488                        function_ref<unsigned(T *)> Limit,
10489                        function_ref<bool(T *, T *)> Comparator,
10490                        function_ref<bool(T *, T *)> AreCompatible,
10491                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10492                        bool LimitForRegisterSize) {
10493   bool Changed = false;
10494   // Sort by type, parent, operands.
10495   stable_sort(Incoming, Comparator);
10496 
10497   // Try to vectorize elements base on their type.
10498   SmallVector<T *> Candidates;
10499   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10500     // Look for the next elements with the same type, parent and operand
10501     // kinds.
10502     auto *SameTypeIt = IncIt;
10503     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10504       ++SameTypeIt;
10505 
10506     // Try to vectorize them.
10507     unsigned NumElts = (SameTypeIt - IncIt);
10508     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10509                       << NumElts << ")\n");
10510     // The vectorization is a 3-state attempt:
10511     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10512     // size of maximal register at first.
10513     // 2. Try to vectorize remaining instructions with the same type, if
10514     // possible. This may result in the better vectorization results rather than
10515     // if we try just to vectorize instructions with the same/alternate opcodes.
10516     // 3. Final attempt to try to vectorize all instructions with the
10517     // same/alternate ops only, this may result in some extra final
10518     // vectorization.
10519     if (NumElts > 1 &&
10520         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10521       // Success start over because instructions might have been changed.
10522       Changed = true;
10523     } else if (NumElts < Limit(*IncIt) &&
10524                (Candidates.empty() ||
10525                 Candidates.front()->getType() == (*IncIt)->getType())) {
10526       Candidates.append(IncIt, std::next(IncIt, NumElts));
10527     }
10528     // Final attempt to vectorize instructions with the same types.
10529     if (Candidates.size() > 1 &&
10530         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10531       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10532         // Success start over because instructions might have been changed.
10533         Changed = true;
10534       } else if (LimitForRegisterSize) {
10535         // Try to vectorize using small vectors.
10536         for (auto *It = Candidates.begin(), *End = Candidates.end();
10537              It != End;) {
10538           auto *SameTypeIt = It;
10539           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10540             ++SameTypeIt;
10541           unsigned NumElts = (SameTypeIt - It);
10542           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10543                                             /*LimitForRegisterSize=*/false))
10544             Changed = true;
10545           It = SameTypeIt;
10546         }
10547       }
10548       Candidates.clear();
10549     }
10550 
10551     // Start over at the next instruction of a different type (or the end).
10552     IncIt = SameTypeIt;
10553   }
10554   return Changed;
10555 }
10556 
10557 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10558 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10559 /// operands. If IsCompatibility is false, function implements strict weak
10560 /// ordering relation between two cmp instructions, returning true if the first
10561 /// instruction is "less" than the second, i.e. its predicate is less than the
10562 /// predicate of the second or the operands IDs are less than the operands IDs
10563 /// of the second cmp instruction.
10564 template <bool IsCompatibility>
10565 static bool compareCmp(Value *V, Value *V2,
10566                        function_ref<bool(Instruction *)> IsDeleted) {
10567   auto *CI1 = cast<CmpInst>(V);
10568   auto *CI2 = cast<CmpInst>(V2);
10569   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10570     return false;
10571   if (CI1->getOperand(0)->getType()->getTypeID() <
10572       CI2->getOperand(0)->getType()->getTypeID())
10573     return !IsCompatibility;
10574   if (CI1->getOperand(0)->getType()->getTypeID() >
10575       CI2->getOperand(0)->getType()->getTypeID())
10576     return false;
10577   CmpInst::Predicate Pred1 = CI1->getPredicate();
10578   CmpInst::Predicate Pred2 = CI2->getPredicate();
10579   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10580   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10581   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10582   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10583   if (BasePred1 < BasePred2)
10584     return !IsCompatibility;
10585   if (BasePred1 > BasePred2)
10586     return false;
10587   // Compare operands.
10588   bool LEPreds = Pred1 <= Pred2;
10589   bool GEPreds = Pred1 >= Pred2;
10590   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10591     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10592     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10593     if (Op1->getValueID() < Op2->getValueID())
10594       return !IsCompatibility;
10595     if (Op1->getValueID() > Op2->getValueID())
10596       return false;
10597     if (auto *I1 = dyn_cast<Instruction>(Op1))
10598       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10599         if (I1->getParent() != I2->getParent())
10600           return false;
10601         InstructionsState S = getSameOpcode({I1, I2});
10602         if (S.getOpcode())
10603           continue;
10604         return false;
10605       }
10606   }
10607   return IsCompatibility;
10608 }
10609 
10610 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10611     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10612     bool AtTerminator) {
10613   bool OpsChanged = false;
10614   SmallVector<Instruction *, 4> PostponedCmps;
10615   for (auto *I : reverse(Instructions)) {
10616     if (R.isDeleted(I))
10617       continue;
10618     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10619       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10620     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10621       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10622     else if (isa<CmpInst>(I))
10623       PostponedCmps.push_back(I);
10624   }
10625   if (AtTerminator) {
10626     // Try to find reductions first.
10627     for (Instruction *I : PostponedCmps) {
10628       if (R.isDeleted(I))
10629         continue;
10630       for (Value *Op : I->operands())
10631         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10632     }
10633     // Try to vectorize operands as vector bundles.
10634     for (Instruction *I : PostponedCmps) {
10635       if (R.isDeleted(I))
10636         continue;
10637       OpsChanged |= tryToVectorize(I, R);
10638     }
10639     // Try to vectorize list of compares.
10640     // Sort by type, compare predicate, etc.
10641     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10642       return compareCmp<false>(V, V2,
10643                                [&R](Instruction *I) { return R.isDeleted(I); });
10644     };
10645 
10646     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10647       if (V1 == V2)
10648         return true;
10649       return compareCmp<true>(V1, V2,
10650                               [&R](Instruction *I) { return R.isDeleted(I); });
10651     };
10652     auto Limit = [&R](Value *V) {
10653       unsigned EltSize = R.getVectorElementSize(V);
10654       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10655     };
10656 
10657     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10658     OpsChanged |= tryToVectorizeSequence<Value>(
10659         Vals, Limit, CompareSorter, AreCompatibleCompares,
10660         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10661           // Exclude possible reductions from other blocks.
10662           bool ArePossiblyReducedInOtherBlock =
10663               any_of(Candidates, [](Value *V) {
10664                 return any_of(V->users(), [V](User *U) {
10665                   return isa<SelectInst>(U) &&
10666                          cast<SelectInst>(U)->getParent() !=
10667                              cast<Instruction>(V)->getParent();
10668                 });
10669               });
10670           if (ArePossiblyReducedInOtherBlock)
10671             return false;
10672           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10673         },
10674         /*LimitForRegisterSize=*/true);
10675     Instructions.clear();
10676   } else {
10677     // Insert in reverse order since the PostponedCmps vector was filled in
10678     // reverse order.
10679     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10680   }
10681   return OpsChanged;
10682 }
10683 
10684 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10685   bool Changed = false;
10686   SmallVector<Value *, 4> Incoming;
10687   SmallPtrSet<Value *, 16> VisitedInstrs;
10688   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10689   // node. Allows better to identify the chains that can be vectorized in the
10690   // better way.
10691   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10692   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10693     assert(isValidElementType(V1->getType()) &&
10694            isValidElementType(V2->getType()) &&
10695            "Expected vectorizable types only.");
10696     // It is fine to compare type IDs here, since we expect only vectorizable
10697     // types, like ints, floats and pointers, we don't care about other type.
10698     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10699       return true;
10700     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10701       return false;
10702     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10703     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10704     if (Opcodes1.size() < Opcodes2.size())
10705       return true;
10706     if (Opcodes1.size() > Opcodes2.size())
10707       return false;
10708     Optional<bool> ConstOrder;
10709     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10710       // Undefs are compatible with any other value.
10711       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10712         if (!ConstOrder)
10713           ConstOrder =
10714               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10715         continue;
10716       }
10717       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10718         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10719           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10720           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10721           if (!NodeI1)
10722             return NodeI2 != nullptr;
10723           if (!NodeI2)
10724             return false;
10725           assert((NodeI1 == NodeI2) ==
10726                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10727                  "Different nodes should have different DFS numbers");
10728           if (NodeI1 != NodeI2)
10729             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10730           InstructionsState S = getSameOpcode({I1, I2});
10731           if (S.getOpcode())
10732             continue;
10733           return I1->getOpcode() < I2->getOpcode();
10734         }
10735       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10736         if (!ConstOrder)
10737           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10738         continue;
10739       }
10740       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10741         return true;
10742       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10743         return false;
10744     }
10745     return ConstOrder && *ConstOrder;
10746   };
10747   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10748     if (V1 == V2)
10749       return true;
10750     if (V1->getType() != V2->getType())
10751       return false;
10752     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10753     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10754     if (Opcodes1.size() != Opcodes2.size())
10755       return false;
10756     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10757       // Undefs are compatible with any other value.
10758       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10759         continue;
10760       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10761         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10762           if (I1->getParent() != I2->getParent())
10763             return false;
10764           InstructionsState S = getSameOpcode({I1, I2});
10765           if (S.getOpcode())
10766             continue;
10767           return false;
10768         }
10769       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10770         continue;
10771       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10772         return false;
10773     }
10774     return true;
10775   };
10776   auto Limit = [&R](Value *V) {
10777     unsigned EltSize = R.getVectorElementSize(V);
10778     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10779   };
10780 
10781   bool HaveVectorizedPhiNodes = false;
10782   do {
10783     // Collect the incoming values from the PHIs.
10784     Incoming.clear();
10785     for (Instruction &I : *BB) {
10786       PHINode *P = dyn_cast<PHINode>(&I);
10787       if (!P)
10788         break;
10789 
10790       // No need to analyze deleted, vectorized and non-vectorizable
10791       // instructions.
10792       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10793           isValidElementType(P->getType()))
10794         Incoming.push_back(P);
10795     }
10796 
10797     // Find the corresponding non-phi nodes for better matching when trying to
10798     // build the tree.
10799     for (Value *V : Incoming) {
10800       SmallVectorImpl<Value *> &Opcodes =
10801           PHIToOpcodes.try_emplace(V).first->getSecond();
10802       if (!Opcodes.empty())
10803         continue;
10804       SmallVector<Value *, 4> Nodes(1, V);
10805       SmallPtrSet<Value *, 4> Visited;
10806       while (!Nodes.empty()) {
10807         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10808         if (!Visited.insert(PHI).second)
10809           continue;
10810         for (Value *V : PHI->incoming_values()) {
10811           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10812             Nodes.push_back(PHI1);
10813             continue;
10814           }
10815           Opcodes.emplace_back(V);
10816         }
10817       }
10818     }
10819 
10820     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10821         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10822         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10823           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10824         },
10825         /*LimitForRegisterSize=*/true);
10826     Changed |= HaveVectorizedPhiNodes;
10827     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10828   } while (HaveVectorizedPhiNodes);
10829 
10830   VisitedInstrs.clear();
10831 
10832   SmallVector<Instruction *, 8> PostProcessInstructions;
10833   SmallDenseSet<Instruction *, 4> KeyNodes;
10834   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10835     // Skip instructions with scalable type. The num of elements is unknown at
10836     // compile-time for scalable type.
10837     if (isa<ScalableVectorType>(it->getType()))
10838       continue;
10839 
10840     // Skip instructions marked for the deletion.
10841     if (R.isDeleted(&*it))
10842       continue;
10843     // We may go through BB multiple times so skip the one we have checked.
10844     if (!VisitedInstrs.insert(&*it).second) {
10845       if (it->use_empty() && KeyNodes.contains(&*it) &&
10846           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10847                                       it->isTerminator())) {
10848         // We would like to start over since some instructions are deleted
10849         // and the iterator may become invalid value.
10850         Changed = true;
10851         it = BB->begin();
10852         e = BB->end();
10853       }
10854       continue;
10855     }
10856 
10857     if (isa<DbgInfoIntrinsic>(it))
10858       continue;
10859 
10860     // Try to vectorize reductions that use PHINodes.
10861     if (PHINode *P = dyn_cast<PHINode>(it)) {
10862       // Check that the PHI is a reduction PHI.
10863       if (P->getNumIncomingValues() == 2) {
10864         // Try to match and vectorize a horizontal reduction.
10865         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10866                                      TTI)) {
10867           Changed = true;
10868           it = BB->begin();
10869           e = BB->end();
10870           continue;
10871         }
10872       }
10873       // Try to vectorize the incoming values of the PHI, to catch reductions
10874       // that feed into PHIs.
10875       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10876         // Skip if the incoming block is the current BB for now. Also, bypass
10877         // unreachable IR for efficiency and to avoid crashing.
10878         // TODO: Collect the skipped incoming values and try to vectorize them
10879         // after processing BB.
10880         if (BB == P->getIncomingBlock(I) ||
10881             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10882           continue;
10883 
10884         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10885                                             P->getIncomingBlock(I), R, TTI);
10886       }
10887       continue;
10888     }
10889 
10890     // Ran into an instruction without users, like terminator, or function call
10891     // with ignored return value, store. Ignore unused instructions (basing on
10892     // instruction type, except for CallInst and InvokeInst).
10893     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10894                             isa<InvokeInst>(it))) {
10895       KeyNodes.insert(&*it);
10896       bool OpsChanged = false;
10897       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10898         for (auto *V : it->operand_values()) {
10899           // Try to match and vectorize a horizontal reduction.
10900           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10901         }
10902       }
10903       // Start vectorization of post-process list of instructions from the
10904       // top-tree instructions to try to vectorize as many instructions as
10905       // possible.
10906       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10907                                                 it->isTerminator());
10908       if (OpsChanged) {
10909         // We would like to start over since some instructions are deleted
10910         // and the iterator may become invalid value.
10911         Changed = true;
10912         it = BB->begin();
10913         e = BB->end();
10914         continue;
10915       }
10916     }
10917 
10918     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10919         isa<InsertValueInst>(it))
10920       PostProcessInstructions.push_back(&*it);
10921   }
10922 
10923   return Changed;
10924 }
10925 
10926 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10927   auto Changed = false;
10928   for (auto &Entry : GEPs) {
10929     // If the getelementptr list has fewer than two elements, there's nothing
10930     // to do.
10931     if (Entry.second.size() < 2)
10932       continue;
10933 
10934     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10935                       << Entry.second.size() << ".\n");
10936 
10937     // Process the GEP list in chunks suitable for the target's supported
10938     // vector size. If a vector register can't hold 1 element, we are done. We
10939     // are trying to vectorize the index computations, so the maximum number of
10940     // elements is based on the size of the index expression, rather than the
10941     // size of the GEP itself (the target's pointer size).
10942     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10943     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10944     if (MaxVecRegSize < EltSize)
10945       continue;
10946 
10947     unsigned MaxElts = MaxVecRegSize / EltSize;
10948     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10949       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10950       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10951 
10952       // Initialize a set a candidate getelementptrs. Note that we use a
10953       // SetVector here to preserve program order. If the index computations
10954       // are vectorizable and begin with loads, we want to minimize the chance
10955       // of having to reorder them later.
10956       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10957 
10958       // Some of the candidates may have already been vectorized after we
10959       // initially collected them. If so, they are marked as deleted, so remove
10960       // them from the set of candidates.
10961       Candidates.remove_if(
10962           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10963 
10964       // Remove from the set of candidates all pairs of getelementptrs with
10965       // constant differences. Such getelementptrs are likely not good
10966       // candidates for vectorization in a bottom-up phase since one can be
10967       // computed from the other. We also ensure all candidate getelementptr
10968       // indices are unique.
10969       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10970         auto *GEPI = GEPList[I];
10971         if (!Candidates.count(GEPI))
10972           continue;
10973         auto *SCEVI = SE->getSCEV(GEPList[I]);
10974         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10975           auto *GEPJ = GEPList[J];
10976           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10977           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10978             Candidates.remove(GEPI);
10979             Candidates.remove(GEPJ);
10980           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10981             Candidates.remove(GEPJ);
10982           }
10983         }
10984       }
10985 
10986       // We break out of the above computation as soon as we know there are
10987       // fewer than two candidates remaining.
10988       if (Candidates.size() < 2)
10989         continue;
10990 
10991       // Add the single, non-constant index of each candidate to the bundle. We
10992       // ensured the indices met these constraints when we originally collected
10993       // the getelementptrs.
10994       SmallVector<Value *, 16> Bundle(Candidates.size());
10995       auto BundleIndex = 0u;
10996       for (auto *V : Candidates) {
10997         auto *GEP = cast<GetElementPtrInst>(V);
10998         auto *GEPIdx = GEP->idx_begin()->get();
10999         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
11000         Bundle[BundleIndex++] = GEPIdx;
11001       }
11002 
11003       // Try and vectorize the indices. We are currently only interested in
11004       // gather-like cases of the form:
11005       //
11006       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11007       //
11008       // where the loads of "a", the loads of "b", and the subtractions can be
11009       // performed in parallel. It's likely that detecting this pattern in a
11010       // bottom-up phase will be simpler and less costly than building a
11011       // full-blown top-down phase beginning at the consecutive loads.
11012       Changed |= tryToVectorizeList(Bundle, R);
11013     }
11014   }
11015   return Changed;
11016 }
11017 
11018 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11019   bool Changed = false;
11020   // Sort by type, base pointers and values operand. Value operands must be
11021   // compatible (have the same opcode, same parent), otherwise it is
11022   // definitely not profitable to try to vectorize them.
11023   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11024     if (V->getPointerOperandType()->getTypeID() <
11025         V2->getPointerOperandType()->getTypeID())
11026       return true;
11027     if (V->getPointerOperandType()->getTypeID() >
11028         V2->getPointerOperandType()->getTypeID())
11029       return false;
11030     // UndefValues are compatible with all other values.
11031     if (isa<UndefValue>(V->getValueOperand()) ||
11032         isa<UndefValue>(V2->getValueOperand()))
11033       return false;
11034     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11035       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11036         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11037             DT->getNode(I1->getParent());
11038         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11039             DT->getNode(I2->getParent());
11040         assert(NodeI1 && "Should only process reachable instructions");
11041         assert(NodeI1 && "Should only process reachable instructions");
11042         assert((NodeI1 == NodeI2) ==
11043                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11044                "Different nodes should have different DFS numbers");
11045         if (NodeI1 != NodeI2)
11046           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11047         InstructionsState S = getSameOpcode({I1, I2});
11048         if (S.getOpcode())
11049           return false;
11050         return I1->getOpcode() < I2->getOpcode();
11051       }
11052     if (isa<Constant>(V->getValueOperand()) &&
11053         isa<Constant>(V2->getValueOperand()))
11054       return false;
11055     return V->getValueOperand()->getValueID() <
11056            V2->getValueOperand()->getValueID();
11057   };
11058 
11059   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11060     if (V1 == V2)
11061       return true;
11062     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11063       return false;
11064     // Undefs are compatible with any other value.
11065     if (isa<UndefValue>(V1->getValueOperand()) ||
11066         isa<UndefValue>(V2->getValueOperand()))
11067       return true;
11068     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11069       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11070         if (I1->getParent() != I2->getParent())
11071           return false;
11072         InstructionsState S = getSameOpcode({I1, I2});
11073         return S.getOpcode() > 0;
11074       }
11075     if (isa<Constant>(V1->getValueOperand()) &&
11076         isa<Constant>(V2->getValueOperand()))
11077       return true;
11078     return V1->getValueOperand()->getValueID() ==
11079            V2->getValueOperand()->getValueID();
11080   };
11081   auto Limit = [&R, this](StoreInst *SI) {
11082     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11083     return R.getMinVF(EltSize);
11084   };
11085 
11086   // Attempt to sort and vectorize each of the store-groups.
11087   for (auto &Pair : Stores) {
11088     if (Pair.second.size() < 2)
11089       continue;
11090 
11091     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11092                       << Pair.second.size() << ".\n");
11093 
11094     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11095       continue;
11096 
11097     Changed |= tryToVectorizeSequence<StoreInst>(
11098         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11099         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11100           return vectorizeStores(Candidates, R);
11101         },
11102         /*LimitForRegisterSize=*/false);
11103   }
11104   return Changed;
11105 }
11106 
11107 char SLPVectorizer::ID = 0;
11108 
11109 static const char lv_name[] = "SLP Vectorizer";
11110 
11111 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11112 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11113 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11114 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11115 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11116 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11117 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11118 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11119 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11120 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11121 
11122 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11123