1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<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 namespace slpvectorizer {
776 
777 /// Bottom Up SLP Vectorizer.
778 class BoUpSLP {
779   struct TreeEntry;
780   struct ScheduleData;
781 
782 public:
783   using ValueList = SmallVector<Value *, 8>;
784   using InstrList = SmallVector<Instruction *, 16>;
785   using ValueSet = SmallPtrSet<Value *, 16>;
786   using StoreList = SmallVector<StoreInst *, 8>;
787   using ExtraValueToDebugLocsMap =
788       MapVector<Value *, SmallVector<Instruction *, 2>>;
789   using OrdersType = SmallVector<unsigned, 4>;
790 
791   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
792           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
793           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
794           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
795       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
796         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
797     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
798     // Use the vector register size specified by the target unless overridden
799     // by a command-line option.
800     // TODO: It would be better to limit the vectorization factor based on
801     //       data type rather than just register size. For example, x86 AVX has
802     //       256-bit registers, but it does not support integer operations
803     //       at that width (that requires AVX2).
804     if (MaxVectorRegSizeOption.getNumOccurrences())
805       MaxVecRegSize = MaxVectorRegSizeOption;
806     else
807       MaxVecRegSize =
808           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
809               .getFixedSize();
810 
811     if (MinVectorRegSizeOption.getNumOccurrences())
812       MinVecRegSize = MinVectorRegSizeOption;
813     else
814       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
815   }
816 
817   /// Vectorize the tree that starts with the elements in \p VL.
818   /// Returns the vectorized root.
819   Value *vectorizeTree();
820 
821   /// Vectorize the tree but with the list of externally used values \p
822   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
823   /// generated extractvalue instructions.
824   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
825 
826   /// \returns the cost incurred by unwanted spills and fills, caused by
827   /// holding live values over call sites.
828   InstructionCost getSpillCost() const;
829 
830   /// \returns the vectorization cost of the subtree that starts at \p VL.
831   /// A negative number means that this is profitable.
832   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
833 
834   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
835   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
836   void buildTree(ArrayRef<Value *> Roots,
837                  ArrayRef<Value *> UserIgnoreLst = None);
838 
839   /// Builds external uses of the vectorized scalars, i.e. the list of
840   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
841   /// ExternallyUsedValues contains additional list of external uses to handle
842   /// vectorization of reductions.
843   void
844   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
845 
846   /// Clear the internal data structures that are created by 'buildTree'.
847   void deleteTree() {
848     VectorizableTree.clear();
849     ScalarToTreeEntry.clear();
850     MustGather.clear();
851     ExternalUses.clear();
852     for (auto &Iter : BlocksSchedules) {
853       BlockScheduling *BS = Iter.second.get();
854       BS->clear();
855     }
856     MinBWs.clear();
857     InstrElementSize.clear();
858   }
859 
860   unsigned getTreeSize() const { return VectorizableTree.size(); }
861 
862   /// Perform LICM and CSE on the newly generated gather sequences.
863   void optimizeGatherSequence();
864 
865   /// Checks if the specified gather tree entry \p TE can be represented as a
866   /// shuffled vector entry + (possibly) permutation with other gathers. It
867   /// implements the checks only for possibly ordered scalars (Loads,
868   /// ExtractElement, ExtractValue), which can be part of the graph.
869   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
870 
871   /// Gets reordering data for the given tree entry. If the entry is vectorized
872   /// - just return ReorderIndices, otherwise check if the scalars can be
873   /// reordered and return the most optimal order.
874   /// \param TopToBottom If true, include the order of vectorized stores and
875   /// insertelement nodes, otherwise skip them.
876   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
877 
878   /// Reorders the current graph to the most profitable order starting from the
879   /// root node to the leaf nodes. The best order is chosen only from the nodes
880   /// of the same size (vectorization factor). Smaller nodes are considered
881   /// parts of subgraph with smaller VF and they are reordered independently. We
882   /// can make it because we still need to extend smaller nodes to the wider VF
883   /// and we can merge reordering shuffles with the widening shuffles.
884   void reorderTopToBottom();
885 
886   /// Reorders the current graph to the most profitable order starting from
887   /// leaves to the root. It allows to rotate small subgraphs and reduce the
888   /// number of reshuffles if the leaf nodes use the same order. In this case we
889   /// can merge the orders and just shuffle user node instead of shuffling its
890   /// operands. Plus, even the leaf nodes have different orders, it allows to
891   /// sink reordering in the graph closer to the root node and merge it later
892   /// during analysis.
893   void reorderBottomToTop(bool IgnoreReorder = false);
894 
895   /// \return The vector element size in bits to use when vectorizing the
896   /// expression tree ending at \p V. If V is a store, the size is the width of
897   /// the stored value. Otherwise, the size is the width of the largest loaded
898   /// value reaching V. This method is used by the vectorizer to calculate
899   /// vectorization factors.
900   unsigned getVectorElementSize(Value *V);
901 
902   /// Compute the minimum type sizes required to represent the entries in a
903   /// vectorizable tree.
904   void computeMinimumValueSizes();
905 
906   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
907   unsigned getMaxVecRegSize() const {
908     return MaxVecRegSize;
909   }
910 
911   // \returns minimum vector register size as set by cl::opt.
912   unsigned getMinVecRegSize() const {
913     return MinVecRegSize;
914   }
915 
916   unsigned getMinVF(unsigned Sz) const {
917     return std::max(2U, getMinVecRegSize() / Sz);
918   }
919 
920   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
921     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
922       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
923     return MaxVF ? MaxVF : UINT_MAX;
924   }
925 
926   /// Check if homogeneous aggregate is isomorphic to some VectorType.
927   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
928   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
929   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
930   ///
931   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
932   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
933 
934   /// \returns True if the VectorizableTree is both tiny and not fully
935   /// vectorizable. We do not vectorize such trees.
936   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
937 
938   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
939   /// can be load combined in the backend. Load combining may not be allowed in
940   /// the IR optimizer, so we do not want to alter the pattern. For example,
941   /// partially transforming a scalar bswap() pattern into vector code is
942   /// effectively impossible for the backend to undo.
943   /// TODO: If load combining is allowed in the IR optimizer, this analysis
944   ///       may not be necessary.
945   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
946 
947   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
948   /// can be load combined in the backend. Load combining may not be allowed in
949   /// the IR optimizer, so we do not want to alter the pattern. For example,
950   /// partially transforming a scalar bswap() pattern into vector code is
951   /// effectively impossible for the backend to undo.
952   /// TODO: If load combining is allowed in the IR optimizer, this analysis
953   ///       may not be necessary.
954   bool isLoadCombineCandidate() const;
955 
956   OptimizationRemarkEmitter *getORE() { return ORE; }
957 
958   /// This structure holds any data we need about the edges being traversed
959   /// during buildTree_rec(). We keep track of:
960   /// (i) the user TreeEntry index, and
961   /// (ii) the index of the edge.
962   struct EdgeInfo {
963     EdgeInfo() = default;
964     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
965         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
966     /// The user TreeEntry.
967     TreeEntry *UserTE = nullptr;
968     /// The operand index of the use.
969     unsigned EdgeIdx = UINT_MAX;
970 #ifndef NDEBUG
971     friend inline raw_ostream &operator<<(raw_ostream &OS,
972                                           const BoUpSLP::EdgeInfo &EI) {
973       EI.dump(OS);
974       return OS;
975     }
976     /// Debug print.
977     void dump(raw_ostream &OS) const {
978       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
979          << " EdgeIdx:" << EdgeIdx << "}";
980     }
981     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
982 #endif
983   };
984 
985   /// A helper data structure to hold the operands of a vector of instructions.
986   /// This supports a fixed vector length for all operand vectors.
987   class VLOperands {
988     /// For each operand we need (i) the value, and (ii) the opcode that it
989     /// would be attached to if the expression was in a left-linearized form.
990     /// This is required to avoid illegal operand reordering.
991     /// For example:
992     /// \verbatim
993     ///                         0 Op1
994     ///                         |/
995     /// Op1 Op2   Linearized    + Op2
996     ///   \ /     ---------->   |/
997     ///    -                    -
998     ///
999     /// Op1 - Op2            (0 + Op1) - Op2
1000     /// \endverbatim
1001     ///
1002     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1003     ///
1004     /// Another way to think of this is to track all the operations across the
1005     /// path from the operand all the way to the root of the tree and to
1006     /// calculate the operation that corresponds to this path. For example, the
1007     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1008     /// corresponding operation is a '-' (which matches the one in the
1009     /// linearized tree, as shown above).
1010     ///
1011     /// For lack of a better term, we refer to this operation as Accumulated
1012     /// Path Operation (APO).
1013     struct OperandData {
1014       OperandData() = default;
1015       OperandData(Value *V, bool APO, bool IsUsed)
1016           : V(V), APO(APO), IsUsed(IsUsed) {}
1017       /// The operand value.
1018       Value *V = nullptr;
1019       /// TreeEntries only allow a single opcode, or an alternate sequence of
1020       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1021       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1022       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1023       /// (e.g., Add/Mul)
1024       bool APO = false;
1025       /// Helper data for the reordering function.
1026       bool IsUsed = false;
1027     };
1028 
1029     /// During operand reordering, we are trying to select the operand at lane
1030     /// that matches best with the operand at the neighboring lane. Our
1031     /// selection is based on the type of value we are looking for. For example,
1032     /// if the neighboring lane has a load, we need to look for a load that is
1033     /// accessing a consecutive address. These strategies are summarized in the
1034     /// 'ReorderingMode' enumerator.
1035     enum class ReorderingMode {
1036       Load,     ///< Matching loads to consecutive memory addresses
1037       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1038       Constant, ///< Matching constants
1039       Splat,    ///< Matching the same instruction multiple times (broadcast)
1040       Failed,   ///< We failed to create a vectorizable group
1041     };
1042 
1043     using OperandDataVec = SmallVector<OperandData, 2>;
1044 
1045     /// A vector of operand vectors.
1046     SmallVector<OperandDataVec, 4> OpsVec;
1047 
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051 
1052     /// \returns the operand data at \p OpIdx and \p Lane.
1053     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1054       return OpsVec[OpIdx][Lane];
1055     }
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1058     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// Clears the used flag for all entries.
1063     void clearUsed() {
1064       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1065            OpIdx != NumOperands; ++OpIdx)
1066         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1067              ++Lane)
1068           OpsVec[OpIdx][Lane].IsUsed = false;
1069     }
1070 
1071     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1072     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1073       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1074     }
1075 
1076     // The hard-coded scores listed here are not very important, though it shall
1077     // be higher for better matches to improve the resulting cost. When
1078     // computing the scores of matching one sub-tree with another, we are
1079     // basically counting the number of values that are matching. So even if all
1080     // scores are set to 1, we would still get a decent matching result.
1081     // However, sometimes we have to break ties. For example we may have to
1082     // choose between matching loads vs matching opcodes. This is what these
1083     // scores are helping us with: they provide the order of preference. Also,
1084     // this is important if the scalar is externally used or used in another
1085     // tree entry node in the different lane.
1086 
1087     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1088     static const int ScoreConsecutiveLoads = 4;
1089     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1090     static const int ScoreReversedLoads = 3;
1091     /// ExtractElementInst from same vector and consecutive indexes.
1092     static const int ScoreConsecutiveExtracts = 4;
1093     /// ExtractElementInst from same vector and reversed indices.
1094     static const int ScoreReversedExtracts = 3;
1095     /// Constants.
1096     static const int ScoreConstants = 2;
1097     /// Instructions with the same opcode.
1098     static const int ScoreSameOpcode = 2;
1099     /// Instructions with alt opcodes (e.g, add + sub).
1100     static const int ScoreAltOpcodes = 1;
1101     /// Identical instructions (a.k.a. splat or broadcast).
1102     static const int ScoreSplat = 1;
1103     /// Matching with an undef is preferable to failing.
1104     static const int ScoreUndef = 1;
1105     /// Score for failing to find a decent match.
1106     static const int ScoreFail = 0;
1107     /// Score if all users are vectorized.
1108     static const int ScoreAllUserVectorized = 1;
1109 
1110     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1111     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1112     /// MainAltOps.
1113     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1114                                ScalarEvolution &SE, int NumLanes,
1115                                ArrayRef<Value *> MainAltOps) {
1116       if (V1 == V2)
1117         return VLOperands::ScoreSplat;
1118 
1119       auto *LI1 = dyn_cast<LoadInst>(V1);
1120       auto *LI2 = dyn_cast<LoadInst>(V2);
1121       if (LI1 && LI2) {
1122         if (LI1->getParent() != LI2->getParent())
1123           return VLOperands::ScoreFail;
1124 
1125         Optional<int> Dist = getPointersDiff(
1126             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1127             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1128         if (!Dist || *Dist == 0)
1129           return VLOperands::ScoreFail;
1130         // The distance is too large - still may be profitable to use masked
1131         // loads/gathers.
1132         if (std::abs(*Dist) > NumLanes / 2)
1133           return VLOperands::ScoreAltOpcodes;
1134         // This still will detect consecutive loads, but we might have "holes"
1135         // in some cases. It is ok for non-power-2 vectorization and may produce
1136         // better results. It should not affect current vectorization.
1137         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1138                            : VLOperands::ScoreReversedLoads;
1139       }
1140 
1141       auto *C1 = dyn_cast<Constant>(V1);
1142       auto *C2 = dyn_cast<Constant>(V2);
1143       if (C1 && C2)
1144         return VLOperands::ScoreConstants;
1145 
1146       // Extracts from consecutive indexes of the same vector better score as
1147       // the extracts could be optimized away.
1148       Value *EV1;
1149       ConstantInt *Ex1Idx;
1150       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1151         // Undefs are always profitable for extractelements.
1152         if (isa<UndefValue>(V2))
1153           return VLOperands::ScoreConsecutiveExtracts;
1154         Value *EV2 = nullptr;
1155         ConstantInt *Ex2Idx = nullptr;
1156         if (match(V2,
1157                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1158                                                          m_Undef())))) {
1159           // Undefs are always profitable for extractelements.
1160           if (!Ex2Idx)
1161             return VLOperands::ScoreConsecutiveExtracts;
1162           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1163             return VLOperands::ScoreConsecutiveExtracts;
1164           if (EV2 == EV1) {
1165             int Idx1 = Ex1Idx->getZExtValue();
1166             int Idx2 = Ex2Idx->getZExtValue();
1167             int Dist = Idx2 - Idx1;
1168             // The distance is too large - still may be profitable to use
1169             // shuffles.
1170             if (std::abs(Dist) == 0)
1171               return VLOperands::ScoreSplat;
1172             if (std::abs(Dist) > NumLanes / 2)
1173               return VLOperands::ScoreSameOpcode;
1174             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1175                               : VLOperands::ScoreReversedExtracts;
1176           }
1177           return VLOperands::ScoreAltOpcodes;
1178         }
1179         return VLOperands::ScoreFail;
1180       }
1181 
1182       auto *I1 = dyn_cast<Instruction>(V1);
1183       auto *I2 = dyn_cast<Instruction>(V2);
1184       if (I1 && I2) {
1185         if (I1->getParent() != I2->getParent())
1186           return VLOperands::ScoreFail;
1187         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1188         Ops.push_back(I1);
1189         Ops.push_back(I2);
1190         InstructionsState S = getSameOpcode(Ops);
1191         // Note: Only consider instructions with <= 2 operands to avoid
1192         // complexity explosion.
1193         if (S.getOpcode() &&
1194             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1195              !S.isAltShuffle()) &&
1196             all_of(Ops, [&S](Value *V) {
1197               return cast<Instruction>(V)->getNumOperands() ==
1198                      S.MainOp->getNumOperands();
1199             }))
1200           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1201                                   : VLOperands::ScoreSameOpcode;
1202       }
1203 
1204       if (isa<UndefValue>(V2))
1205         return VLOperands::ScoreUndef;
1206 
1207       return VLOperands::ScoreFail;
1208     }
1209 
1210     /// \param Lane lane of the operands under analysis.
1211     /// \param OpIdx operand index in \p Lane lane we're looking the best
1212     /// candidate for.
1213     /// \param Idx operand index of the current candidate value.
1214     /// \returns The additional score due to possible broadcasting of the
1215     /// elements in the lane. It is more profitable to have power-of-2 unique
1216     /// elements in the lane, it will be vectorized with higher probability
1217     /// after removing duplicates. Currently the SLP vectorizer supports only
1218     /// vectorization of the power-of-2 number of unique scalars.
1219     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1220       Value *IdxLaneV = getData(Idx, Lane).V;
1221       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1222         return 0;
1223       SmallPtrSet<Value *, 4> Uniques;
1224       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1225         if (Ln == Lane)
1226           continue;
1227         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1228         if (!isa<Instruction>(OpIdxLnV))
1229           return 0;
1230         Uniques.insert(OpIdxLnV);
1231       }
1232       int UniquesCount = Uniques.size();
1233       int UniquesCntWithIdxLaneV =
1234           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1235       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1236       int UniquesCntWithOpIdxLaneV =
1237           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1238       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1239         return 0;
1240       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1241               UniquesCntWithOpIdxLaneV) -
1242              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1243     }
1244 
1245     /// \param Lane lane of the operands under analysis.
1246     /// \param OpIdx operand index in \p Lane lane we're looking the best
1247     /// candidate for.
1248     /// \param Idx operand index of the current candidate value.
1249     /// \returns The additional score for the scalar which users are all
1250     /// vectorized.
1251     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1252       Value *IdxLaneV = getData(Idx, Lane).V;
1253       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1254       // Do not care about number of uses for vector-like instructions
1255       // (extractelement/extractvalue with constant indices), they are extracts
1256       // themselves and already externally used. Vectorization of such
1257       // instructions does not add extra extractelement instruction, just may
1258       // remove it.
1259       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1260           isVectorLikeInstWithConstOps(OpIdxLaneV))
1261         return VLOperands::ScoreAllUserVectorized;
1262       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1263       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1264         return 0;
1265       return R.areAllUsersVectorized(IdxLaneI, None)
1266                  ? VLOperands::ScoreAllUserVectorized
1267                  : 0;
1268     }
1269 
1270     /// Go through the operands of \p LHS and \p RHS recursively until \p
1271     /// MaxLevel, and return the cummulative score. For example:
1272     /// \verbatim
1273     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1274     ///     \ /         \ /         \ /        \ /
1275     ///      +           +           +          +
1276     ///     G1          G2          G3         G4
1277     /// \endverbatim
1278     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1279     /// each level recursively, accumulating the score. It starts from matching
1280     /// the additions at level 0, then moves on to the loads (level 1). The
1281     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1282     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1283     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1284     /// Please note that the order of the operands does not matter, as we
1285     /// evaluate the score of all profitable combinations of operands. In
1286     /// other words the score of G1 and G4 is the same as G1 and G2. This
1287     /// heuristic is based on ideas described in:
1288     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1289     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1290     ///   Luís F. W. Góes
1291     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1292                            ArrayRef<Value *> MainAltOps) {
1293 
1294       // Get the shallow score of V1 and V2.
1295       int ShallowScoreAtThisLevel =
1296           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1297 
1298       // If reached MaxLevel,
1299       //  or if V1 and V2 are not instructions,
1300       //  or if they are SPLAT,
1301       //  or if they are not consecutive,
1302       //  or if profitable to vectorize loads or extractelements, early return
1303       //  the current cost.
1304       auto *I1 = dyn_cast<Instruction>(LHS);
1305       auto *I2 = dyn_cast<Instruction>(RHS);
1306       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1307           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1308           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1309             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1310             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1311            ShallowScoreAtThisLevel))
1312         return ShallowScoreAtThisLevel;
1313       assert(I1 && I2 && "Should have early exited.");
1314 
1315       // Contains the I2 operand indexes that got matched with I1 operands.
1316       SmallSet<unsigned, 4> Op2Used;
1317 
1318       // Recursion towards the operands of I1 and I2. We are trying all possible
1319       // operand pairs, and keeping track of the best score.
1320       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1321            OpIdx1 != NumOperands1; ++OpIdx1) {
1322         // Try to pair op1I with the best operand of I2.
1323         int MaxTmpScore = 0;
1324         unsigned MaxOpIdx2 = 0;
1325         bool FoundBest = false;
1326         // If I2 is commutative try all combinations.
1327         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1328         unsigned ToIdx = isCommutative(I2)
1329                              ? I2->getNumOperands()
1330                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1331         assert(FromIdx <= ToIdx && "Bad index");
1332         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1333           // Skip operands already paired with OpIdx1.
1334           if (Op2Used.count(OpIdx2))
1335             continue;
1336           // Recursively calculate the cost at each level
1337           int TmpScore =
1338               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1339                                  CurrLevel + 1, MaxLevel, None);
1340           // Look for the best score.
1341           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1342             MaxTmpScore = TmpScore;
1343             MaxOpIdx2 = OpIdx2;
1344             FoundBest = true;
1345           }
1346         }
1347         if (FoundBest) {
1348           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1349           Op2Used.insert(MaxOpIdx2);
1350           ShallowScoreAtThisLevel += MaxTmpScore;
1351         }
1352       }
1353       return ShallowScoreAtThisLevel;
1354     }
1355 
1356     /// Score scaling factor for fully compatible instructions but with
1357     /// different number of external uses. Allows better selection of the
1358     /// instructions with less external uses.
1359     static const int ScoreScaleFactor = 10;
1360 
1361     /// \Returns the look-ahead score, which tells us how much the sub-trees
1362     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1363     /// score. This helps break ties in an informed way when we cannot decide on
1364     /// the order of the operands by just considering the immediate
1365     /// predecessors.
1366     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1367                           int Lane, unsigned OpIdx, unsigned Idx,
1368                           bool &IsUsed) {
1369       int Score =
1370           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1371       if (Score) {
1372         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1373         if (Score <= -SplatScore) {
1374           // Set the minimum score for splat-like sequence to avoid setting
1375           // failed state.
1376           Score = 1;
1377         } else {
1378           Score += SplatScore;
1379           // Scale score to see the difference between different operands
1380           // and similar operands but all vectorized/not all vectorized
1381           // uses. It does not affect actual selection of the best
1382           // compatible operand in general, just allows to select the
1383           // operand with all vectorized uses.
1384           Score *= ScoreScaleFactor;
1385           Score += getExternalUseScore(Lane, OpIdx, Idx);
1386           IsUsed = true;
1387         }
1388       }
1389       return Score;
1390     }
1391 
1392     /// Best defined scores per lanes between the passes. Used to choose the
1393     /// best operand (with the highest score) between the passes.
1394     /// The key - {Operand Index, Lane}.
1395     /// The value - the best score between the passes for the lane and the
1396     /// operand.
1397     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1398         BestScoresPerLanes;
1399 
1400     // Search all operands in Ops[*][Lane] for the one that matches best
1401     // Ops[OpIdx][LastLane] and return its opreand index.
1402     // If no good match can be found, return None.
1403     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1404                                       ArrayRef<ReorderingMode> ReorderingModes,
1405                                       ArrayRef<Value *> MainAltOps) {
1406       unsigned NumOperands = getNumOperands();
1407 
1408       // The operand of the previous lane at OpIdx.
1409       Value *OpLastLane = getData(OpIdx, LastLane).V;
1410 
1411       // Our strategy mode for OpIdx.
1412       ReorderingMode RMode = ReorderingModes[OpIdx];
1413       if (RMode == ReorderingMode::Failed)
1414         return None;
1415 
1416       // The linearized opcode of the operand at OpIdx, Lane.
1417       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1418 
1419       // The best operand index and its score.
1420       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1421       // are using the score to differentiate between the two.
1422       struct BestOpData {
1423         Optional<unsigned> Idx = None;
1424         unsigned Score = 0;
1425       } BestOp;
1426       BestOp.Score =
1427           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1428               .first->second;
1429 
1430       // Track if the operand must be marked as used. If the operand is set to
1431       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1432       // want to reestimate the operands again on the following iterations).
1433       bool IsUsed =
1434           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1435       // Iterate through all unused operands and look for the best.
1436       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1437         // Get the operand at Idx and Lane.
1438         OperandData &OpData = getData(Idx, Lane);
1439         Value *Op = OpData.V;
1440         bool OpAPO = OpData.APO;
1441 
1442         // Skip already selected operands.
1443         if (OpData.IsUsed)
1444           continue;
1445 
1446         // Skip if we are trying to move the operand to a position with a
1447         // different opcode in the linearized tree form. This would break the
1448         // semantics.
1449         if (OpAPO != OpIdxAPO)
1450           continue;
1451 
1452         // Look for an operand that matches the current mode.
1453         switch (RMode) {
1454         case ReorderingMode::Load:
1455         case ReorderingMode::Constant:
1456         case ReorderingMode::Opcode: {
1457           bool LeftToRight = Lane > LastLane;
1458           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1459           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1460           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1461                                         OpIdx, Idx, IsUsed);
1462           if (Score > static_cast<int>(BestOp.Score)) {
1463             BestOp.Idx = Idx;
1464             BestOp.Score = Score;
1465             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1466           }
1467           break;
1468         }
1469         case ReorderingMode::Splat:
1470           if (Op == OpLastLane)
1471             BestOp.Idx = Idx;
1472           break;
1473         case ReorderingMode::Failed:
1474           llvm_unreachable("Not expected Failed reordering mode.");
1475         }
1476       }
1477 
1478       if (BestOp.Idx) {
1479         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1480         return BestOp.Idx;
1481       }
1482       // If we could not find a good match return None.
1483       return None;
1484     }
1485 
1486     /// Helper for reorderOperandVecs.
1487     /// \returns the lane that we should start reordering from. This is the one
1488     /// which has the least number of operands that can freely move about or
1489     /// less profitable because it already has the most optimal set of operands.
1490     unsigned getBestLaneToStartReordering() const {
1491       unsigned Min = UINT_MAX;
1492       unsigned SameOpNumber = 0;
1493       // std::pair<unsigned, unsigned> is used to implement a simple voting
1494       // algorithm and choose the lane with the least number of operands that
1495       // can freely move about or less profitable because it already has the
1496       // most optimal set of operands. The first unsigned is a counter for
1497       // voting, the second unsigned is the counter of lanes with instructions
1498       // with same/alternate opcodes and same parent basic block.
1499       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1500       // Try to be closer to the original results, if we have multiple lanes
1501       // with same cost. If 2 lanes have the same cost, use the one with the
1502       // lowest index.
1503       for (int I = getNumLanes(); I > 0; --I) {
1504         unsigned Lane = I - 1;
1505         OperandsOrderData NumFreeOpsHash =
1506             getMaxNumOperandsThatCanBeReordered(Lane);
1507         // Compare the number of operands that can move and choose the one with
1508         // the least number.
1509         if (NumFreeOpsHash.NumOfAPOs < Min) {
1510           Min = NumFreeOpsHash.NumOfAPOs;
1511           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1512           HashMap.clear();
1513           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1514         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1515                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1516           // Select the most optimal lane in terms of number of operands that
1517           // should be moved around.
1518           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1519           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1520         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1521                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1522           auto It = HashMap.find(NumFreeOpsHash.Hash);
1523           if (It == HashMap.end())
1524             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525           else
1526             ++It->second.first;
1527         }
1528       }
1529       // Select the lane with the minimum counter.
1530       unsigned BestLane = 0;
1531       unsigned CntMin = UINT_MAX;
1532       for (const auto &Data : reverse(HashMap)) {
1533         if (Data.second.first < CntMin) {
1534           CntMin = Data.second.first;
1535           BestLane = Data.second.second;
1536         }
1537       }
1538       return BestLane;
1539     }
1540 
1541     /// Data structure that helps to reorder operands.
1542     struct OperandsOrderData {
1543       /// The best number of operands with the same APOs, which can be
1544       /// reordered.
1545       unsigned NumOfAPOs = UINT_MAX;
1546       /// Number of operands with the same/alternate instruction opcode and
1547       /// parent.
1548       unsigned NumOpsWithSameOpcodeParent = 0;
1549       /// Hash for the actual operands ordering.
1550       /// Used to count operands, actually their position id and opcode
1551       /// value. It is used in the voting mechanism to find the lane with the
1552       /// least number of operands that can freely move about or less profitable
1553       /// because it already has the most optimal set of operands. Can be
1554       /// replaced with SmallVector<unsigned> instead but hash code is faster
1555       /// and requires less memory.
1556       unsigned Hash = 0;
1557     };
1558     /// \returns the maximum number of operands that are allowed to be reordered
1559     /// for \p Lane and the number of compatible instructions(with the same
1560     /// parent/opcode). This is used as a heuristic for selecting the first lane
1561     /// to start operand reordering.
1562     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1563       unsigned CntTrue = 0;
1564       unsigned NumOperands = getNumOperands();
1565       // Operands with the same APO can be reordered. We therefore need to count
1566       // how many of them we have for each APO, like this: Cnt[APO] = x.
1567       // Since we only have two APOs, namely true and false, we can avoid using
1568       // a map. Instead we can simply count the number of operands that
1569       // correspond to one of them (in this case the 'true' APO), and calculate
1570       // the other by subtracting it from the total number of operands.
1571       // Operands with the same instruction opcode and parent are more
1572       // profitable since we don't need to move them in many cases, with a high
1573       // probability such lane already can be vectorized effectively.
1574       bool AllUndefs = true;
1575       unsigned NumOpsWithSameOpcodeParent = 0;
1576       Instruction *OpcodeI = nullptr;
1577       BasicBlock *Parent = nullptr;
1578       unsigned Hash = 0;
1579       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1580         const OperandData &OpData = getData(OpIdx, Lane);
1581         if (OpData.APO)
1582           ++CntTrue;
1583         // Use Boyer-Moore majority voting for finding the majority opcode and
1584         // the number of times it occurs.
1585         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1586           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1587               I->getParent() != Parent) {
1588             if (NumOpsWithSameOpcodeParent == 0) {
1589               NumOpsWithSameOpcodeParent = 1;
1590               OpcodeI = I;
1591               Parent = I->getParent();
1592             } else {
1593               --NumOpsWithSameOpcodeParent;
1594             }
1595           } else {
1596             ++NumOpsWithSameOpcodeParent;
1597           }
1598         }
1599         Hash = hash_combine(
1600             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1601         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1602       }
1603       if (AllUndefs)
1604         return {};
1605       OperandsOrderData Data;
1606       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1607       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1608       Data.Hash = Hash;
1609       return Data;
1610     }
1611 
1612     /// Go through the instructions in VL and append their operands.
1613     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1614       assert(!VL.empty() && "Bad VL");
1615       assert((empty() || VL.size() == getNumLanes()) &&
1616              "Expected same number of lanes");
1617       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1618       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1619       OpsVec.resize(NumOperands);
1620       unsigned NumLanes = VL.size();
1621       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1622         OpsVec[OpIdx].resize(NumLanes);
1623         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1624           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1625           // Our tree has just 3 nodes: the root and two operands.
1626           // It is therefore trivial to get the APO. We only need to check the
1627           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1628           // RHS operand. The LHS operand of both add and sub is never attached
1629           // to an inversese operation in the linearized form, therefore its APO
1630           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1631 
1632           // Since operand reordering is performed on groups of commutative
1633           // operations or alternating sequences (e.g., +, -), we can safely
1634           // tell the inverse operations by checking commutativity.
1635           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1636           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1637           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1638                                  APO, false};
1639         }
1640       }
1641     }
1642 
1643     /// \returns the number of operands.
1644     unsigned getNumOperands() const { return OpsVec.size(); }
1645 
1646     /// \returns the number of lanes.
1647     unsigned getNumLanes() const { return OpsVec[0].size(); }
1648 
1649     /// \returns the operand value at \p OpIdx and \p Lane.
1650     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1651       return getData(OpIdx, Lane).V;
1652     }
1653 
1654     /// \returns true if the data structure is empty.
1655     bool empty() const { return OpsVec.empty(); }
1656 
1657     /// Clears the data.
1658     void clear() { OpsVec.clear(); }
1659 
1660     /// \Returns true if there are enough operands identical to \p Op to fill
1661     /// the whole vector.
1662     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1663     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1664       bool OpAPO = getData(OpIdx, Lane).APO;
1665       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1666         if (Ln == Lane)
1667           continue;
1668         // This is set to true if we found a candidate for broadcast at Lane.
1669         bool FoundCandidate = false;
1670         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1671           OperandData &Data = getData(OpI, Ln);
1672           if (Data.APO != OpAPO || Data.IsUsed)
1673             continue;
1674           if (Data.V == Op) {
1675             FoundCandidate = true;
1676             Data.IsUsed = true;
1677             break;
1678           }
1679         }
1680         if (!FoundCandidate)
1681           return false;
1682       }
1683       return true;
1684     }
1685 
1686   public:
1687     /// Initialize with all the operands of the instruction vector \p RootVL.
1688     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1689                ScalarEvolution &SE, const BoUpSLP &R)
1690         : DL(DL), SE(SE), R(R) {
1691       // Append all the operands of RootVL.
1692       appendOperandsOfVL(RootVL);
1693     }
1694 
1695     /// \Returns a value vector with the operands across all lanes for the
1696     /// opearnd at \p OpIdx.
1697     ValueList getVL(unsigned OpIdx) const {
1698       ValueList OpVL(OpsVec[OpIdx].size());
1699       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1700              "Expected same num of lanes across all operands");
1701       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1702         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1703       return OpVL;
1704     }
1705 
1706     // Performs operand reordering for 2 or more operands.
1707     // The original operands are in OrigOps[OpIdx][Lane].
1708     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1709     void reorder() {
1710       unsigned NumOperands = getNumOperands();
1711       unsigned NumLanes = getNumLanes();
1712       // Each operand has its own mode. We are using this mode to help us select
1713       // the instructions for each lane, so that they match best with the ones
1714       // we have selected so far.
1715       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1716 
1717       // This is a greedy single-pass algorithm. We are going over each lane
1718       // once and deciding on the best order right away with no back-tracking.
1719       // However, in order to increase its effectiveness, we start with the lane
1720       // that has operands that can move the least. For example, given the
1721       // following lanes:
1722       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1723       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1724       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1725       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1726       // we will start at Lane 1, since the operands of the subtraction cannot
1727       // be reordered. Then we will visit the rest of the lanes in a circular
1728       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1729 
1730       // Find the first lane that we will start our search from.
1731       unsigned FirstLane = getBestLaneToStartReordering();
1732 
1733       // Initialize the modes.
1734       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1735         Value *OpLane0 = getValue(OpIdx, FirstLane);
1736         // Keep track if we have instructions with all the same opcode on one
1737         // side.
1738         if (isa<LoadInst>(OpLane0))
1739           ReorderingModes[OpIdx] = ReorderingMode::Load;
1740         else if (isa<Instruction>(OpLane0)) {
1741           // Check if OpLane0 should be broadcast.
1742           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1743             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1744           else
1745             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1746         }
1747         else if (isa<Constant>(OpLane0))
1748           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1749         else if (isa<Argument>(OpLane0))
1750           // Our best hope is a Splat. It may save some cost in some cases.
1751           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1752         else
1753           // NOTE: This should be unreachable.
1754           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1755       }
1756 
1757       // Check that we don't have same operands. No need to reorder if operands
1758       // are just perfect diamond or shuffled diamond match. Do not do it only
1759       // for possible broadcasts or non-power of 2 number of scalars (just for
1760       // now).
1761       auto &&SkipReordering = [this]() {
1762         SmallPtrSet<Value *, 4> UniqueValues;
1763         ArrayRef<OperandData> Op0 = OpsVec.front();
1764         for (const OperandData &Data : Op0)
1765           UniqueValues.insert(Data.V);
1766         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1767           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1768                 return !UniqueValues.contains(Data.V);
1769               }))
1770             return false;
1771         }
1772         // TODO: Check if we can remove a check for non-power-2 number of
1773         // scalars after full support of non-power-2 vectorization.
1774         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1775       };
1776 
1777       // If the initial strategy fails for any of the operand indexes, then we
1778       // perform reordering again in a second pass. This helps avoid assigning
1779       // high priority to the failed strategy, and should improve reordering for
1780       // the non-failed operand indexes.
1781       for (int Pass = 0; Pass != 2; ++Pass) {
1782         // Check if no need to reorder operands since they're are perfect or
1783         // shuffled diamond match.
1784         // Need to to do it to avoid extra external use cost counting for
1785         // shuffled matches, which may cause regressions.
1786         if (SkipReordering())
1787           break;
1788         // Skip the second pass if the first pass did not fail.
1789         bool StrategyFailed = false;
1790         // Mark all operand data as free to use.
1791         clearUsed();
1792         // We keep the original operand order for the FirstLane, so reorder the
1793         // rest of the lanes. We are visiting the nodes in a circular fashion,
1794         // using FirstLane as the center point and increasing the radius
1795         // distance.
1796         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1797         for (unsigned I = 0; I < NumOperands; ++I)
1798           MainAltOps[I].push_back(getData(I, FirstLane).V);
1799 
1800         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1801           // Visit the lane on the right and then the lane on the left.
1802           for (int Direction : {+1, -1}) {
1803             int Lane = FirstLane + Direction * Distance;
1804             if (Lane < 0 || Lane >= (int)NumLanes)
1805               continue;
1806             int LastLane = Lane - Direction;
1807             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1808                    "Out of bounds");
1809             // Look for a good match for each operand.
1810             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1811               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1812               Optional<unsigned> BestIdx = getBestOperand(
1813                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1814               // By not selecting a value, we allow the operands that follow to
1815               // select a better matching value. We will get a non-null value in
1816               // the next run of getBestOperand().
1817               if (BestIdx) {
1818                 // Swap the current operand with the one returned by
1819                 // getBestOperand().
1820                 swap(OpIdx, BestIdx.getValue(), Lane);
1821               } else {
1822                 // We failed to find a best operand, set mode to 'Failed'.
1823                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1824                 // Enable the second pass.
1825                 StrategyFailed = true;
1826               }
1827               // Try to get the alternate opcode and follow it during analysis.
1828               if (MainAltOps[OpIdx].size() != 2) {
1829                 OperandData &AltOp = getData(OpIdx, Lane);
1830                 InstructionsState OpS =
1831                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1832                 if (OpS.getOpcode() && OpS.isAltShuffle())
1833                   MainAltOps[OpIdx].push_back(AltOp.V);
1834               }
1835             }
1836           }
1837         }
1838         // Skip second pass if the strategy did not fail.
1839         if (!StrategyFailed)
1840           break;
1841       }
1842     }
1843 
1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1845     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1846       switch (RMode) {
1847       case ReorderingMode::Load:
1848         return "Load";
1849       case ReorderingMode::Opcode:
1850         return "Opcode";
1851       case ReorderingMode::Constant:
1852         return "Constant";
1853       case ReorderingMode::Splat:
1854         return "Splat";
1855       case ReorderingMode::Failed:
1856         return "Failed";
1857       }
1858       llvm_unreachable("Unimplemented Reordering Type");
1859     }
1860 
1861     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1862                                                    raw_ostream &OS) {
1863       return OS << getModeStr(RMode);
1864     }
1865 
1866     /// Debug print.
1867     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1868       printMode(RMode, dbgs());
1869     }
1870 
1871     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1872       return printMode(RMode, OS);
1873     }
1874 
1875     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1876       const unsigned Indent = 2;
1877       unsigned Cnt = 0;
1878       for (const OperandDataVec &OpDataVec : OpsVec) {
1879         OS << "Operand " << Cnt++ << "\n";
1880         for (const OperandData &OpData : OpDataVec) {
1881           OS.indent(Indent) << "{";
1882           if (Value *V = OpData.V)
1883             OS << *V;
1884           else
1885             OS << "null";
1886           OS << ", APO:" << OpData.APO << "}\n";
1887         }
1888         OS << "\n";
1889       }
1890       return OS;
1891     }
1892 
1893     /// Debug print.
1894     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1895 #endif
1896   };
1897 
1898   /// Checks if the instruction is marked for deletion.
1899   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1900 
1901   /// Marks values operands for later deletion by replacing them with Undefs.
1902   void eraseInstructions(ArrayRef<Value *> AV);
1903 
1904   ~BoUpSLP();
1905 
1906 private:
1907   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1908   /// reordering (i.e. the operands can be reordered because they have only one
1909   /// user and reordarable).
1910   /// \param NonVectorized List of all gather nodes that require reordering
1911   /// (e.g., gather of extractlements or partially vectorizable loads).
1912   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1913   /// reordering, subset of \p NonVectorized.
1914   bool
1915   canReorderOperands(TreeEntry *UserTE,
1916                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1917                      ArrayRef<TreeEntry *> ReorderableGathers,
1918                      SmallVectorImpl<TreeEntry *> &GatherOps);
1919 
1920   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1921   /// if any. If it is not vectorized (gather node), returns nullptr.
1922   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1923     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1924     TreeEntry *TE = nullptr;
1925     const auto *It = find_if(VL, [this, &TE](Value *V) {
1926       TE = getTreeEntry(V);
1927       return TE;
1928     });
1929     if (It != VL.end() && TE->isSame(VL))
1930       return TE;
1931     return nullptr;
1932   }
1933 
1934   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1935   /// if any. If it is not vectorized (gather node), returns nullptr.
1936   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1937                                         unsigned OpIdx) const {
1938     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1939         const_cast<TreeEntry *>(UserTE), OpIdx);
1940   }
1941 
1942   /// Checks if all users of \p I are the part of the vectorization tree.
1943   bool areAllUsersVectorized(Instruction *I,
1944                              ArrayRef<Value *> VectorizedVals) const;
1945 
1946   /// \returns the cost of the vectorizable entry.
1947   InstructionCost getEntryCost(const TreeEntry *E,
1948                                ArrayRef<Value *> VectorizedVals);
1949 
1950   /// This is the recursive part of buildTree.
1951   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1952                      const EdgeInfo &EI);
1953 
1954   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1955   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1956   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1957   /// returns false, setting \p CurrentOrder to either an empty vector or a
1958   /// non-identity permutation that allows to reuse extract instructions.
1959   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1960                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1961 
1962   /// Vectorize a single entry in the tree.
1963   Value *vectorizeTree(TreeEntry *E);
1964 
1965   /// Vectorize a single entry in the tree, starting in \p VL.
1966   Value *vectorizeTree(ArrayRef<Value *> VL);
1967 
1968   /// \returns the scalarization cost for this type. Scalarization in this
1969   /// context means the creation of vectors from a group of scalars. If \p
1970   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1971   /// vector elements.
1972   InstructionCost getGatherCost(FixedVectorType *Ty,
1973                                 const APInt &ShuffledIndices,
1974                                 bool NeedToShuffle) const;
1975 
1976   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1977   /// tree entries.
1978   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1979   /// previous tree entries. \p Mask is filled with the shuffle mask.
1980   Optional<TargetTransformInfo::ShuffleKind>
1981   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1982                         SmallVectorImpl<const TreeEntry *> &Entries);
1983 
1984   /// \returns the scalarization cost for this list of values. Assuming that
1985   /// this subtree gets vectorized, we may need to extract the values from the
1986   /// roots. This method calculates the cost of extracting the values.
1987   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1988 
1989   /// Set the Builder insert point to one after the last instruction in
1990   /// the bundle
1991   void setInsertPointAfterBundle(const TreeEntry *E);
1992 
1993   /// \returns a vector from a collection of scalars in \p VL.
1994   Value *gather(ArrayRef<Value *> VL);
1995 
1996   /// \returns whether the VectorizableTree is fully vectorizable and will
1997   /// be beneficial even the tree height is tiny.
1998   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1999 
2000   /// Reorder commutative or alt operands to get better probability of
2001   /// generating vectorized code.
2002   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2003                                              SmallVectorImpl<Value *> &Left,
2004                                              SmallVectorImpl<Value *> &Right,
2005                                              const DataLayout &DL,
2006                                              ScalarEvolution &SE,
2007                                              const BoUpSLP &R);
2008   struct TreeEntry {
2009     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2010     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2011 
2012     /// \returns true if the scalars in VL are equal to this entry.
2013     bool isSame(ArrayRef<Value *> VL) const {
2014       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2015         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2016           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2017         return VL.size() == Mask.size() &&
2018                std::equal(VL.begin(), VL.end(), Mask.begin(),
2019                           [Scalars](Value *V, int Idx) {
2020                             return (isa<UndefValue>(V) &&
2021                                     Idx == UndefMaskElem) ||
2022                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2023                           });
2024       };
2025       if (!ReorderIndices.empty()) {
2026         // TODO: implement matching if the nodes are just reordered, still can
2027         // treat the vector as the same if the list of scalars matches VL
2028         // directly, without reordering.
2029         SmallVector<int> Mask;
2030         inversePermutation(ReorderIndices, Mask);
2031         if (VL.size() == Scalars.size())
2032           return IsSame(Scalars, Mask);
2033         if (VL.size() == ReuseShuffleIndices.size()) {
2034           ::addMask(Mask, ReuseShuffleIndices);
2035           return IsSame(Scalars, Mask);
2036         }
2037         return false;
2038       }
2039       return IsSame(Scalars, ReuseShuffleIndices);
2040     }
2041 
2042     /// \returns true if current entry has same operands as \p TE.
2043     bool hasEqualOperands(const TreeEntry &TE) const {
2044       if (TE.getNumOperands() != getNumOperands())
2045         return false;
2046       SmallBitVector Used(getNumOperands());
2047       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2048         unsigned PrevCount = Used.count();
2049         for (unsigned K = 0; K < E; ++K) {
2050           if (Used.test(K))
2051             continue;
2052           if (getOperand(K) == TE.getOperand(I)) {
2053             Used.set(K);
2054             break;
2055           }
2056         }
2057         // Check if we actually found the matching operand.
2058         if (PrevCount == Used.count())
2059           return false;
2060       }
2061       return true;
2062     }
2063 
2064     /// \return Final vectorization factor for the node. Defined by the total
2065     /// number of vectorized scalars, including those, used several times in the
2066     /// entry and counted in the \a ReuseShuffleIndices, if any.
2067     unsigned getVectorFactor() const {
2068       if (!ReuseShuffleIndices.empty())
2069         return ReuseShuffleIndices.size();
2070       return Scalars.size();
2071     };
2072 
2073     /// A vector of scalars.
2074     ValueList Scalars;
2075 
2076     /// The Scalars are vectorized into this value. It is initialized to Null.
2077     Value *VectorizedValue = nullptr;
2078 
2079     /// Do we need to gather this sequence or vectorize it
2080     /// (either with vector instruction or with scatter/gather
2081     /// intrinsics for store/load)?
2082     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2083     EntryState State;
2084 
2085     /// Does this sequence require some shuffling?
2086     SmallVector<int, 4> ReuseShuffleIndices;
2087 
2088     /// Does this entry require reordering?
2089     SmallVector<unsigned, 4> ReorderIndices;
2090 
2091     /// Points back to the VectorizableTree.
2092     ///
2093     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2094     /// to be a pointer and needs to be able to initialize the child iterator.
2095     /// Thus we need a reference back to the container to translate the indices
2096     /// to entries.
2097     VecTreeTy &Container;
2098 
2099     /// The TreeEntry index containing the user of this entry.  We can actually
2100     /// have multiple users so the data structure is not truly a tree.
2101     SmallVector<EdgeInfo, 1> UserTreeIndices;
2102 
2103     /// The index of this treeEntry in VectorizableTree.
2104     int Idx = -1;
2105 
2106   private:
2107     /// The operands of each instruction in each lane Operands[op_index][lane].
2108     /// Note: This helps avoid the replication of the code that performs the
2109     /// reordering of operands during buildTree_rec() and vectorizeTree().
2110     SmallVector<ValueList, 2> Operands;
2111 
2112     /// The main/alternate instruction.
2113     Instruction *MainOp = nullptr;
2114     Instruction *AltOp = nullptr;
2115 
2116   public:
2117     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2118     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2119       if (Operands.size() < OpIdx + 1)
2120         Operands.resize(OpIdx + 1);
2121       assert(Operands[OpIdx].empty() && "Already resized?");
2122       assert(OpVL.size() <= Scalars.size() &&
2123              "Number of operands is greater than the number of scalars.");
2124       Operands[OpIdx].resize(OpVL.size());
2125       copy(OpVL, Operands[OpIdx].begin());
2126     }
2127 
2128     /// Set the operands of this bundle in their original order.
2129     void setOperandsInOrder() {
2130       assert(Operands.empty() && "Already initialized?");
2131       auto *I0 = cast<Instruction>(Scalars[0]);
2132       Operands.resize(I0->getNumOperands());
2133       unsigned NumLanes = Scalars.size();
2134       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2135            OpIdx != NumOperands; ++OpIdx) {
2136         Operands[OpIdx].resize(NumLanes);
2137         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2138           auto *I = cast<Instruction>(Scalars[Lane]);
2139           assert(I->getNumOperands() == NumOperands &&
2140                  "Expected same number of operands");
2141           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2142         }
2143       }
2144     }
2145 
2146     /// Reorders operands of the node to the given mask \p Mask.
2147     void reorderOperands(ArrayRef<int> Mask) {
2148       for (ValueList &Operand : Operands)
2149         reorderScalars(Operand, Mask);
2150     }
2151 
2152     /// \returns the \p OpIdx operand of this TreeEntry.
2153     ValueList &getOperand(unsigned OpIdx) {
2154       assert(OpIdx < Operands.size() && "Off bounds");
2155       return Operands[OpIdx];
2156     }
2157 
2158     /// \returns the \p OpIdx operand of this TreeEntry.
2159     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2160       assert(OpIdx < Operands.size() && "Off bounds");
2161       return Operands[OpIdx];
2162     }
2163 
2164     /// \returns the number of operands.
2165     unsigned getNumOperands() const { return Operands.size(); }
2166 
2167     /// \return the single \p OpIdx operand.
2168     Value *getSingleOperand(unsigned OpIdx) const {
2169       assert(OpIdx < Operands.size() && "Off bounds");
2170       assert(!Operands[OpIdx].empty() && "No operand available");
2171       return Operands[OpIdx][0];
2172     }
2173 
2174     /// Some of the instructions in the list have alternate opcodes.
2175     bool isAltShuffle() const { return MainOp != AltOp; }
2176 
2177     bool isOpcodeOrAlt(Instruction *I) const {
2178       unsigned CheckedOpcode = I->getOpcode();
2179       return (getOpcode() == CheckedOpcode ||
2180               getAltOpcode() == CheckedOpcode);
2181     }
2182 
2183     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2184     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2185     /// \p OpValue.
2186     Value *isOneOf(Value *Op) const {
2187       auto *I = dyn_cast<Instruction>(Op);
2188       if (I && isOpcodeOrAlt(I))
2189         return Op;
2190       return MainOp;
2191     }
2192 
2193     void setOperations(const InstructionsState &S) {
2194       MainOp = S.MainOp;
2195       AltOp = S.AltOp;
2196     }
2197 
2198     Instruction *getMainOp() const {
2199       return MainOp;
2200     }
2201 
2202     Instruction *getAltOp() const {
2203       return AltOp;
2204     }
2205 
2206     /// The main/alternate opcodes for the list of instructions.
2207     unsigned getOpcode() const {
2208       return MainOp ? MainOp->getOpcode() : 0;
2209     }
2210 
2211     unsigned getAltOpcode() const {
2212       return AltOp ? AltOp->getOpcode() : 0;
2213     }
2214 
2215     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2216     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2217     int findLaneForValue(Value *V) const {
2218       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2219       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2220       if (!ReorderIndices.empty())
2221         FoundLane = ReorderIndices[FoundLane];
2222       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2223       if (!ReuseShuffleIndices.empty()) {
2224         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2225                                   find(ReuseShuffleIndices, FoundLane));
2226       }
2227       return FoundLane;
2228     }
2229 
2230 #ifndef NDEBUG
2231     /// Debug printer.
2232     LLVM_DUMP_METHOD void dump() const {
2233       dbgs() << Idx << ".\n";
2234       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2235         dbgs() << "Operand " << OpI << ":\n";
2236         for (const Value *V : Operands[OpI])
2237           dbgs().indent(2) << *V << "\n";
2238       }
2239       dbgs() << "Scalars: \n";
2240       for (Value *V : Scalars)
2241         dbgs().indent(2) << *V << "\n";
2242       dbgs() << "State: ";
2243       switch (State) {
2244       case Vectorize:
2245         dbgs() << "Vectorize\n";
2246         break;
2247       case ScatterVectorize:
2248         dbgs() << "ScatterVectorize\n";
2249         break;
2250       case NeedToGather:
2251         dbgs() << "NeedToGather\n";
2252         break;
2253       }
2254       dbgs() << "MainOp: ";
2255       if (MainOp)
2256         dbgs() << *MainOp << "\n";
2257       else
2258         dbgs() << "NULL\n";
2259       dbgs() << "AltOp: ";
2260       if (AltOp)
2261         dbgs() << *AltOp << "\n";
2262       else
2263         dbgs() << "NULL\n";
2264       dbgs() << "VectorizedValue: ";
2265       if (VectorizedValue)
2266         dbgs() << *VectorizedValue << "\n";
2267       else
2268         dbgs() << "NULL\n";
2269       dbgs() << "ReuseShuffleIndices: ";
2270       if (ReuseShuffleIndices.empty())
2271         dbgs() << "Empty";
2272       else
2273         for (int ReuseIdx : ReuseShuffleIndices)
2274           dbgs() << ReuseIdx << ", ";
2275       dbgs() << "\n";
2276       dbgs() << "ReorderIndices: ";
2277       for (unsigned ReorderIdx : ReorderIndices)
2278         dbgs() << ReorderIdx << ", ";
2279       dbgs() << "\n";
2280       dbgs() << "UserTreeIndices: ";
2281       for (const auto &EInfo : UserTreeIndices)
2282         dbgs() << EInfo << ", ";
2283       dbgs() << "\n";
2284     }
2285 #endif
2286   };
2287 
2288 #ifndef NDEBUG
2289   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2290                      InstructionCost VecCost,
2291                      InstructionCost ScalarCost) const {
2292     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2293     dbgs() << "SLP: Costs:\n";
2294     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2295     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2296     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2297     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2298                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2299   }
2300 #endif
2301 
2302   /// Create a new VectorizableTree entry.
2303   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2304                           const InstructionsState &S,
2305                           const EdgeInfo &UserTreeIdx,
2306                           ArrayRef<int> ReuseShuffleIndices = None,
2307                           ArrayRef<unsigned> ReorderIndices = None) {
2308     TreeEntry::EntryState EntryState =
2309         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2310     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2311                         ReuseShuffleIndices, ReorderIndices);
2312   }
2313 
2314   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2315                           TreeEntry::EntryState EntryState,
2316                           Optional<ScheduleData *> Bundle,
2317                           const InstructionsState &S,
2318                           const EdgeInfo &UserTreeIdx,
2319                           ArrayRef<int> ReuseShuffleIndices = None,
2320                           ArrayRef<unsigned> ReorderIndices = None) {
2321     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2322             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2323            "Need to vectorize gather entry?");
2324     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2325     TreeEntry *Last = VectorizableTree.back().get();
2326     Last->Idx = VectorizableTree.size() - 1;
2327     Last->State = EntryState;
2328     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2329                                      ReuseShuffleIndices.end());
2330     if (ReorderIndices.empty()) {
2331       Last->Scalars.assign(VL.begin(), VL.end());
2332       Last->setOperations(S);
2333     } else {
2334       // Reorder scalars and build final mask.
2335       Last->Scalars.assign(VL.size(), nullptr);
2336       transform(ReorderIndices, Last->Scalars.begin(),
2337                 [VL](unsigned Idx) -> Value * {
2338                   if (Idx >= VL.size())
2339                     return UndefValue::get(VL.front()->getType());
2340                   return VL[Idx];
2341                 });
2342       InstructionsState S = getSameOpcode(Last->Scalars);
2343       Last->setOperations(S);
2344       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2345     }
2346     if (Last->State != TreeEntry::NeedToGather) {
2347       for (Value *V : VL) {
2348         assert(!getTreeEntry(V) && "Scalar already in tree!");
2349         ScalarToTreeEntry[V] = Last;
2350       }
2351       // Update the scheduler bundle to point to this TreeEntry.
2352       unsigned Lane = 0;
2353       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2354            BundleMember = BundleMember->NextInBundle) {
2355         BundleMember->TE = Last;
2356         BundleMember->Lane = Lane;
2357         ++Lane;
2358       }
2359       assert((!Bundle.getValue() || Lane == VL.size()) &&
2360              "Bundle and VL out of sync");
2361     } else {
2362       MustGather.insert(VL.begin(), VL.end());
2363     }
2364 
2365     if (UserTreeIdx.UserTE)
2366       Last->UserTreeIndices.push_back(UserTreeIdx);
2367 
2368     return Last;
2369   }
2370 
2371   /// -- Vectorization State --
2372   /// Holds all of the tree entries.
2373   TreeEntry::VecTreeTy VectorizableTree;
2374 
2375 #ifndef NDEBUG
2376   /// Debug printer.
2377   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2378     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2379       VectorizableTree[Id]->dump();
2380       dbgs() << "\n";
2381     }
2382   }
2383 #endif
2384 
2385   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2386 
2387   const TreeEntry *getTreeEntry(Value *V) const {
2388     return ScalarToTreeEntry.lookup(V);
2389   }
2390 
2391   /// Maps a specific scalar to its tree entry.
2392   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2393 
2394   /// Maps a value to the proposed vectorizable size.
2395   SmallDenseMap<Value *, unsigned> InstrElementSize;
2396 
2397   /// A list of scalars that we found that we need to keep as scalars.
2398   ValueSet MustGather;
2399 
2400   /// This POD struct describes one external user in the vectorized tree.
2401   struct ExternalUser {
2402     ExternalUser(Value *S, llvm::User *U, int L)
2403         : Scalar(S), User(U), Lane(L) {}
2404 
2405     // Which scalar in our function.
2406     Value *Scalar;
2407 
2408     // Which user that uses the scalar.
2409     llvm::User *User;
2410 
2411     // Which lane does the scalar belong to.
2412     int Lane;
2413   };
2414   using UserList = SmallVector<ExternalUser, 16>;
2415 
2416   /// Checks if two instructions may access the same memory.
2417   ///
2418   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2419   /// is invariant in the calling loop.
2420   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2421                  Instruction *Inst2) {
2422     // First check if the result is already in the cache.
2423     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2424     Optional<bool> &result = AliasCache[key];
2425     if (result.hasValue()) {
2426       return result.getValue();
2427     }
2428     bool aliased = true;
2429     if (Loc1.Ptr && isSimple(Inst1))
2430       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2431     // Store the result in the cache.
2432     result = aliased;
2433     return aliased;
2434   }
2435 
2436   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2437 
2438   /// Cache for alias results.
2439   /// TODO: consider moving this to the AliasAnalysis itself.
2440   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2441 
2442   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2443   // globally through SLP because we don't perform any action which
2444   // invalidates capture results.
2445   BatchAAResults BatchAA;
2446 
2447   /// Removes an instruction from its block and eventually deletes it.
2448   /// It's like Instruction::eraseFromParent() except that the actual deletion
2449   /// is delayed until BoUpSLP is destructed.
2450   /// This is required to ensure that there are no incorrect collisions in the
2451   /// AliasCache, which can happen if a new instruction is allocated at the
2452   /// same address as a previously deleted instruction.
2453   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2454     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2455     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2456   }
2457 
2458   /// Temporary store for deleted instructions. Instructions will be deleted
2459   /// eventually when the BoUpSLP is destructed.
2460   DenseMap<Instruction *, bool> DeletedInstructions;
2461 
2462   /// A list of values that need to extracted out of the tree.
2463   /// This list holds pairs of (Internal Scalar : External User). External User
2464   /// can be nullptr, it means that this Internal Scalar will be used later,
2465   /// after vectorization.
2466   UserList ExternalUses;
2467 
2468   /// Values used only by @llvm.assume calls.
2469   SmallPtrSet<const Value *, 32> EphValues;
2470 
2471   /// Holds all of the instructions that we gathered.
2472   SetVector<Instruction *> GatherShuffleSeq;
2473 
2474   /// A list of blocks that we are going to CSE.
2475   SetVector<BasicBlock *> CSEBlocks;
2476 
2477   /// Contains all scheduling relevant data for an instruction.
2478   /// A ScheduleData either represents a single instruction or a member of an
2479   /// instruction bundle (= a group of instructions which is combined into a
2480   /// vector instruction).
2481   struct ScheduleData {
2482     // The initial value for the dependency counters. It means that the
2483     // dependencies are not calculated yet.
2484     enum { InvalidDeps = -1 };
2485 
2486     ScheduleData() = default;
2487 
2488     void init(int BlockSchedulingRegionID, Value *OpVal) {
2489       FirstInBundle = this;
2490       NextInBundle = nullptr;
2491       NextLoadStore = nullptr;
2492       IsScheduled = false;
2493       SchedulingRegionID = BlockSchedulingRegionID;
2494       clearDependencies();
2495       OpValue = OpVal;
2496       TE = nullptr;
2497       Lane = -1;
2498     }
2499 
2500     /// Verify basic self consistency properties
2501     void verify() {
2502       if (hasValidDependencies()) {
2503         assert(UnscheduledDeps <= Dependencies && "invariant");
2504       } else {
2505         assert(UnscheduledDeps == Dependencies && "invariant");
2506       }
2507 
2508       if (IsScheduled) {
2509         assert(isSchedulingEntity() &&
2510                 "unexpected scheduled state");
2511         for (const ScheduleData *BundleMember = this; BundleMember;
2512              BundleMember = BundleMember->NextInBundle) {
2513           assert(BundleMember->hasValidDependencies() &&
2514                  BundleMember->UnscheduledDeps == 0 &&
2515                  "unexpected scheduled state");
2516           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2517                  "only bundle is marked scheduled");
2518         }
2519       }
2520 
2521       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2522              "all bundle members must be in same basic block");
2523     }
2524 
2525     /// Returns true if the dependency information has been calculated.
2526     /// Note that depenendency validity can vary between instructions within
2527     /// a single bundle.
2528     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2529 
2530     /// Returns true for single instructions and for bundle representatives
2531     /// (= the head of a bundle).
2532     bool isSchedulingEntity() const { return FirstInBundle == this; }
2533 
2534     /// Returns true if it represents an instruction bundle and not only a
2535     /// single instruction.
2536     bool isPartOfBundle() const {
2537       return NextInBundle != nullptr || FirstInBundle != this;
2538     }
2539 
2540     /// Returns true if it is ready for scheduling, i.e. it has no more
2541     /// unscheduled depending instructions/bundles.
2542     bool isReady() const {
2543       assert(isSchedulingEntity() &&
2544              "can't consider non-scheduling entity for ready list");
2545       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2546     }
2547 
2548     /// Modifies the number of unscheduled dependencies for this instruction,
2549     /// and returns the number of remaining dependencies for the containing
2550     /// bundle.
2551     int incrementUnscheduledDeps(int Incr) {
2552       assert(hasValidDependencies() &&
2553              "increment of unscheduled deps would be meaningless");
2554       UnscheduledDeps += Incr;
2555       return FirstInBundle->unscheduledDepsInBundle();
2556     }
2557 
2558     /// Sets the number of unscheduled dependencies to the number of
2559     /// dependencies.
2560     void resetUnscheduledDeps() {
2561       UnscheduledDeps = Dependencies;
2562     }
2563 
2564     /// Clears all dependency information.
2565     void clearDependencies() {
2566       Dependencies = InvalidDeps;
2567       resetUnscheduledDeps();
2568       MemoryDependencies.clear();
2569     }
2570 
2571     int unscheduledDepsInBundle() const {
2572       assert(isSchedulingEntity() && "only meaningful on the bundle");
2573       int Sum = 0;
2574       for (const ScheduleData *BundleMember = this; BundleMember;
2575            BundleMember = BundleMember->NextInBundle) {
2576         if (BundleMember->UnscheduledDeps == InvalidDeps)
2577           return InvalidDeps;
2578         Sum += BundleMember->UnscheduledDeps;
2579       }
2580       return Sum;
2581     }
2582 
2583     void dump(raw_ostream &os) const {
2584       if (!isSchedulingEntity()) {
2585         os << "/ " << *Inst;
2586       } else if (NextInBundle) {
2587         os << '[' << *Inst;
2588         ScheduleData *SD = NextInBundle;
2589         while (SD) {
2590           os << ';' << *SD->Inst;
2591           SD = SD->NextInBundle;
2592         }
2593         os << ']';
2594       } else {
2595         os << *Inst;
2596       }
2597     }
2598 
2599     Instruction *Inst = nullptr;
2600 
2601     /// Opcode of the current instruction in the schedule data.
2602     Value *OpValue = nullptr;
2603 
2604     /// The TreeEntry that this instruction corresponds to.
2605     TreeEntry *TE = nullptr;
2606 
2607     /// Points to the head in an instruction bundle (and always to this for
2608     /// single instructions).
2609     ScheduleData *FirstInBundle = nullptr;
2610 
2611     /// Single linked list of all instructions in a bundle. Null if it is a
2612     /// single instruction.
2613     ScheduleData *NextInBundle = nullptr;
2614 
2615     /// Single linked list of all memory instructions (e.g. load, store, call)
2616     /// in the block - until the end of the scheduling region.
2617     ScheduleData *NextLoadStore = nullptr;
2618 
2619     /// The dependent memory instructions.
2620     /// This list is derived on demand in calculateDependencies().
2621     SmallVector<ScheduleData *, 4> MemoryDependencies;
2622 
2623     /// This ScheduleData is in the current scheduling region if this matches
2624     /// the current SchedulingRegionID of BlockScheduling.
2625     int SchedulingRegionID = 0;
2626 
2627     /// The number of dependencies. Constitutes of the number of users of the
2628     /// instruction plus the number of dependent memory instructions (if any).
2629     /// This value is calculated on demand.
2630     /// If InvalidDeps, the number of dependencies is not calculated yet.
2631     int Dependencies = InvalidDeps;
2632 
2633     /// The number of dependencies minus the number of dependencies of scheduled
2634     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2635     /// for scheduling.
2636     /// Note that this is negative as long as Dependencies is not calculated.
2637     int UnscheduledDeps = InvalidDeps;
2638 
2639     /// The lane of this node in the TreeEntry.
2640     int Lane = -1;
2641 
2642     /// True if this instruction is scheduled (or considered as scheduled in the
2643     /// dry-run).
2644     bool IsScheduled = false;
2645   };
2646 
2647 #ifndef NDEBUG
2648   friend inline raw_ostream &operator<<(raw_ostream &os,
2649                                         const BoUpSLP::ScheduleData &SD) {
2650     SD.dump(os);
2651     return os;
2652   }
2653 #endif
2654 
2655   friend struct GraphTraits<BoUpSLP *>;
2656   friend struct DOTGraphTraits<BoUpSLP *>;
2657 
2658   /// Contains all scheduling data for a basic block.
2659   struct BlockScheduling {
2660     BlockScheduling(BasicBlock *BB)
2661         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2662 
2663     void clear() {
2664       ReadyInsts.clear();
2665       ScheduleStart = nullptr;
2666       ScheduleEnd = nullptr;
2667       FirstLoadStoreInRegion = nullptr;
2668       LastLoadStoreInRegion = nullptr;
2669 
2670       // Reduce the maximum schedule region size by the size of the
2671       // previous scheduling run.
2672       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2673       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2674         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2675       ScheduleRegionSize = 0;
2676 
2677       // Make a new scheduling region, i.e. all existing ScheduleData is not
2678       // in the new region yet.
2679       ++SchedulingRegionID;
2680     }
2681 
2682     ScheduleData *getScheduleData(Instruction *I) {
2683       if (BB != I->getParent())
2684         // Avoid lookup if can't possibly be in map.
2685         return nullptr;
2686       ScheduleData *SD = ScheduleDataMap[I];
2687       if (SD && isInSchedulingRegion(SD))
2688         return SD;
2689       return nullptr;
2690     }
2691 
2692     ScheduleData *getScheduleData(Value *V) {
2693       if (auto *I = dyn_cast<Instruction>(V))
2694         return getScheduleData(I);
2695       return nullptr;
2696     }
2697 
2698     ScheduleData *getScheduleData(Value *V, Value *Key) {
2699       if (V == Key)
2700         return getScheduleData(V);
2701       auto I = ExtraScheduleDataMap.find(V);
2702       if (I != ExtraScheduleDataMap.end()) {
2703         ScheduleData *SD = I->second[Key];
2704         if (SD && isInSchedulingRegion(SD))
2705           return SD;
2706       }
2707       return nullptr;
2708     }
2709 
2710     bool isInSchedulingRegion(ScheduleData *SD) const {
2711       return SD->SchedulingRegionID == SchedulingRegionID;
2712     }
2713 
2714     /// Marks an instruction as scheduled and puts all dependent ready
2715     /// instructions into the ready-list.
2716     template <typename ReadyListType>
2717     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2718       SD->IsScheduled = true;
2719       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2720 
2721       for (ScheduleData *BundleMember = SD; BundleMember;
2722            BundleMember = BundleMember->NextInBundle) {
2723         if (BundleMember->Inst != BundleMember->OpValue)
2724           continue;
2725 
2726         // Handle the def-use chain dependencies.
2727 
2728         // Decrement the unscheduled counter and insert to ready list if ready.
2729         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2730           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2731             if (OpDef && OpDef->hasValidDependencies() &&
2732                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2733               // There are no more unscheduled dependencies after
2734               // decrementing, so we can put the dependent instruction
2735               // into the ready list.
2736               ScheduleData *DepBundle = OpDef->FirstInBundle;
2737               assert(!DepBundle->IsScheduled &&
2738                      "already scheduled bundle gets ready");
2739               ReadyList.insert(DepBundle);
2740               LLVM_DEBUG(dbgs()
2741                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2742             }
2743           });
2744         };
2745 
2746         // If BundleMember is a vector bundle, its operands may have been
2747         // reordered during buildTree(). We therefore need to get its operands
2748         // through the TreeEntry.
2749         if (TreeEntry *TE = BundleMember->TE) {
2750           int Lane = BundleMember->Lane;
2751           assert(Lane >= 0 && "Lane not set");
2752 
2753           // Since vectorization tree is being built recursively this assertion
2754           // ensures that the tree entry has all operands set before reaching
2755           // this code. Couple of exceptions known at the moment are extracts
2756           // where their second (immediate) operand is not added. Since
2757           // immediates do not affect scheduler behavior this is considered
2758           // okay.
2759           auto *In = TE->getMainOp();
2760           assert(In &&
2761                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2762                   In->getNumOperands() == TE->getNumOperands()) &&
2763                  "Missed TreeEntry operands?");
2764           (void)In; // fake use to avoid build failure when assertions disabled
2765 
2766           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2767                OpIdx != NumOperands; ++OpIdx)
2768             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2769               DecrUnsched(I);
2770         } else {
2771           // If BundleMember is a stand-alone instruction, no operand reordering
2772           // has taken place, so we directly access its operands.
2773           for (Use &U : BundleMember->Inst->operands())
2774             if (auto *I = dyn_cast<Instruction>(U.get()))
2775               DecrUnsched(I);
2776         }
2777         // Handle the memory dependencies.
2778         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2779           if (MemoryDepSD->hasValidDependencies() &&
2780               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2781             // There are no more unscheduled dependencies after decrementing,
2782             // so we can put the dependent instruction into the ready list.
2783             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2784             assert(!DepBundle->IsScheduled &&
2785                    "already scheduled bundle gets ready");
2786             ReadyList.insert(DepBundle);
2787             LLVM_DEBUG(dbgs()
2788                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2789           }
2790         }
2791       }
2792     }
2793 
2794     /// Verify basic self consistency properties of the data structure.
2795     void verify() {
2796       if (!ScheduleStart)
2797         return;
2798 
2799       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2800              ScheduleStart->comesBefore(ScheduleEnd) &&
2801              "Not a valid scheduling region?");
2802 
2803       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2804         auto *SD = getScheduleData(I);
2805         assert(SD && "primary scheduledata must exist in window");
2806         assert(isInSchedulingRegion(SD) &&
2807                "primary schedule data not in window?");
2808         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2809                "entire bundle in window!");
2810         (void)SD;
2811         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2812       }
2813 
2814       for (auto *SD : ReadyInsts) {
2815         assert(SD->isSchedulingEntity() && SD->isReady() &&
2816                "item in ready list not ready?");
2817         (void)SD;
2818       }
2819     }
2820 
2821     void doForAllOpcodes(Value *V,
2822                          function_ref<void(ScheduleData *SD)> Action) {
2823       if (ScheduleData *SD = getScheduleData(V))
2824         Action(SD);
2825       auto I = ExtraScheduleDataMap.find(V);
2826       if (I != ExtraScheduleDataMap.end())
2827         for (auto &P : I->second)
2828           if (isInSchedulingRegion(P.second))
2829             Action(P.second);
2830     }
2831 
2832     /// Put all instructions into the ReadyList which are ready for scheduling.
2833     template <typename ReadyListType>
2834     void initialFillReadyList(ReadyListType &ReadyList) {
2835       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2836         doForAllOpcodes(I, [&](ScheduleData *SD) {
2837           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2838               SD->isReady()) {
2839             ReadyList.insert(SD);
2840             LLVM_DEBUG(dbgs()
2841                        << "SLP:    initially in ready list: " << *SD << "\n");
2842           }
2843         });
2844       }
2845     }
2846 
2847     /// Build a bundle from the ScheduleData nodes corresponding to the
2848     /// scalar instruction for each lane.
2849     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2850 
2851     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2852     /// cyclic dependencies. This is only a dry-run, no instructions are
2853     /// actually moved at this stage.
2854     /// \returns the scheduling bundle. The returned Optional value is non-None
2855     /// if \p VL is allowed to be scheduled.
2856     Optional<ScheduleData *>
2857     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2858                       const InstructionsState &S);
2859 
2860     /// Un-bundles a group of instructions.
2861     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2862 
2863     /// Allocates schedule data chunk.
2864     ScheduleData *allocateScheduleDataChunks();
2865 
2866     /// Extends the scheduling region so that V is inside the region.
2867     /// \returns true if the region size is within the limit.
2868     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2869 
2870     /// Initialize the ScheduleData structures for new instructions in the
2871     /// scheduling region.
2872     void initScheduleData(Instruction *FromI, Instruction *ToI,
2873                           ScheduleData *PrevLoadStore,
2874                           ScheduleData *NextLoadStore);
2875 
2876     /// Updates the dependency information of a bundle and of all instructions/
2877     /// bundles which depend on the original bundle.
2878     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2879                                BoUpSLP *SLP);
2880 
2881     /// Sets all instruction in the scheduling region to un-scheduled.
2882     void resetSchedule();
2883 
2884     BasicBlock *BB;
2885 
2886     /// Simple memory allocation for ScheduleData.
2887     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2888 
2889     /// The size of a ScheduleData array in ScheduleDataChunks.
2890     int ChunkSize;
2891 
2892     /// The allocator position in the current chunk, which is the last entry
2893     /// of ScheduleDataChunks.
2894     int ChunkPos;
2895 
2896     /// Attaches ScheduleData to Instruction.
2897     /// Note that the mapping survives during all vectorization iterations, i.e.
2898     /// ScheduleData structures are recycled.
2899     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2900 
2901     /// Attaches ScheduleData to Instruction with the leading key.
2902     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2903         ExtraScheduleDataMap;
2904 
2905     /// The ready-list for scheduling (only used for the dry-run).
2906     SetVector<ScheduleData *> ReadyInsts;
2907 
2908     /// The first instruction of the scheduling region.
2909     Instruction *ScheduleStart = nullptr;
2910 
2911     /// The first instruction _after_ the scheduling region.
2912     Instruction *ScheduleEnd = nullptr;
2913 
2914     /// The first memory accessing instruction in the scheduling region
2915     /// (can be null).
2916     ScheduleData *FirstLoadStoreInRegion = nullptr;
2917 
2918     /// The last memory accessing instruction in the scheduling region
2919     /// (can be null).
2920     ScheduleData *LastLoadStoreInRegion = nullptr;
2921 
2922     /// The current size of the scheduling region.
2923     int ScheduleRegionSize = 0;
2924 
2925     /// The maximum size allowed for the scheduling region.
2926     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2927 
2928     /// The ID of the scheduling region. For a new vectorization iteration this
2929     /// is incremented which "removes" all ScheduleData from the region.
2930     /// Make sure that the initial SchedulingRegionID is greater than the
2931     /// initial SchedulingRegionID in ScheduleData (which is 0).
2932     int SchedulingRegionID = 1;
2933   };
2934 
2935   /// Attaches the BlockScheduling structures to basic blocks.
2936   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2937 
2938   /// Performs the "real" scheduling. Done before vectorization is actually
2939   /// performed in a basic block.
2940   void scheduleBlock(BlockScheduling *BS);
2941 
2942   /// List of users to ignore during scheduling and that don't need extracting.
2943   ArrayRef<Value *> UserIgnoreList;
2944 
2945   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2946   /// sorted SmallVectors of unsigned.
2947   struct OrdersTypeDenseMapInfo {
2948     static OrdersType getEmptyKey() {
2949       OrdersType V;
2950       V.push_back(~1U);
2951       return V;
2952     }
2953 
2954     static OrdersType getTombstoneKey() {
2955       OrdersType V;
2956       V.push_back(~2U);
2957       return V;
2958     }
2959 
2960     static unsigned getHashValue(const OrdersType &V) {
2961       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2962     }
2963 
2964     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2965       return LHS == RHS;
2966     }
2967   };
2968 
2969   // Analysis and block reference.
2970   Function *F;
2971   ScalarEvolution *SE;
2972   TargetTransformInfo *TTI;
2973   TargetLibraryInfo *TLI;
2974   LoopInfo *LI;
2975   DominatorTree *DT;
2976   AssumptionCache *AC;
2977   DemandedBits *DB;
2978   const DataLayout *DL;
2979   OptimizationRemarkEmitter *ORE;
2980 
2981   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2982   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2983 
2984   /// Instruction builder to construct the vectorized tree.
2985   IRBuilder<> Builder;
2986 
2987   /// A map of scalar integer values to the smallest bit width with which they
2988   /// can legally be represented. The values map to (width, signed) pairs,
2989   /// where "width" indicates the minimum bit width and "signed" is True if the
2990   /// value must be signed-extended, rather than zero-extended, back to its
2991   /// original width.
2992   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2993 };
2994 
2995 } // end namespace slpvectorizer
2996 
2997 template <> struct GraphTraits<BoUpSLP *> {
2998   using TreeEntry = BoUpSLP::TreeEntry;
2999 
3000   /// NodeRef has to be a pointer per the GraphWriter.
3001   using NodeRef = TreeEntry *;
3002 
3003   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3004 
3005   /// Add the VectorizableTree to the index iterator to be able to return
3006   /// TreeEntry pointers.
3007   struct ChildIteratorType
3008       : public iterator_adaptor_base<
3009             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3010     ContainerTy &VectorizableTree;
3011 
3012     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3013                       ContainerTy &VT)
3014         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3015 
3016     NodeRef operator*() { return I->UserTE; }
3017   };
3018 
3019   static NodeRef getEntryNode(BoUpSLP &R) {
3020     return R.VectorizableTree[0].get();
3021   }
3022 
3023   static ChildIteratorType child_begin(NodeRef N) {
3024     return {N->UserTreeIndices.begin(), N->Container};
3025   }
3026 
3027   static ChildIteratorType child_end(NodeRef N) {
3028     return {N->UserTreeIndices.end(), N->Container};
3029   }
3030 
3031   /// For the node iterator we just need to turn the TreeEntry iterator into a
3032   /// TreeEntry* iterator so that it dereferences to NodeRef.
3033   class nodes_iterator {
3034     using ItTy = ContainerTy::iterator;
3035     ItTy It;
3036 
3037   public:
3038     nodes_iterator(const ItTy &It2) : It(It2) {}
3039     NodeRef operator*() { return It->get(); }
3040     nodes_iterator operator++() {
3041       ++It;
3042       return *this;
3043     }
3044     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3045   };
3046 
3047   static nodes_iterator nodes_begin(BoUpSLP *R) {
3048     return nodes_iterator(R->VectorizableTree.begin());
3049   }
3050 
3051   static nodes_iterator nodes_end(BoUpSLP *R) {
3052     return nodes_iterator(R->VectorizableTree.end());
3053   }
3054 
3055   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3056 };
3057 
3058 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3059   using TreeEntry = BoUpSLP::TreeEntry;
3060 
3061   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3062 
3063   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3064     std::string Str;
3065     raw_string_ostream OS(Str);
3066     if (isSplat(Entry->Scalars))
3067       OS << "<splat> ";
3068     for (auto V : Entry->Scalars) {
3069       OS << *V;
3070       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3071             return EU.Scalar == V;
3072           }))
3073         OS << " <extract>";
3074       OS << "\n";
3075     }
3076     return Str;
3077   }
3078 
3079   static std::string getNodeAttributes(const TreeEntry *Entry,
3080                                        const BoUpSLP *) {
3081     if (Entry->State == TreeEntry::NeedToGather)
3082       return "color=red";
3083     return "";
3084   }
3085 };
3086 
3087 } // end namespace llvm
3088 
3089 BoUpSLP::~BoUpSLP() {
3090   for (const auto &Pair : DeletedInstructions) {
3091     // Replace operands of ignored instructions with Undefs in case if they were
3092     // marked for deletion.
3093     if (Pair.getSecond()) {
3094       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3095       Pair.getFirst()->replaceAllUsesWith(Undef);
3096     }
3097     Pair.getFirst()->dropAllReferences();
3098   }
3099   for (const auto &Pair : DeletedInstructions) {
3100     assert(Pair.getFirst()->use_empty() &&
3101            "trying to erase instruction with users.");
3102     Pair.getFirst()->eraseFromParent();
3103   }
3104 #ifdef EXPENSIVE_CHECKS
3105   // If we could guarantee that this call is not extremely slow, we could
3106   // remove the ifdef limitation (see PR47712).
3107   assert(!verifyFunction(*F, &dbgs()));
3108 #endif
3109 }
3110 
3111 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3112   for (auto *V : AV) {
3113     if (auto *I = dyn_cast<Instruction>(V))
3114       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3115   };
3116 }
3117 
3118 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3119 /// contains original mask for the scalars reused in the node. Procedure
3120 /// transform this mask in accordance with the given \p Mask.
3121 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3122   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3123          "Expected non-empty mask.");
3124   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3125   Prev.swap(Reuses);
3126   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3127     if (Mask[I] != UndefMaskElem)
3128       Reuses[Mask[I]] = Prev[I];
3129 }
3130 
3131 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3132 /// the original order of the scalars. Procedure transforms the provided order
3133 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3134 /// identity order, \p Order is cleared.
3135 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3136   assert(!Mask.empty() && "Expected non-empty mask.");
3137   SmallVector<int> MaskOrder;
3138   if (Order.empty()) {
3139     MaskOrder.resize(Mask.size());
3140     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3141   } else {
3142     inversePermutation(Order, MaskOrder);
3143   }
3144   reorderReuses(MaskOrder, Mask);
3145   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3146     Order.clear();
3147     return;
3148   }
3149   Order.assign(Mask.size(), Mask.size());
3150   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3151     if (MaskOrder[I] != UndefMaskElem)
3152       Order[MaskOrder[I]] = I;
3153   fixupOrderingIndices(Order);
3154 }
3155 
3156 Optional<BoUpSLP::OrdersType>
3157 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3158   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3159   unsigned NumScalars = TE.Scalars.size();
3160   OrdersType CurrentOrder(NumScalars, NumScalars);
3161   SmallVector<int> Positions;
3162   SmallBitVector UsedPositions(NumScalars);
3163   const TreeEntry *STE = nullptr;
3164   // Try to find all gathered scalars that are gets vectorized in other
3165   // vectorize node. Here we can have only one single tree vector node to
3166   // correctly identify order of the gathered scalars.
3167   for (unsigned I = 0; I < NumScalars; ++I) {
3168     Value *V = TE.Scalars[I];
3169     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3170       continue;
3171     if (const auto *LocalSTE = getTreeEntry(V)) {
3172       if (!STE)
3173         STE = LocalSTE;
3174       else if (STE != LocalSTE)
3175         // Take the order only from the single vector node.
3176         return None;
3177       unsigned Lane =
3178           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3179       if (Lane >= NumScalars)
3180         return None;
3181       if (CurrentOrder[Lane] != NumScalars) {
3182         if (Lane != I)
3183           continue;
3184         UsedPositions.reset(CurrentOrder[Lane]);
3185       }
3186       // The partial identity (where only some elements of the gather node are
3187       // in the identity order) is good.
3188       CurrentOrder[Lane] = I;
3189       UsedPositions.set(I);
3190     }
3191   }
3192   // Need to keep the order if we have a vector entry and at least 2 scalars or
3193   // the vectorized entry has just 2 scalars.
3194   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3195     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3196       for (unsigned I = 0; I < NumScalars; ++I)
3197         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3198           return false;
3199       return true;
3200     };
3201     if (IsIdentityOrder(CurrentOrder)) {
3202       CurrentOrder.clear();
3203       return CurrentOrder;
3204     }
3205     auto *It = CurrentOrder.begin();
3206     for (unsigned I = 0; I < NumScalars;) {
3207       if (UsedPositions.test(I)) {
3208         ++I;
3209         continue;
3210       }
3211       if (*It == NumScalars) {
3212         *It = I;
3213         ++I;
3214       }
3215       ++It;
3216     }
3217     return CurrentOrder;
3218   }
3219   return None;
3220 }
3221 
3222 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3223                                                          bool TopToBottom) {
3224   // No need to reorder if need to shuffle reuses, still need to shuffle the
3225   // node.
3226   if (!TE.ReuseShuffleIndices.empty())
3227     return None;
3228   if (TE.State == TreeEntry::Vectorize &&
3229       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3230        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3231       !TE.isAltShuffle())
3232     return TE.ReorderIndices;
3233   if (TE.State == TreeEntry::NeedToGather) {
3234     // TODO: add analysis of other gather nodes with extractelement
3235     // instructions and other values/instructions, not only undefs.
3236     if (((TE.getOpcode() == Instruction::ExtractElement &&
3237           !TE.isAltShuffle()) ||
3238          (all_of(TE.Scalars,
3239                  [](Value *V) {
3240                    return isa<UndefValue, ExtractElementInst>(V);
3241                  }) &&
3242           any_of(TE.Scalars,
3243                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3244         all_of(TE.Scalars,
3245                [](Value *V) {
3246                  auto *EE = dyn_cast<ExtractElementInst>(V);
3247                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3248                }) &&
3249         allSameType(TE.Scalars)) {
3250       // Check that gather of extractelements can be represented as
3251       // just a shuffle of a single vector.
3252       OrdersType CurrentOrder;
3253       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3254       if (Reuse || !CurrentOrder.empty()) {
3255         if (!CurrentOrder.empty())
3256           fixupOrderingIndices(CurrentOrder);
3257         return CurrentOrder;
3258       }
3259     }
3260     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3261       return CurrentOrder;
3262   }
3263   return None;
3264 }
3265 
3266 void BoUpSLP::reorderTopToBottom() {
3267   // Maps VF to the graph nodes.
3268   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3269   // ExtractElement gather nodes which can be vectorized and need to handle
3270   // their ordering.
3271   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3272   // Find all reorderable nodes with the given VF.
3273   // Currently the are vectorized stores,loads,extracts + some gathering of
3274   // extracts.
3275   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3276                                  const std::unique_ptr<TreeEntry> &TE) {
3277     if (Optional<OrdersType> CurrentOrder =
3278             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3279       // Do not include ordering for nodes used in the alt opcode vectorization,
3280       // better to reorder them during bottom-to-top stage. If follow the order
3281       // here, it causes reordering of the whole graph though actually it is
3282       // profitable just to reorder the subgraph that starts from the alternate
3283       // opcode vectorization node. Such nodes already end-up with the shuffle
3284       // instruction and it is just enough to change this shuffle rather than
3285       // rotate the scalars for the whole graph.
3286       unsigned Cnt = 0;
3287       const TreeEntry *UserTE = TE.get();
3288       while (UserTE && Cnt < RecursionMaxDepth) {
3289         if (UserTE->UserTreeIndices.size() != 1)
3290           break;
3291         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3292               return EI.UserTE->State == TreeEntry::Vectorize &&
3293                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3294             }))
3295           return;
3296         if (UserTE->UserTreeIndices.empty())
3297           UserTE = nullptr;
3298         else
3299           UserTE = UserTE->UserTreeIndices.back().UserTE;
3300         ++Cnt;
3301       }
3302       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3303       if (TE->State != TreeEntry::Vectorize)
3304         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3305     }
3306   });
3307 
3308   // Reorder the graph nodes according to their vectorization factor.
3309   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3310        VF /= 2) {
3311     auto It = VFToOrderedEntries.find(VF);
3312     if (It == VFToOrderedEntries.end())
3313       continue;
3314     // Try to find the most profitable order. We just are looking for the most
3315     // used order and reorder scalar elements in the nodes according to this
3316     // mostly used order.
3317     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3318     // All operands are reordered and used only in this node - propagate the
3319     // most used order to the user node.
3320     MapVector<OrdersType, unsigned,
3321               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3322         OrdersUses;
3323     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3324     for (const TreeEntry *OpTE : OrderedEntries) {
3325       // No need to reorder this nodes, still need to extend and to use shuffle,
3326       // just need to merge reordering shuffle and the reuse shuffle.
3327       if (!OpTE->ReuseShuffleIndices.empty())
3328         continue;
3329       // Count number of orders uses.
3330       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3331         if (OpTE->State == TreeEntry::NeedToGather)
3332           return GathersToOrders.find(OpTE)->second;
3333         return OpTE->ReorderIndices;
3334       }();
3335       // Stores actually store the mask, not the order, need to invert.
3336       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3337           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3338         SmallVector<int> Mask;
3339         inversePermutation(Order, Mask);
3340         unsigned E = Order.size();
3341         OrdersType CurrentOrder(E, E);
3342         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3343           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3344         });
3345         fixupOrderingIndices(CurrentOrder);
3346         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3347       } else {
3348         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3349       }
3350     }
3351     // Set order of the user node.
3352     if (OrdersUses.empty())
3353       continue;
3354     // Choose the most used order.
3355     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3356     unsigned Cnt = OrdersUses.front().second;
3357     for (const auto &Pair : drop_begin(OrdersUses)) {
3358       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3359         BestOrder = Pair.first;
3360         Cnt = Pair.second;
3361       }
3362     }
3363     // Set order of the user node.
3364     if (BestOrder.empty())
3365       continue;
3366     SmallVector<int> Mask;
3367     inversePermutation(BestOrder, Mask);
3368     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3369     unsigned E = BestOrder.size();
3370     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3371       return I < E ? static_cast<int>(I) : UndefMaskElem;
3372     });
3373     // Do an actual reordering, if profitable.
3374     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3375       // Just do the reordering for the nodes with the given VF.
3376       if (TE->Scalars.size() != VF) {
3377         if (TE->ReuseShuffleIndices.size() == VF) {
3378           // Need to reorder the reuses masks of the operands with smaller VF to
3379           // be able to find the match between the graph nodes and scalar
3380           // operands of the given node during vectorization/cost estimation.
3381           assert(all_of(TE->UserTreeIndices,
3382                         [VF, &TE](const EdgeInfo &EI) {
3383                           return EI.UserTE->Scalars.size() == VF ||
3384                                  EI.UserTE->Scalars.size() ==
3385                                      TE->Scalars.size();
3386                         }) &&
3387                  "All users must be of VF size.");
3388           // Update ordering of the operands with the smaller VF than the given
3389           // one.
3390           reorderReuses(TE->ReuseShuffleIndices, Mask);
3391         }
3392         continue;
3393       }
3394       if (TE->State == TreeEntry::Vectorize &&
3395           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3396               InsertElementInst>(TE->getMainOp()) &&
3397           !TE->isAltShuffle()) {
3398         // Build correct orders for extract{element,value}, loads and
3399         // stores.
3400         reorderOrder(TE->ReorderIndices, Mask);
3401         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3402           TE->reorderOperands(Mask);
3403       } else {
3404         // Reorder the node and its operands.
3405         TE->reorderOperands(Mask);
3406         assert(TE->ReorderIndices.empty() &&
3407                "Expected empty reorder sequence.");
3408         reorderScalars(TE->Scalars, Mask);
3409       }
3410       if (!TE->ReuseShuffleIndices.empty()) {
3411         // Apply reversed order to keep the original ordering of the reused
3412         // elements to avoid extra reorder indices shuffling.
3413         OrdersType CurrentOrder;
3414         reorderOrder(CurrentOrder, MaskOrder);
3415         SmallVector<int> NewReuses;
3416         inversePermutation(CurrentOrder, NewReuses);
3417         addMask(NewReuses, TE->ReuseShuffleIndices);
3418         TE->ReuseShuffleIndices.swap(NewReuses);
3419       }
3420     }
3421   }
3422 }
3423 
3424 bool BoUpSLP::canReorderOperands(
3425     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3426     ArrayRef<TreeEntry *> ReorderableGathers,
3427     SmallVectorImpl<TreeEntry *> &GatherOps) {
3428   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3429     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3430           return OpData.first == I &&
3431                  OpData.second->State == TreeEntry::Vectorize;
3432         }))
3433       continue;
3434     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3435       // Do not reorder if operand node is used by many user nodes.
3436       if (any_of(TE->UserTreeIndices,
3437                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3438         return false;
3439       // Add the node to the list of the ordered nodes with the identity
3440       // order.
3441       Edges.emplace_back(I, TE);
3442       continue;
3443     }
3444     ArrayRef<Value *> VL = UserTE->getOperand(I);
3445     TreeEntry *Gather = nullptr;
3446     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3447           assert(TE->State != TreeEntry::Vectorize &&
3448                  "Only non-vectorized nodes are expected.");
3449           if (TE->isSame(VL)) {
3450             Gather = TE;
3451             return true;
3452           }
3453           return false;
3454         }) > 1)
3455       return false;
3456     if (Gather)
3457       GatherOps.push_back(Gather);
3458   }
3459   return true;
3460 }
3461 
3462 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3463   SetVector<TreeEntry *> OrderedEntries;
3464   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3465   // Find all reorderable leaf nodes with the given VF.
3466   // Currently the are vectorized loads,extracts without alternate operands +
3467   // some gathering of extracts.
3468   SmallVector<TreeEntry *> NonVectorized;
3469   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3470                               &NonVectorized](
3471                                  const std::unique_ptr<TreeEntry> &TE) {
3472     if (TE->State != TreeEntry::Vectorize)
3473       NonVectorized.push_back(TE.get());
3474     if (Optional<OrdersType> CurrentOrder =
3475             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3476       OrderedEntries.insert(TE.get());
3477       if (TE->State != TreeEntry::Vectorize)
3478         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3479     }
3480   });
3481 
3482   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3483   // I.e., if the node has operands, that are reordered, try to make at least
3484   // one operand order in the natural order and reorder others + reorder the
3485   // user node itself.
3486   SmallPtrSet<const TreeEntry *, 4> Visited;
3487   while (!OrderedEntries.empty()) {
3488     // 1. Filter out only reordered nodes.
3489     // 2. If the entry has multiple uses - skip it and jump to the next node.
3490     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3491     SmallVector<TreeEntry *> Filtered;
3492     for (TreeEntry *TE : OrderedEntries) {
3493       if (!(TE->State == TreeEntry::Vectorize ||
3494             (TE->State == TreeEntry::NeedToGather &&
3495              GathersToOrders.count(TE))) ||
3496           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3497           !all_of(drop_begin(TE->UserTreeIndices),
3498                   [TE](const EdgeInfo &EI) {
3499                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3500                   }) ||
3501           !Visited.insert(TE).second) {
3502         Filtered.push_back(TE);
3503         continue;
3504       }
3505       // Build a map between user nodes and their operands order to speedup
3506       // search. The graph currently does not provide this dependency directly.
3507       for (EdgeInfo &EI : TE->UserTreeIndices) {
3508         TreeEntry *UserTE = EI.UserTE;
3509         auto It = Users.find(UserTE);
3510         if (It == Users.end())
3511           It = Users.insert({UserTE, {}}).first;
3512         It->second.emplace_back(EI.EdgeIdx, TE);
3513       }
3514     }
3515     // Erase filtered entries.
3516     for_each(Filtered,
3517              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3518     for (auto &Data : Users) {
3519       // Check that operands are used only in the User node.
3520       SmallVector<TreeEntry *> GatherOps;
3521       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3522                               GatherOps)) {
3523         for_each(Data.second,
3524                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3525                    OrderedEntries.remove(Op.second);
3526                  });
3527         continue;
3528       }
3529       // All operands are reordered and used only in this node - propagate the
3530       // most used order to the user node.
3531       MapVector<OrdersType, unsigned,
3532                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3533           OrdersUses;
3534       // Do the analysis for each tree entry only once, otherwise the order of
3535       // the same node my be considered several times, though might be not
3536       // profitable.
3537       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3538       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3539       for (const auto &Op : Data.second) {
3540         TreeEntry *OpTE = Op.second;
3541         if (!VisitedOps.insert(OpTE).second)
3542           continue;
3543         if (!OpTE->ReuseShuffleIndices.empty() ||
3544             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3545           continue;
3546         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3547           if (OpTE->State == TreeEntry::NeedToGather)
3548             return GathersToOrders.find(OpTE)->second;
3549           return OpTE->ReorderIndices;
3550         }();
3551         unsigned NumOps = count_if(
3552             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3553               return P.second == OpTE;
3554             });
3555         // Stores actually store the mask, not the order, need to invert.
3556         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3557             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3558           SmallVector<int> Mask;
3559           inversePermutation(Order, Mask);
3560           unsigned E = Order.size();
3561           OrdersType CurrentOrder(E, E);
3562           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3563             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3564           });
3565           fixupOrderingIndices(CurrentOrder);
3566           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3567               NumOps;
3568         } else {
3569           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3570         }
3571         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3572         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3573                                             const TreeEntry *TE) {
3574           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3575               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3576               (IgnoreReorder && TE->Idx == 0))
3577             return true;
3578           if (TE->State == TreeEntry::NeedToGather) {
3579             auto It = GathersToOrders.find(TE);
3580             if (It != GathersToOrders.end())
3581               return !It->second.empty();
3582             return true;
3583           }
3584           return false;
3585         };
3586         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3587           TreeEntry *UserTE = EI.UserTE;
3588           if (!VisitedUsers.insert(UserTE).second)
3589             continue;
3590           // May reorder user node if it requires reordering, has reused
3591           // scalars, is an alternate op vectorize node or its op nodes require
3592           // reordering.
3593           if (AllowsReordering(UserTE))
3594             continue;
3595           // Check if users allow reordering.
3596           // Currently look up just 1 level of operands to avoid increase of
3597           // the compile time.
3598           // Profitable to reorder if definitely more operands allow
3599           // reordering rather than those with natural order.
3600           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3601           if (static_cast<unsigned>(count_if(
3602                   Ops, [UserTE, &AllowsReordering](
3603                            const std::pair<unsigned, TreeEntry *> &Op) {
3604                     return AllowsReordering(Op.second) &&
3605                            all_of(Op.second->UserTreeIndices,
3606                                   [UserTE](const EdgeInfo &EI) {
3607                                     return EI.UserTE == UserTE;
3608                                   });
3609                   })) <= Ops.size() / 2)
3610             ++Res.first->second;
3611         }
3612       }
3613       // If no orders - skip current nodes and jump to the next one, if any.
3614       if (OrdersUses.empty()) {
3615         for_each(Data.second,
3616                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3617                    OrderedEntries.remove(Op.second);
3618                  });
3619         continue;
3620       }
3621       // Choose the best order.
3622       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3623       unsigned Cnt = OrdersUses.front().second;
3624       for (const auto &Pair : drop_begin(OrdersUses)) {
3625         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3626           BestOrder = Pair.first;
3627           Cnt = Pair.second;
3628         }
3629       }
3630       // Set order of the user node (reordering of operands and user nodes).
3631       if (BestOrder.empty()) {
3632         for_each(Data.second,
3633                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3634                    OrderedEntries.remove(Op.second);
3635                  });
3636         continue;
3637       }
3638       // Erase operands from OrderedEntries list and adjust their orders.
3639       VisitedOps.clear();
3640       SmallVector<int> Mask;
3641       inversePermutation(BestOrder, Mask);
3642       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3643       unsigned E = BestOrder.size();
3644       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3645         return I < E ? static_cast<int>(I) : UndefMaskElem;
3646       });
3647       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3648         TreeEntry *TE = Op.second;
3649         OrderedEntries.remove(TE);
3650         if (!VisitedOps.insert(TE).second)
3651           continue;
3652         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3653           // Just reorder reuses indices.
3654           reorderReuses(TE->ReuseShuffleIndices, Mask);
3655           continue;
3656         }
3657         // Gathers are processed separately.
3658         if (TE->State != TreeEntry::Vectorize)
3659           continue;
3660         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3661                 TE->ReorderIndices.empty()) &&
3662                "Non-matching sizes of user/operand entries.");
3663         reorderOrder(TE->ReorderIndices, Mask);
3664       }
3665       // For gathers just need to reorder its scalars.
3666       for (TreeEntry *Gather : GatherOps) {
3667         assert(Gather->ReorderIndices.empty() &&
3668                "Unexpected reordering of gathers.");
3669         if (!Gather->ReuseShuffleIndices.empty()) {
3670           // Just reorder reuses indices.
3671           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3672           continue;
3673         }
3674         reorderScalars(Gather->Scalars, Mask);
3675         OrderedEntries.remove(Gather);
3676       }
3677       // Reorder operands of the user node and set the ordering for the user
3678       // node itself.
3679       if (Data.first->State != TreeEntry::Vectorize ||
3680           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3681               Data.first->getMainOp()) ||
3682           Data.first->isAltShuffle())
3683         Data.first->reorderOperands(Mask);
3684       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3685           Data.first->isAltShuffle()) {
3686         reorderScalars(Data.first->Scalars, Mask);
3687         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3688         if (Data.first->ReuseShuffleIndices.empty() &&
3689             !Data.first->ReorderIndices.empty() &&
3690             !Data.first->isAltShuffle()) {
3691           // Insert user node to the list to try to sink reordering deeper in
3692           // the graph.
3693           OrderedEntries.insert(Data.first);
3694         }
3695       } else {
3696         reorderOrder(Data.first->ReorderIndices, Mask);
3697       }
3698     }
3699   }
3700   // If the reordering is unnecessary, just remove the reorder.
3701   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3702       VectorizableTree.front()->ReuseShuffleIndices.empty())
3703     VectorizableTree.front()->ReorderIndices.clear();
3704 }
3705 
3706 void BoUpSLP::buildExternalUses(
3707     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3708   // Collect the values that we need to extract from the tree.
3709   for (auto &TEPtr : VectorizableTree) {
3710     TreeEntry *Entry = TEPtr.get();
3711 
3712     // No need to handle users of gathered values.
3713     if (Entry->State == TreeEntry::NeedToGather)
3714       continue;
3715 
3716     // For each lane:
3717     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3718       Value *Scalar = Entry->Scalars[Lane];
3719       int FoundLane = Entry->findLaneForValue(Scalar);
3720 
3721       // Check if the scalar is externally used as an extra arg.
3722       auto ExtI = ExternallyUsedValues.find(Scalar);
3723       if (ExtI != ExternallyUsedValues.end()) {
3724         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3725                           << Lane << " from " << *Scalar << ".\n");
3726         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3727       }
3728       for (User *U : Scalar->users()) {
3729         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3730 
3731         Instruction *UserInst = dyn_cast<Instruction>(U);
3732         if (!UserInst)
3733           continue;
3734 
3735         if (isDeleted(UserInst))
3736           continue;
3737 
3738         // Skip in-tree scalars that become vectors
3739         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3740           Value *UseScalar = UseEntry->Scalars[0];
3741           // Some in-tree scalars will remain as scalar in vectorized
3742           // instructions. If that is the case, the one in Lane 0 will
3743           // be used.
3744           if (UseScalar != U ||
3745               UseEntry->State == TreeEntry::ScatterVectorize ||
3746               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3747             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3748                               << ".\n");
3749             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3750             continue;
3751           }
3752         }
3753 
3754         // Ignore users in the user ignore list.
3755         if (is_contained(UserIgnoreList, UserInst))
3756           continue;
3757 
3758         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3759                           << Lane << " from " << *Scalar << ".\n");
3760         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3761       }
3762     }
3763   }
3764 }
3765 
3766 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3767                         ArrayRef<Value *> UserIgnoreLst) {
3768   deleteTree();
3769   UserIgnoreList = UserIgnoreLst;
3770   if (!allSameType(Roots))
3771     return;
3772   buildTree_rec(Roots, 0, EdgeInfo());
3773 }
3774 
3775 namespace {
3776 /// Tracks the state we can represent the loads in the given sequence.
3777 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3778 } // anonymous namespace
3779 
3780 /// Checks if the given array of loads can be represented as a vectorized,
3781 /// scatter or just simple gather.
3782 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3783                                     const TargetTransformInfo &TTI,
3784                                     const DataLayout &DL, ScalarEvolution &SE,
3785                                     SmallVectorImpl<unsigned> &Order,
3786                                     SmallVectorImpl<Value *> &PointerOps) {
3787   // Check that a vectorized load would load the same memory as a scalar
3788   // load. For example, we don't want to vectorize loads that are smaller
3789   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3790   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3791   // from such a struct, we read/write packed bits disagreeing with the
3792   // unvectorized version.
3793   Type *ScalarTy = VL0->getType();
3794 
3795   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3796     return LoadsState::Gather;
3797 
3798   // Make sure all loads in the bundle are simple - we can't vectorize
3799   // atomic or volatile loads.
3800   PointerOps.clear();
3801   PointerOps.resize(VL.size());
3802   auto *POIter = PointerOps.begin();
3803   for (Value *V : VL) {
3804     auto *L = cast<LoadInst>(V);
3805     if (!L->isSimple())
3806       return LoadsState::Gather;
3807     *POIter = L->getPointerOperand();
3808     ++POIter;
3809   }
3810 
3811   Order.clear();
3812   // Check the order of pointer operands.
3813   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3814     Value *Ptr0;
3815     Value *PtrN;
3816     if (Order.empty()) {
3817       Ptr0 = PointerOps.front();
3818       PtrN = PointerOps.back();
3819     } else {
3820       Ptr0 = PointerOps[Order.front()];
3821       PtrN = PointerOps[Order.back()];
3822     }
3823     Optional<int> Diff =
3824         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3825     // Check that the sorted loads are consecutive.
3826     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3827       return LoadsState::Vectorize;
3828     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3829     for (Value *V : VL)
3830       CommonAlignment =
3831           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3832     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3833                                 CommonAlignment))
3834       return LoadsState::ScatterVectorize;
3835   }
3836 
3837   return LoadsState::Gather;
3838 }
3839 
3840 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3841                             const EdgeInfo &UserTreeIdx) {
3842   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3843 
3844   SmallVector<int> ReuseShuffleIndicies;
3845   SmallVector<Value *> UniqueValues;
3846   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3847                                 &UserTreeIdx,
3848                                 this](const InstructionsState &S) {
3849     // Check that every instruction appears once in this bundle.
3850     DenseMap<Value *, unsigned> UniquePositions;
3851     for (Value *V : VL) {
3852       if (isConstant(V)) {
3853         ReuseShuffleIndicies.emplace_back(
3854             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3855         UniqueValues.emplace_back(V);
3856         continue;
3857       }
3858       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3859       ReuseShuffleIndicies.emplace_back(Res.first->second);
3860       if (Res.second)
3861         UniqueValues.emplace_back(V);
3862     }
3863     size_t NumUniqueScalarValues = UniqueValues.size();
3864     if (NumUniqueScalarValues == VL.size()) {
3865       ReuseShuffleIndicies.clear();
3866     } else {
3867       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3868       if (NumUniqueScalarValues <= 1 ||
3869           (UniquePositions.size() == 1 && all_of(UniqueValues,
3870                                                  [](Value *V) {
3871                                                    return isa<UndefValue>(V) ||
3872                                                           !isConstant(V);
3873                                                  })) ||
3874           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3875         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3876         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3877         return false;
3878       }
3879       VL = UniqueValues;
3880     }
3881     return true;
3882   };
3883 
3884   InstructionsState S = getSameOpcode(VL);
3885   if (Depth == RecursionMaxDepth) {
3886     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3887     if (TryToFindDuplicates(S))
3888       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3889                    ReuseShuffleIndicies);
3890     return;
3891   }
3892 
3893   // Don't handle scalable vectors
3894   if (S.getOpcode() == Instruction::ExtractElement &&
3895       isa<ScalableVectorType>(
3896           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3897     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3898     if (TryToFindDuplicates(S))
3899       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3900                    ReuseShuffleIndicies);
3901     return;
3902   }
3903 
3904   // Don't handle vectors.
3905   if (S.OpValue->getType()->isVectorTy() &&
3906       !isa<InsertElementInst>(S.OpValue)) {
3907     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3908     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3909     return;
3910   }
3911 
3912   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3913     if (SI->getValueOperand()->getType()->isVectorTy()) {
3914       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3915       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3916       return;
3917     }
3918 
3919   // If all of the operands are identical or constant we have a simple solution.
3920   // If we deal with insert/extract instructions, they all must have constant
3921   // indices, otherwise we should gather them, not try to vectorize.
3922   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3923       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3924        !all_of(VL, isVectorLikeInstWithConstOps))) {
3925     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3926     if (TryToFindDuplicates(S))
3927       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3928                    ReuseShuffleIndicies);
3929     return;
3930   }
3931 
3932   // We now know that this is a vector of instructions of the same type from
3933   // the same block.
3934 
3935   // Don't vectorize ephemeral values.
3936   for (Value *V : VL) {
3937     if (EphValues.count(V)) {
3938       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3939                         << ") is ephemeral.\n");
3940       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3941       return;
3942     }
3943   }
3944 
3945   // Check if this is a duplicate of another entry.
3946   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3947     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3948     if (!E->isSame(VL)) {
3949       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3950       if (TryToFindDuplicates(S))
3951         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3952                      ReuseShuffleIndicies);
3953       return;
3954     }
3955     // Record the reuse of the tree node.  FIXME, currently this is only used to
3956     // properly draw the graph rather than for the actual vectorization.
3957     E->UserTreeIndices.push_back(UserTreeIdx);
3958     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3959                       << ".\n");
3960     return;
3961   }
3962 
3963   // Check that none of the instructions in the bundle are already in the tree.
3964   for (Value *V : VL) {
3965     auto *I = dyn_cast<Instruction>(V);
3966     if (!I)
3967       continue;
3968     if (getTreeEntry(I)) {
3969       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3970                         << ") is already in tree.\n");
3971       if (TryToFindDuplicates(S))
3972         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3973                      ReuseShuffleIndicies);
3974       return;
3975     }
3976   }
3977 
3978   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3979   for (Value *V : VL) {
3980     if (is_contained(UserIgnoreList, V)) {
3981       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3982       if (TryToFindDuplicates(S))
3983         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3984                      ReuseShuffleIndicies);
3985       return;
3986     }
3987   }
3988 
3989   // Check that all of the users of the scalars that we want to vectorize are
3990   // schedulable.
3991   auto *VL0 = cast<Instruction>(S.OpValue);
3992   BasicBlock *BB = VL0->getParent();
3993 
3994   if (!DT->isReachableFromEntry(BB)) {
3995     // Don't go into unreachable blocks. They may contain instructions with
3996     // dependency cycles which confuse the final scheduling.
3997     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3998     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3999     return;
4000   }
4001 
4002   // Check that every instruction appears once in this bundle.
4003   if (!TryToFindDuplicates(S))
4004     return;
4005 
4006   auto &BSRef = BlocksSchedules[BB];
4007   if (!BSRef)
4008     BSRef = std::make_unique<BlockScheduling>(BB);
4009 
4010   BlockScheduling &BS = *BSRef.get();
4011 
4012   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4013 #ifdef EXPENSIVE_CHECKS
4014   // Make sure we didn't break any internal invariants
4015   BS.verify();
4016 #endif
4017   if (!Bundle) {
4018     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4019     assert((!BS.getScheduleData(VL0) ||
4020             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4021            "tryScheduleBundle should cancelScheduling on failure");
4022     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4023                  ReuseShuffleIndicies);
4024     return;
4025   }
4026   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4027 
4028   unsigned ShuffleOrOp = S.isAltShuffle() ?
4029                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4030   switch (ShuffleOrOp) {
4031     case Instruction::PHI: {
4032       auto *PH = cast<PHINode>(VL0);
4033 
4034       // Check for terminator values (e.g. invoke).
4035       for (Value *V : VL)
4036         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4037           Instruction *Term = dyn_cast<Instruction>(
4038               cast<PHINode>(V)->getIncomingValueForBlock(
4039                   PH->getIncomingBlock(I)));
4040           if (Term && Term->isTerminator()) {
4041             LLVM_DEBUG(dbgs()
4042                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4043             BS.cancelScheduling(VL, VL0);
4044             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4045                          ReuseShuffleIndicies);
4046             return;
4047           }
4048         }
4049 
4050       TreeEntry *TE =
4051           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4052       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4053 
4054       // Keeps the reordered operands to avoid code duplication.
4055       SmallVector<ValueList, 2> OperandsVec;
4056       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4057         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4058           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4059           TE->setOperand(I, Operands);
4060           OperandsVec.push_back(Operands);
4061           continue;
4062         }
4063         ValueList Operands;
4064         // Prepare the operand vector.
4065         for (Value *V : VL)
4066           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4067               PH->getIncomingBlock(I)));
4068         TE->setOperand(I, Operands);
4069         OperandsVec.push_back(Operands);
4070       }
4071       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4072         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4073       return;
4074     }
4075     case Instruction::ExtractValue:
4076     case Instruction::ExtractElement: {
4077       OrdersType CurrentOrder;
4078       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4079       if (Reuse) {
4080         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4081         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4082                      ReuseShuffleIndicies);
4083         // This is a special case, as it does not gather, but at the same time
4084         // we are not extending buildTree_rec() towards the operands.
4085         ValueList Op0;
4086         Op0.assign(VL.size(), VL0->getOperand(0));
4087         VectorizableTree.back()->setOperand(0, Op0);
4088         return;
4089       }
4090       if (!CurrentOrder.empty()) {
4091         LLVM_DEBUG({
4092           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4093                     "with order";
4094           for (unsigned Idx : CurrentOrder)
4095             dbgs() << " " << Idx;
4096           dbgs() << "\n";
4097         });
4098         fixupOrderingIndices(CurrentOrder);
4099         // Insert new order with initial value 0, if it does not exist,
4100         // otherwise return the iterator to the existing one.
4101         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4102                      ReuseShuffleIndicies, CurrentOrder);
4103         // This is a special case, as it does not gather, but at the same time
4104         // we are not extending buildTree_rec() towards the operands.
4105         ValueList Op0;
4106         Op0.assign(VL.size(), VL0->getOperand(0));
4107         VectorizableTree.back()->setOperand(0, Op0);
4108         return;
4109       }
4110       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4111       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4112                    ReuseShuffleIndicies);
4113       BS.cancelScheduling(VL, VL0);
4114       return;
4115     }
4116     case Instruction::InsertElement: {
4117       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4118 
4119       // Check that we have a buildvector and not a shuffle of 2 or more
4120       // different vectors.
4121       ValueSet SourceVectors;
4122       for (Value *V : VL) {
4123         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4124         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4125       }
4126 
4127       if (count_if(VL, [&SourceVectors](Value *V) {
4128             return !SourceVectors.contains(V);
4129           }) >= 2) {
4130         // Found 2nd source vector - cancel.
4131         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4132                              "different source vectors.\n");
4133         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4134         BS.cancelScheduling(VL, VL0);
4135         return;
4136       }
4137 
4138       auto OrdCompare = [](const std::pair<int, int> &P1,
4139                            const std::pair<int, int> &P2) {
4140         return P1.first > P2.first;
4141       };
4142       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4143                     decltype(OrdCompare)>
4144           Indices(OrdCompare);
4145       for (int I = 0, E = VL.size(); I < E; ++I) {
4146         unsigned Idx = *getInsertIndex(VL[I]);
4147         Indices.emplace(Idx, I);
4148       }
4149       OrdersType CurrentOrder(VL.size(), VL.size());
4150       bool IsIdentity = true;
4151       for (int I = 0, E = VL.size(); I < E; ++I) {
4152         CurrentOrder[Indices.top().second] = I;
4153         IsIdentity &= Indices.top().second == I;
4154         Indices.pop();
4155       }
4156       if (IsIdentity)
4157         CurrentOrder.clear();
4158       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4159                                    None, CurrentOrder);
4160       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4161 
4162       constexpr int NumOps = 2;
4163       ValueList VectorOperands[NumOps];
4164       for (int I = 0; I < NumOps; ++I) {
4165         for (Value *V : VL)
4166           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4167 
4168         TE->setOperand(I, VectorOperands[I]);
4169       }
4170       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4171       return;
4172     }
4173     case Instruction::Load: {
4174       // Check that a vectorized load would load the same memory as a scalar
4175       // load. For example, we don't want to vectorize loads that are smaller
4176       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4177       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4178       // from such a struct, we read/write packed bits disagreeing with the
4179       // unvectorized version.
4180       SmallVector<Value *> PointerOps;
4181       OrdersType CurrentOrder;
4182       TreeEntry *TE = nullptr;
4183       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4184                                 PointerOps)) {
4185       case LoadsState::Vectorize:
4186         if (CurrentOrder.empty()) {
4187           // Original loads are consecutive and does not require reordering.
4188           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4189                             ReuseShuffleIndicies);
4190           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4191         } else {
4192           fixupOrderingIndices(CurrentOrder);
4193           // Need to reorder.
4194           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4195                             ReuseShuffleIndicies, CurrentOrder);
4196           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4197         }
4198         TE->setOperandsInOrder();
4199         break;
4200       case LoadsState::ScatterVectorize:
4201         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4202         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4203                           UserTreeIdx, ReuseShuffleIndicies);
4204         TE->setOperandsInOrder();
4205         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4206         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4207         break;
4208       case LoadsState::Gather:
4209         BS.cancelScheduling(VL, VL0);
4210         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4211                      ReuseShuffleIndicies);
4212 #ifndef NDEBUG
4213         Type *ScalarTy = VL0->getType();
4214         if (DL->getTypeSizeInBits(ScalarTy) !=
4215             DL->getTypeAllocSizeInBits(ScalarTy))
4216           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4217         else if (any_of(VL, [](Value *V) {
4218                    return !cast<LoadInst>(V)->isSimple();
4219                  }))
4220           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4221         else
4222           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4223 #endif // NDEBUG
4224         break;
4225       }
4226       return;
4227     }
4228     case Instruction::ZExt:
4229     case Instruction::SExt:
4230     case Instruction::FPToUI:
4231     case Instruction::FPToSI:
4232     case Instruction::FPExt:
4233     case Instruction::PtrToInt:
4234     case Instruction::IntToPtr:
4235     case Instruction::SIToFP:
4236     case Instruction::UIToFP:
4237     case Instruction::Trunc:
4238     case Instruction::FPTrunc:
4239     case Instruction::BitCast: {
4240       Type *SrcTy = VL0->getOperand(0)->getType();
4241       for (Value *V : VL) {
4242         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4243         if (Ty != SrcTy || !isValidElementType(Ty)) {
4244           BS.cancelScheduling(VL, VL0);
4245           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4246                        ReuseShuffleIndicies);
4247           LLVM_DEBUG(dbgs()
4248                      << "SLP: Gathering casts with different src types.\n");
4249           return;
4250         }
4251       }
4252       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4253                                    ReuseShuffleIndicies);
4254       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4255 
4256       TE->setOperandsInOrder();
4257       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4258         ValueList Operands;
4259         // Prepare the operand vector.
4260         for (Value *V : VL)
4261           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4262 
4263         buildTree_rec(Operands, Depth + 1, {TE, i});
4264       }
4265       return;
4266     }
4267     case Instruction::ICmp:
4268     case Instruction::FCmp: {
4269       // Check that all of the compares have the same predicate.
4270       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4271       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4272       Type *ComparedTy = VL0->getOperand(0)->getType();
4273       for (Value *V : VL) {
4274         CmpInst *Cmp = cast<CmpInst>(V);
4275         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4276             Cmp->getOperand(0)->getType() != ComparedTy) {
4277           BS.cancelScheduling(VL, VL0);
4278           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4279                        ReuseShuffleIndicies);
4280           LLVM_DEBUG(dbgs()
4281                      << "SLP: Gathering cmp with different predicate.\n");
4282           return;
4283         }
4284       }
4285 
4286       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4287                                    ReuseShuffleIndicies);
4288       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4289 
4290       ValueList Left, Right;
4291       if (cast<CmpInst>(VL0)->isCommutative()) {
4292         // Commutative predicate - collect + sort operands of the instructions
4293         // so that each side is more likely to have the same opcode.
4294         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4295         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4296       } else {
4297         // Collect operands - commute if it uses the swapped predicate.
4298         for (Value *V : VL) {
4299           auto *Cmp = cast<CmpInst>(V);
4300           Value *LHS = Cmp->getOperand(0);
4301           Value *RHS = Cmp->getOperand(1);
4302           if (Cmp->getPredicate() != P0)
4303             std::swap(LHS, RHS);
4304           Left.push_back(LHS);
4305           Right.push_back(RHS);
4306         }
4307       }
4308       TE->setOperand(0, Left);
4309       TE->setOperand(1, Right);
4310       buildTree_rec(Left, Depth + 1, {TE, 0});
4311       buildTree_rec(Right, Depth + 1, {TE, 1});
4312       return;
4313     }
4314     case Instruction::Select:
4315     case Instruction::FNeg:
4316     case Instruction::Add:
4317     case Instruction::FAdd:
4318     case Instruction::Sub:
4319     case Instruction::FSub:
4320     case Instruction::Mul:
4321     case Instruction::FMul:
4322     case Instruction::UDiv:
4323     case Instruction::SDiv:
4324     case Instruction::FDiv:
4325     case Instruction::URem:
4326     case Instruction::SRem:
4327     case Instruction::FRem:
4328     case Instruction::Shl:
4329     case Instruction::LShr:
4330     case Instruction::AShr:
4331     case Instruction::And:
4332     case Instruction::Or:
4333     case Instruction::Xor: {
4334       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4335                                    ReuseShuffleIndicies);
4336       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4337 
4338       // Sort operands of the instructions so that each side is more likely to
4339       // have the same opcode.
4340       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4341         ValueList Left, Right;
4342         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4343         TE->setOperand(0, Left);
4344         TE->setOperand(1, Right);
4345         buildTree_rec(Left, Depth + 1, {TE, 0});
4346         buildTree_rec(Right, Depth + 1, {TE, 1});
4347         return;
4348       }
4349 
4350       TE->setOperandsInOrder();
4351       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4352         ValueList Operands;
4353         // Prepare the operand vector.
4354         for (Value *V : VL)
4355           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4356 
4357         buildTree_rec(Operands, Depth + 1, {TE, i});
4358       }
4359       return;
4360     }
4361     case Instruction::GetElementPtr: {
4362       // We don't combine GEPs with complicated (nested) indexing.
4363       for (Value *V : VL) {
4364         if (cast<Instruction>(V)->getNumOperands() != 2) {
4365           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4366           BS.cancelScheduling(VL, VL0);
4367           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4368                        ReuseShuffleIndicies);
4369           return;
4370         }
4371       }
4372 
4373       // We can't combine several GEPs into one vector if they operate on
4374       // different types.
4375       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4376       for (Value *V : VL) {
4377         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4378         if (Ty0 != CurTy) {
4379           LLVM_DEBUG(dbgs()
4380                      << "SLP: not-vectorizable GEP (different types).\n");
4381           BS.cancelScheduling(VL, VL0);
4382           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4383                        ReuseShuffleIndicies);
4384           return;
4385         }
4386       }
4387 
4388       // We don't combine GEPs with non-constant indexes.
4389       Type *Ty1 = VL0->getOperand(1)->getType();
4390       for (Value *V : VL) {
4391         auto Op = cast<Instruction>(V)->getOperand(1);
4392         if (!isa<ConstantInt>(Op) ||
4393             (Op->getType() != Ty1 &&
4394              Op->getType()->getScalarSizeInBits() >
4395                  DL->getIndexSizeInBits(
4396                      V->getType()->getPointerAddressSpace()))) {
4397           LLVM_DEBUG(dbgs()
4398                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4399           BS.cancelScheduling(VL, VL0);
4400           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4401                        ReuseShuffleIndicies);
4402           return;
4403         }
4404       }
4405 
4406       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4407                                    ReuseShuffleIndicies);
4408       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4409       SmallVector<ValueList, 2> Operands(2);
4410       // Prepare the operand vector for pointer operands.
4411       for (Value *V : VL)
4412         Operands.front().push_back(
4413             cast<GetElementPtrInst>(V)->getPointerOperand());
4414       TE->setOperand(0, Operands.front());
4415       // Need to cast all indices to the same type before vectorization to
4416       // avoid crash.
4417       // Required to be able to find correct matches between different gather
4418       // nodes and reuse the vectorized values rather than trying to gather them
4419       // again.
4420       int IndexIdx = 1;
4421       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4422       Type *Ty = all_of(VL,
4423                         [VL0Ty, IndexIdx](Value *V) {
4424                           return VL0Ty == cast<GetElementPtrInst>(V)
4425                                               ->getOperand(IndexIdx)
4426                                               ->getType();
4427                         })
4428                      ? VL0Ty
4429                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4430                                             ->getPointerOperandType()
4431                                             ->getScalarType());
4432       // Prepare the operand vector.
4433       for (Value *V : VL) {
4434         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4435         auto *CI = cast<ConstantInt>(Op);
4436         Operands.back().push_back(ConstantExpr::getIntegerCast(
4437             CI, Ty, CI->getValue().isSignBitSet()));
4438       }
4439       TE->setOperand(IndexIdx, Operands.back());
4440 
4441       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4442         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4443       return;
4444     }
4445     case Instruction::Store: {
4446       // Check if the stores are consecutive or if we need to swizzle them.
4447       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4448       // Avoid types that are padded when being allocated as scalars, while
4449       // being packed together in a vector (such as i1).
4450       if (DL->getTypeSizeInBits(ScalarTy) !=
4451           DL->getTypeAllocSizeInBits(ScalarTy)) {
4452         BS.cancelScheduling(VL, VL0);
4453         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4454                      ReuseShuffleIndicies);
4455         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4456         return;
4457       }
4458       // Make sure all stores in the bundle are simple - we can't vectorize
4459       // atomic or volatile stores.
4460       SmallVector<Value *, 4> PointerOps(VL.size());
4461       ValueList Operands(VL.size());
4462       auto POIter = PointerOps.begin();
4463       auto OIter = Operands.begin();
4464       for (Value *V : VL) {
4465         auto *SI = cast<StoreInst>(V);
4466         if (!SI->isSimple()) {
4467           BS.cancelScheduling(VL, VL0);
4468           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4469                        ReuseShuffleIndicies);
4470           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4471           return;
4472         }
4473         *POIter = SI->getPointerOperand();
4474         *OIter = SI->getValueOperand();
4475         ++POIter;
4476         ++OIter;
4477       }
4478 
4479       OrdersType CurrentOrder;
4480       // Check the order of pointer operands.
4481       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4482         Value *Ptr0;
4483         Value *PtrN;
4484         if (CurrentOrder.empty()) {
4485           Ptr0 = PointerOps.front();
4486           PtrN = PointerOps.back();
4487         } else {
4488           Ptr0 = PointerOps[CurrentOrder.front()];
4489           PtrN = PointerOps[CurrentOrder.back()];
4490         }
4491         Optional<int> Dist =
4492             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4493         // Check that the sorted pointer operands are consecutive.
4494         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4495           if (CurrentOrder.empty()) {
4496             // Original stores are consecutive and does not require reordering.
4497             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4498                                          UserTreeIdx, ReuseShuffleIndicies);
4499             TE->setOperandsInOrder();
4500             buildTree_rec(Operands, Depth + 1, {TE, 0});
4501             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4502           } else {
4503             fixupOrderingIndices(CurrentOrder);
4504             TreeEntry *TE =
4505                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4506                              ReuseShuffleIndicies, CurrentOrder);
4507             TE->setOperandsInOrder();
4508             buildTree_rec(Operands, Depth + 1, {TE, 0});
4509             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4510           }
4511           return;
4512         }
4513       }
4514 
4515       BS.cancelScheduling(VL, VL0);
4516       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4517                    ReuseShuffleIndicies);
4518       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4519       return;
4520     }
4521     case Instruction::Call: {
4522       // Check if the calls are all to the same vectorizable intrinsic or
4523       // library function.
4524       CallInst *CI = cast<CallInst>(VL0);
4525       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4526 
4527       VFShape Shape = VFShape::get(
4528           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4529           false /*HasGlobalPred*/);
4530       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4531 
4532       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4533         BS.cancelScheduling(VL, VL0);
4534         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4535                      ReuseShuffleIndicies);
4536         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4537         return;
4538       }
4539       Function *F = CI->getCalledFunction();
4540       unsigned NumArgs = CI->arg_size();
4541       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4542       for (unsigned j = 0; j != NumArgs; ++j)
4543         if (hasVectorInstrinsicScalarOpd(ID, j))
4544           ScalarArgs[j] = CI->getArgOperand(j);
4545       for (Value *V : VL) {
4546         CallInst *CI2 = dyn_cast<CallInst>(V);
4547         if (!CI2 || CI2->getCalledFunction() != F ||
4548             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4549             (VecFunc &&
4550              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4551             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4552           BS.cancelScheduling(VL, VL0);
4553           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4554                        ReuseShuffleIndicies);
4555           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4556                             << "\n");
4557           return;
4558         }
4559         // Some intrinsics have scalar arguments and should be same in order for
4560         // them to be vectorized.
4561         for (unsigned j = 0; j != NumArgs; ++j) {
4562           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4563             Value *A1J = CI2->getArgOperand(j);
4564             if (ScalarArgs[j] != A1J) {
4565               BS.cancelScheduling(VL, VL0);
4566               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4567                            ReuseShuffleIndicies);
4568               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4569                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4570                                 << "\n");
4571               return;
4572             }
4573           }
4574         }
4575         // Verify that the bundle operands are identical between the two calls.
4576         if (CI->hasOperandBundles() &&
4577             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4578                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4579                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4580           BS.cancelScheduling(VL, VL0);
4581           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4582                        ReuseShuffleIndicies);
4583           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4584                             << *CI << "!=" << *V << '\n');
4585           return;
4586         }
4587       }
4588 
4589       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4590                                    ReuseShuffleIndicies);
4591       TE->setOperandsInOrder();
4592       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4593         // For scalar operands no need to to create an entry since no need to
4594         // vectorize it.
4595         if (hasVectorInstrinsicScalarOpd(ID, i))
4596           continue;
4597         ValueList Operands;
4598         // Prepare the operand vector.
4599         for (Value *V : VL) {
4600           auto *CI2 = cast<CallInst>(V);
4601           Operands.push_back(CI2->getArgOperand(i));
4602         }
4603         buildTree_rec(Operands, Depth + 1, {TE, i});
4604       }
4605       return;
4606     }
4607     case Instruction::ShuffleVector: {
4608       // If this is not an alternate sequence of opcode like add-sub
4609       // then do not vectorize this instruction.
4610       if (!S.isAltShuffle()) {
4611         BS.cancelScheduling(VL, VL0);
4612         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4613                      ReuseShuffleIndicies);
4614         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4615         return;
4616       }
4617       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4618                                    ReuseShuffleIndicies);
4619       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4620 
4621       // Reorder operands if reordering would enable vectorization.
4622       auto *CI = dyn_cast<CmpInst>(VL0);
4623       if (isa<BinaryOperator>(VL0) || CI) {
4624         ValueList Left, Right;
4625         if (!CI || all_of(VL, [](Value *V) {
4626               return cast<CmpInst>(V)->isCommutative();
4627             })) {
4628           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4629         } else {
4630           CmpInst::Predicate P0 = CI->getPredicate();
4631           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4632           assert(P0 != AltP0 &&
4633                  "Expected different main/alternate predicates.");
4634           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4635           Value *BaseOp0 = VL0->getOperand(0);
4636           Value *BaseOp1 = VL0->getOperand(1);
4637           // Collect operands - commute if it uses the swapped predicate or
4638           // alternate operation.
4639           for (Value *V : VL) {
4640             auto *Cmp = cast<CmpInst>(V);
4641             Value *LHS = Cmp->getOperand(0);
4642             Value *RHS = Cmp->getOperand(1);
4643             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4644             if (P0 == AltP0Swapped) {
4645               if (CI != Cmp && S.AltOp != Cmp &&
4646                   ((P0 == CurrentPred &&
4647                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4648                    (AltP0 == CurrentPred &&
4649                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4650                 std::swap(LHS, RHS);
4651             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4652               std::swap(LHS, RHS);
4653             }
4654             Left.push_back(LHS);
4655             Right.push_back(RHS);
4656           }
4657         }
4658         TE->setOperand(0, Left);
4659         TE->setOperand(1, Right);
4660         buildTree_rec(Left, Depth + 1, {TE, 0});
4661         buildTree_rec(Right, Depth + 1, {TE, 1});
4662         return;
4663       }
4664 
4665       TE->setOperandsInOrder();
4666       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4667         ValueList Operands;
4668         // Prepare the operand vector.
4669         for (Value *V : VL)
4670           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4671 
4672         buildTree_rec(Operands, Depth + 1, {TE, i});
4673       }
4674       return;
4675     }
4676     default:
4677       BS.cancelScheduling(VL, VL0);
4678       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4679                    ReuseShuffleIndicies);
4680       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4681       return;
4682   }
4683 }
4684 
4685 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4686   unsigned N = 1;
4687   Type *EltTy = T;
4688 
4689   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4690          isa<VectorType>(EltTy)) {
4691     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4692       // Check that struct is homogeneous.
4693       for (const auto *Ty : ST->elements())
4694         if (Ty != *ST->element_begin())
4695           return 0;
4696       N *= ST->getNumElements();
4697       EltTy = *ST->element_begin();
4698     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4699       N *= AT->getNumElements();
4700       EltTy = AT->getElementType();
4701     } else {
4702       auto *VT = cast<FixedVectorType>(EltTy);
4703       N *= VT->getNumElements();
4704       EltTy = VT->getElementType();
4705     }
4706   }
4707 
4708   if (!isValidElementType(EltTy))
4709     return 0;
4710   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4711   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4712     return 0;
4713   return N;
4714 }
4715 
4716 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4717                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4718   const auto *It = find_if(VL, [](Value *V) {
4719     return isa<ExtractElementInst, ExtractValueInst>(V);
4720   });
4721   assert(It != VL.end() && "Expected at least one extract instruction.");
4722   auto *E0 = cast<Instruction>(*It);
4723   assert(all_of(VL,
4724                 [](Value *V) {
4725                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4726                       V);
4727                 }) &&
4728          "Invalid opcode");
4729   // Check if all of the extracts come from the same vector and from the
4730   // correct offset.
4731   Value *Vec = E0->getOperand(0);
4732 
4733   CurrentOrder.clear();
4734 
4735   // We have to extract from a vector/aggregate with the same number of elements.
4736   unsigned NElts;
4737   if (E0->getOpcode() == Instruction::ExtractValue) {
4738     const DataLayout &DL = E0->getModule()->getDataLayout();
4739     NElts = canMapToVector(Vec->getType(), DL);
4740     if (!NElts)
4741       return false;
4742     // Check if load can be rewritten as load of vector.
4743     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4744     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4745       return false;
4746   } else {
4747     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4748   }
4749 
4750   if (NElts != VL.size())
4751     return false;
4752 
4753   // Check that all of the indices extract from the correct offset.
4754   bool ShouldKeepOrder = true;
4755   unsigned E = VL.size();
4756   // Assign to all items the initial value E + 1 so we can check if the extract
4757   // instruction index was used already.
4758   // Also, later we can check that all the indices are used and we have a
4759   // consecutive access in the extract instructions, by checking that no
4760   // element of CurrentOrder still has value E + 1.
4761   CurrentOrder.assign(E, E);
4762   unsigned I = 0;
4763   for (; I < E; ++I) {
4764     auto *Inst = dyn_cast<Instruction>(VL[I]);
4765     if (!Inst)
4766       continue;
4767     if (Inst->getOperand(0) != Vec)
4768       break;
4769     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4770       if (isa<UndefValue>(EE->getIndexOperand()))
4771         continue;
4772     Optional<unsigned> Idx = getExtractIndex(Inst);
4773     if (!Idx)
4774       break;
4775     const unsigned ExtIdx = *Idx;
4776     if (ExtIdx != I) {
4777       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4778         break;
4779       ShouldKeepOrder = false;
4780       CurrentOrder[ExtIdx] = I;
4781     } else {
4782       if (CurrentOrder[I] != E)
4783         break;
4784       CurrentOrder[I] = I;
4785     }
4786   }
4787   if (I < E) {
4788     CurrentOrder.clear();
4789     return false;
4790   }
4791   if (ShouldKeepOrder)
4792     CurrentOrder.clear();
4793 
4794   return ShouldKeepOrder;
4795 }
4796 
4797 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4798                                     ArrayRef<Value *> VectorizedVals) const {
4799   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4800          all_of(I->users(), [this](User *U) {
4801            return ScalarToTreeEntry.count(U) > 0 ||
4802                   isVectorLikeInstWithConstOps(U) ||
4803                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4804          });
4805 }
4806 
4807 static std::pair<InstructionCost, InstructionCost>
4808 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4809                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4810   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4811 
4812   // Calculate the cost of the scalar and vector calls.
4813   SmallVector<Type *, 4> VecTys;
4814   for (Use &Arg : CI->args())
4815     VecTys.push_back(
4816         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4817   FastMathFlags FMF;
4818   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4819     FMF = FPCI->getFastMathFlags();
4820   SmallVector<const Value *> Arguments(CI->args());
4821   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4822                                     dyn_cast<IntrinsicInst>(CI));
4823   auto IntrinsicCost =
4824     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4825 
4826   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4827                                      VecTy->getNumElements())),
4828                             false /*HasGlobalPred*/);
4829   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4830   auto LibCost = IntrinsicCost;
4831   if (!CI->isNoBuiltin() && VecFunc) {
4832     // Calculate the cost of the vector library call.
4833     // If the corresponding vector call is cheaper, return its cost.
4834     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4835                                     TTI::TCK_RecipThroughput);
4836   }
4837   return {IntrinsicCost, LibCost};
4838 }
4839 
4840 /// Compute the cost of creating a vector of type \p VecTy containing the
4841 /// extracted values from \p VL.
4842 static InstructionCost
4843 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4844                    TargetTransformInfo::ShuffleKind ShuffleKind,
4845                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4846   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4847 
4848   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4849       VecTy->getNumElements() < NumOfParts)
4850     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4851 
4852   bool AllConsecutive = true;
4853   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4854   unsigned Idx = -1;
4855   InstructionCost Cost = 0;
4856 
4857   // Process extracts in blocks of EltsPerVector to check if the source vector
4858   // operand can be re-used directly. If not, add the cost of creating a shuffle
4859   // to extract the values into a vector register.
4860   for (auto *V : VL) {
4861     ++Idx;
4862 
4863     // Need to exclude undefs from analysis.
4864     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4865       continue;
4866 
4867     // Reached the start of a new vector registers.
4868     if (Idx % EltsPerVector == 0) {
4869       AllConsecutive = true;
4870       continue;
4871     }
4872 
4873     // Check all extracts for a vector register on the target directly
4874     // extract values in order.
4875     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4876     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4877       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4878       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4879                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4880     }
4881 
4882     if (AllConsecutive)
4883       continue;
4884 
4885     // Skip all indices, except for the last index per vector block.
4886     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4887       continue;
4888 
4889     // If we have a series of extracts which are not consecutive and hence
4890     // cannot re-use the source vector register directly, compute the shuffle
4891     // cost to extract the a vector with EltsPerVector elements.
4892     Cost += TTI.getShuffleCost(
4893         TargetTransformInfo::SK_PermuteSingleSrc,
4894         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4895   }
4896   return Cost;
4897 }
4898 
4899 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4900 /// operations operands.
4901 static void
4902 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4903                       ArrayRef<int> ReusesIndices,
4904                       const function_ref<bool(Instruction *)> IsAltOp,
4905                       SmallVectorImpl<int> &Mask,
4906                       SmallVectorImpl<Value *> *OpScalars = nullptr,
4907                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
4908   unsigned Sz = VL.size();
4909   Mask.assign(Sz, UndefMaskElem);
4910   SmallVector<int> OrderMask;
4911   if (!ReorderIndices.empty())
4912     inversePermutation(ReorderIndices, OrderMask);
4913   for (unsigned I = 0; I < Sz; ++I) {
4914     unsigned Idx = I;
4915     if (!ReorderIndices.empty())
4916       Idx = OrderMask[I];
4917     auto *OpInst = cast<Instruction>(VL[Idx]);
4918     if (IsAltOp(OpInst)) {
4919       Mask[I] = Sz + Idx;
4920       if (AltScalars)
4921         AltScalars->push_back(OpInst);
4922     } else {
4923       Mask[I] = Idx;
4924       if (OpScalars)
4925         OpScalars->push_back(OpInst);
4926     }
4927   }
4928   if (!ReusesIndices.empty()) {
4929     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4930     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4931       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4932     });
4933     Mask.swap(NewMask);
4934   }
4935 }
4936 
4937 /// Checks if the specified instruction \p I is an alternate operation for the
4938 /// given \p MainOp and \p AltOp instructions.
4939 static bool isAlternateInstruction(const Instruction *I,
4940                                    const Instruction *MainOp,
4941                                    const Instruction *AltOp) {
4942   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
4943     auto *AltCI0 = cast<CmpInst>(AltOp);
4944     auto *CI = cast<CmpInst>(I);
4945     CmpInst::Predicate P0 = CI0->getPredicate();
4946     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
4947     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
4948     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4949     CmpInst::Predicate CurrentPred = CI->getPredicate();
4950     if (P0 == AltP0Swapped)
4951       return I == AltCI0 ||
4952              (I != MainOp &&
4953               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
4954                                    CI->getOperand(0), CI->getOperand(1)));
4955     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
4956   }
4957   return I->getOpcode() == AltOp->getOpcode();
4958 }
4959 
4960 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4961                                       ArrayRef<Value *> VectorizedVals) {
4962   ArrayRef<Value*> VL = E->Scalars;
4963 
4964   Type *ScalarTy = VL[0]->getType();
4965   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4966     ScalarTy = SI->getValueOperand()->getType();
4967   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4968     ScalarTy = CI->getOperand(0)->getType();
4969   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4970     ScalarTy = IE->getOperand(1)->getType();
4971   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4972   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4973 
4974   // If we have computed a smaller type for the expression, update VecTy so
4975   // that the costs will be accurate.
4976   if (MinBWs.count(VL[0]))
4977     VecTy = FixedVectorType::get(
4978         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4979   unsigned EntryVF = E->getVectorFactor();
4980   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4981 
4982   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4983   // FIXME: it tries to fix a problem with MSVC buildbots.
4984   TargetTransformInfo &TTIRef = *TTI;
4985   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4986                                VectorizedVals, E](InstructionCost &Cost) {
4987     DenseMap<Value *, int> ExtractVectorsTys;
4988     SmallPtrSet<Value *, 4> CheckedExtracts;
4989     for (auto *V : VL) {
4990       if (isa<UndefValue>(V))
4991         continue;
4992       // If all users of instruction are going to be vectorized and this
4993       // instruction itself is not going to be vectorized, consider this
4994       // instruction as dead and remove its cost from the final cost of the
4995       // vectorized tree.
4996       // Also, avoid adjusting the cost for extractelements with multiple uses
4997       // in different graph entries.
4998       const TreeEntry *VE = getTreeEntry(V);
4999       if (!CheckedExtracts.insert(V).second ||
5000           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5001           (VE && VE != E))
5002         continue;
5003       auto *EE = cast<ExtractElementInst>(V);
5004       Optional<unsigned> EEIdx = getExtractIndex(EE);
5005       if (!EEIdx)
5006         continue;
5007       unsigned Idx = *EEIdx;
5008       if (TTIRef.getNumberOfParts(VecTy) !=
5009           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5010         auto It =
5011             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5012         It->getSecond() = std::min<int>(It->second, Idx);
5013       }
5014       // Take credit for instruction that will become dead.
5015       if (EE->hasOneUse()) {
5016         Instruction *Ext = EE->user_back();
5017         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5018             all_of(Ext->users(),
5019                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5020           // Use getExtractWithExtendCost() to calculate the cost of
5021           // extractelement/ext pair.
5022           Cost -=
5023               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5024                                               EE->getVectorOperandType(), Idx);
5025           // Add back the cost of s|zext which is subtracted separately.
5026           Cost += TTIRef.getCastInstrCost(
5027               Ext->getOpcode(), Ext->getType(), EE->getType(),
5028               TTI::getCastContextHint(Ext), CostKind, Ext);
5029           continue;
5030         }
5031       }
5032       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5033                                         EE->getVectorOperandType(), Idx);
5034     }
5035     // Add a cost for subvector extracts/inserts if required.
5036     for (const auto &Data : ExtractVectorsTys) {
5037       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5038       unsigned NumElts = VecTy->getNumElements();
5039       if (Data.second % NumElts == 0)
5040         continue;
5041       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5042         unsigned Idx = (Data.second / NumElts) * NumElts;
5043         unsigned EENumElts = EEVTy->getNumElements();
5044         if (Idx + NumElts <= EENumElts) {
5045           Cost +=
5046               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5047                                     EEVTy, None, Idx, VecTy);
5048         } else {
5049           // Need to round up the subvector type vectorization factor to avoid a
5050           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5051           // <= EENumElts.
5052           auto *SubVT =
5053               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5054           Cost +=
5055               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5056                                     EEVTy, None, Idx, SubVT);
5057         }
5058       } else {
5059         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5060                                       VecTy, None, 0, EEVTy);
5061       }
5062     }
5063   };
5064   if (E->State == TreeEntry::NeedToGather) {
5065     if (allConstant(VL))
5066       return 0;
5067     if (isa<InsertElementInst>(VL[0]))
5068       return InstructionCost::getInvalid();
5069     SmallVector<int> Mask;
5070     SmallVector<const TreeEntry *> Entries;
5071     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5072         isGatherShuffledEntry(E, Mask, Entries);
5073     if (Shuffle.hasValue()) {
5074       InstructionCost GatherCost = 0;
5075       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5076         // Perfect match in the graph, will reuse the previously vectorized
5077         // node. Cost is 0.
5078         LLVM_DEBUG(
5079             dbgs()
5080             << "SLP: perfect diamond match for gather bundle that starts with "
5081             << *VL.front() << ".\n");
5082         if (NeedToShuffleReuses)
5083           GatherCost =
5084               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5085                                   FinalVecTy, E->ReuseShuffleIndices);
5086       } else {
5087         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5088                           << " entries for bundle that starts with "
5089                           << *VL.front() << ".\n");
5090         // Detected that instead of gather we can emit a shuffle of single/two
5091         // previously vectorized nodes. Add the cost of the permutation rather
5092         // than gather.
5093         ::addMask(Mask, E->ReuseShuffleIndices);
5094         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5095       }
5096       return GatherCost;
5097     }
5098     if ((E->getOpcode() == Instruction::ExtractElement ||
5099          all_of(E->Scalars,
5100                 [](Value *V) {
5101                   return isa<ExtractElementInst, UndefValue>(V);
5102                 })) &&
5103         allSameType(VL)) {
5104       // Check that gather of extractelements can be represented as just a
5105       // shuffle of a single/two vectors the scalars are extracted from.
5106       SmallVector<int> Mask;
5107       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5108           isFixedVectorShuffle(VL, Mask);
5109       if (ShuffleKind.hasValue()) {
5110         // Found the bunch of extractelement instructions that must be gathered
5111         // into a vector and can be represented as a permutation elements in a
5112         // single input vector or of 2 input vectors.
5113         InstructionCost Cost =
5114             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5115         AdjustExtractsCost(Cost);
5116         if (NeedToShuffleReuses)
5117           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5118                                       FinalVecTy, E->ReuseShuffleIndices);
5119         return Cost;
5120       }
5121     }
5122     if (isSplat(VL)) {
5123       // Found the broadcasting of the single scalar, calculate the cost as the
5124       // broadcast.
5125       assert(VecTy == FinalVecTy &&
5126              "No reused scalars expected for broadcast.");
5127       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5128     }
5129     InstructionCost ReuseShuffleCost = 0;
5130     if (NeedToShuffleReuses)
5131       ReuseShuffleCost = TTI->getShuffleCost(
5132           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5133     // Improve gather cost for gather of loads, if we can group some of the
5134     // loads into vector loads.
5135     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5136         !E->isAltShuffle()) {
5137       BoUpSLP::ValueSet VectorizedLoads;
5138       unsigned StartIdx = 0;
5139       unsigned VF = VL.size() / 2;
5140       unsigned VectorizedCnt = 0;
5141       unsigned ScatterVectorizeCnt = 0;
5142       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5143       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5144         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5145              Cnt += VF) {
5146           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5147           if (!VectorizedLoads.count(Slice.front()) &&
5148               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5149             SmallVector<Value *> PointerOps;
5150             OrdersType CurrentOrder;
5151             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5152                                               *SE, CurrentOrder, PointerOps);
5153             switch (LS) {
5154             case LoadsState::Vectorize:
5155             case LoadsState::ScatterVectorize:
5156               // Mark the vectorized loads so that we don't vectorize them
5157               // again.
5158               if (LS == LoadsState::Vectorize)
5159                 ++VectorizedCnt;
5160               else
5161                 ++ScatterVectorizeCnt;
5162               VectorizedLoads.insert(Slice.begin(), Slice.end());
5163               // If we vectorized initial block, no need to try to vectorize it
5164               // again.
5165               if (Cnt == StartIdx)
5166                 StartIdx += VF;
5167               break;
5168             case LoadsState::Gather:
5169               break;
5170             }
5171           }
5172         }
5173         // Check if the whole array was vectorized already - exit.
5174         if (StartIdx >= VL.size())
5175           break;
5176         // Found vectorizable parts - exit.
5177         if (!VectorizedLoads.empty())
5178           break;
5179       }
5180       if (!VectorizedLoads.empty()) {
5181         InstructionCost GatherCost = 0;
5182         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5183         bool NeedInsertSubvectorAnalysis =
5184             !NumParts || (VL.size() / VF) > NumParts;
5185         // Get the cost for gathered loads.
5186         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5187           if (VectorizedLoads.contains(VL[I]))
5188             continue;
5189           GatherCost += getGatherCost(VL.slice(I, VF));
5190         }
5191         // The cost for vectorized loads.
5192         InstructionCost ScalarsCost = 0;
5193         for (Value *V : VectorizedLoads) {
5194           auto *LI = cast<LoadInst>(V);
5195           ScalarsCost += TTI->getMemoryOpCost(
5196               Instruction::Load, LI->getType(), LI->getAlign(),
5197               LI->getPointerAddressSpace(), CostKind, LI);
5198         }
5199         auto *LI = cast<LoadInst>(E->getMainOp());
5200         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5201         Align Alignment = LI->getAlign();
5202         GatherCost +=
5203             VectorizedCnt *
5204             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5205                                  LI->getPointerAddressSpace(), CostKind, LI);
5206         GatherCost += ScatterVectorizeCnt *
5207                       TTI->getGatherScatterOpCost(
5208                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5209                           /*VariableMask=*/false, Alignment, CostKind, LI);
5210         if (NeedInsertSubvectorAnalysis) {
5211           // Add the cost for the subvectors insert.
5212           for (int I = VF, E = VL.size(); I < E; I += VF)
5213             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5214                                               None, I, LoadTy);
5215         }
5216         return ReuseShuffleCost + GatherCost - ScalarsCost;
5217       }
5218     }
5219     return ReuseShuffleCost + getGatherCost(VL);
5220   }
5221   InstructionCost CommonCost = 0;
5222   SmallVector<int> Mask;
5223   if (!E->ReorderIndices.empty()) {
5224     SmallVector<int> NewMask;
5225     if (E->getOpcode() == Instruction::Store) {
5226       // For stores the order is actually a mask.
5227       NewMask.resize(E->ReorderIndices.size());
5228       copy(E->ReorderIndices, NewMask.begin());
5229     } else {
5230       inversePermutation(E->ReorderIndices, NewMask);
5231     }
5232     ::addMask(Mask, NewMask);
5233   }
5234   if (NeedToShuffleReuses)
5235     ::addMask(Mask, E->ReuseShuffleIndices);
5236   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5237     CommonCost =
5238         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5239   assert((E->State == TreeEntry::Vectorize ||
5240           E->State == TreeEntry::ScatterVectorize) &&
5241          "Unhandled state");
5242   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5243   Instruction *VL0 = E->getMainOp();
5244   unsigned ShuffleOrOp =
5245       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5246   switch (ShuffleOrOp) {
5247     case Instruction::PHI:
5248       return 0;
5249 
5250     case Instruction::ExtractValue:
5251     case Instruction::ExtractElement: {
5252       // The common cost of removal ExtractElement/ExtractValue instructions +
5253       // the cost of shuffles, if required to resuffle the original vector.
5254       if (NeedToShuffleReuses) {
5255         unsigned Idx = 0;
5256         for (unsigned I : E->ReuseShuffleIndices) {
5257           if (ShuffleOrOp == Instruction::ExtractElement) {
5258             auto *EE = cast<ExtractElementInst>(VL[I]);
5259             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5260                                                   EE->getVectorOperandType(),
5261                                                   *getExtractIndex(EE));
5262           } else {
5263             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5264                                                   VecTy, Idx);
5265             ++Idx;
5266           }
5267         }
5268         Idx = EntryVF;
5269         for (Value *V : VL) {
5270           if (ShuffleOrOp == Instruction::ExtractElement) {
5271             auto *EE = cast<ExtractElementInst>(V);
5272             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5273                                                   EE->getVectorOperandType(),
5274                                                   *getExtractIndex(EE));
5275           } else {
5276             --Idx;
5277             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5278                                                   VecTy, Idx);
5279           }
5280         }
5281       }
5282       if (ShuffleOrOp == Instruction::ExtractValue) {
5283         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5284           auto *EI = cast<Instruction>(VL[I]);
5285           // Take credit for instruction that will become dead.
5286           if (EI->hasOneUse()) {
5287             Instruction *Ext = EI->user_back();
5288             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5289                 all_of(Ext->users(),
5290                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5291               // Use getExtractWithExtendCost() to calculate the cost of
5292               // extractelement/ext pair.
5293               CommonCost -= TTI->getExtractWithExtendCost(
5294                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5295               // Add back the cost of s|zext which is subtracted separately.
5296               CommonCost += TTI->getCastInstrCost(
5297                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5298                   TTI::getCastContextHint(Ext), CostKind, Ext);
5299               continue;
5300             }
5301           }
5302           CommonCost -=
5303               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5304         }
5305       } else {
5306         AdjustExtractsCost(CommonCost);
5307       }
5308       return CommonCost;
5309     }
5310     case Instruction::InsertElement: {
5311       assert(E->ReuseShuffleIndices.empty() &&
5312              "Unique insertelements only are expected.");
5313       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5314 
5315       unsigned const NumElts = SrcVecTy->getNumElements();
5316       unsigned const NumScalars = VL.size();
5317       APInt DemandedElts = APInt::getZero(NumElts);
5318       // TODO: Add support for Instruction::InsertValue.
5319       SmallVector<int> Mask;
5320       if (!E->ReorderIndices.empty()) {
5321         inversePermutation(E->ReorderIndices, Mask);
5322         Mask.append(NumElts - NumScalars, UndefMaskElem);
5323       } else {
5324         Mask.assign(NumElts, UndefMaskElem);
5325         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5326       }
5327       unsigned Offset = *getInsertIndex(VL0);
5328       bool IsIdentity = true;
5329       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5330       Mask.swap(PrevMask);
5331       for (unsigned I = 0; I < NumScalars; ++I) {
5332         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5333         DemandedElts.setBit(InsertIdx);
5334         IsIdentity &= InsertIdx - Offset == I;
5335         Mask[InsertIdx - Offset] = I;
5336       }
5337       assert(Offset < NumElts && "Failed to find vector index offset");
5338 
5339       InstructionCost Cost = 0;
5340       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5341                                             /*Insert*/ true, /*Extract*/ false);
5342 
5343       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5344         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5345         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5346         Cost += TTI->getShuffleCost(
5347             TargetTransformInfo::SK_PermuteSingleSrc,
5348             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5349       } else if (!IsIdentity) {
5350         auto *FirstInsert =
5351             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5352               return !is_contained(E->Scalars,
5353                                    cast<Instruction>(V)->getOperand(0));
5354             }));
5355         if (isUndefVector(FirstInsert->getOperand(0))) {
5356           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5357         } else {
5358           SmallVector<int> InsertMask(NumElts);
5359           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5360           for (unsigned I = 0; I < NumElts; I++) {
5361             if (Mask[I] != UndefMaskElem)
5362               InsertMask[Offset + I] = NumElts + I;
5363           }
5364           Cost +=
5365               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5366         }
5367       }
5368 
5369       return Cost;
5370     }
5371     case Instruction::ZExt:
5372     case Instruction::SExt:
5373     case Instruction::FPToUI:
5374     case Instruction::FPToSI:
5375     case Instruction::FPExt:
5376     case Instruction::PtrToInt:
5377     case Instruction::IntToPtr:
5378     case Instruction::SIToFP:
5379     case Instruction::UIToFP:
5380     case Instruction::Trunc:
5381     case Instruction::FPTrunc:
5382     case Instruction::BitCast: {
5383       Type *SrcTy = VL0->getOperand(0)->getType();
5384       InstructionCost ScalarEltCost =
5385           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5386                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5387       if (NeedToShuffleReuses) {
5388         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5389       }
5390 
5391       // Calculate the cost of this instruction.
5392       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5393 
5394       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5395       InstructionCost VecCost = 0;
5396       // Check if the values are candidates to demote.
5397       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5398         VecCost = CommonCost + TTI->getCastInstrCost(
5399                                    E->getOpcode(), VecTy, SrcVecTy,
5400                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5401       }
5402       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5403       return VecCost - ScalarCost;
5404     }
5405     case Instruction::FCmp:
5406     case Instruction::ICmp:
5407     case Instruction::Select: {
5408       // Calculate the cost of this instruction.
5409       InstructionCost ScalarEltCost =
5410           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5411                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5412       if (NeedToShuffleReuses) {
5413         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5414       }
5415       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5416       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5417 
5418       // Check if all entries in VL are either compares or selects with compares
5419       // as condition that have the same predicates.
5420       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5421       bool First = true;
5422       for (auto *V : VL) {
5423         CmpInst::Predicate CurrentPred;
5424         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5425         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5426              !match(V, MatchCmp)) ||
5427             (!First && VecPred != CurrentPred)) {
5428           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5429           break;
5430         }
5431         First = false;
5432         VecPred = CurrentPred;
5433       }
5434 
5435       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5436           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5437       // Check if it is possible and profitable to use min/max for selects in
5438       // VL.
5439       //
5440       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5441       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5442         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5443                                           {VecTy, VecTy});
5444         InstructionCost IntrinsicCost =
5445             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5446         // If the selects are the only uses of the compares, they will be dead
5447         // and we can adjust the cost by removing their cost.
5448         if (IntrinsicAndUse.second)
5449           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5450                                                    MaskTy, VecPred, CostKind);
5451         VecCost = std::min(VecCost, IntrinsicCost);
5452       }
5453       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5454       return CommonCost + VecCost - ScalarCost;
5455     }
5456     case Instruction::FNeg:
5457     case Instruction::Add:
5458     case Instruction::FAdd:
5459     case Instruction::Sub:
5460     case Instruction::FSub:
5461     case Instruction::Mul:
5462     case Instruction::FMul:
5463     case Instruction::UDiv:
5464     case Instruction::SDiv:
5465     case Instruction::FDiv:
5466     case Instruction::URem:
5467     case Instruction::SRem:
5468     case Instruction::FRem:
5469     case Instruction::Shl:
5470     case Instruction::LShr:
5471     case Instruction::AShr:
5472     case Instruction::And:
5473     case Instruction::Or:
5474     case Instruction::Xor: {
5475       // Certain instructions can be cheaper to vectorize if they have a
5476       // constant second vector operand.
5477       TargetTransformInfo::OperandValueKind Op1VK =
5478           TargetTransformInfo::OK_AnyValue;
5479       TargetTransformInfo::OperandValueKind Op2VK =
5480           TargetTransformInfo::OK_UniformConstantValue;
5481       TargetTransformInfo::OperandValueProperties Op1VP =
5482           TargetTransformInfo::OP_None;
5483       TargetTransformInfo::OperandValueProperties Op2VP =
5484           TargetTransformInfo::OP_PowerOf2;
5485 
5486       // If all operands are exactly the same ConstantInt then set the
5487       // operand kind to OK_UniformConstantValue.
5488       // If instead not all operands are constants, then set the operand kind
5489       // to OK_AnyValue. If all operands are constants but not the same,
5490       // then set the operand kind to OK_NonUniformConstantValue.
5491       ConstantInt *CInt0 = nullptr;
5492       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5493         const Instruction *I = cast<Instruction>(VL[i]);
5494         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5495         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5496         if (!CInt) {
5497           Op2VK = TargetTransformInfo::OK_AnyValue;
5498           Op2VP = TargetTransformInfo::OP_None;
5499           break;
5500         }
5501         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5502             !CInt->getValue().isPowerOf2())
5503           Op2VP = TargetTransformInfo::OP_None;
5504         if (i == 0) {
5505           CInt0 = CInt;
5506           continue;
5507         }
5508         if (CInt0 != CInt)
5509           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5510       }
5511 
5512       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5513       InstructionCost ScalarEltCost =
5514           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5515                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5516       if (NeedToShuffleReuses) {
5517         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5518       }
5519       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5520       InstructionCost VecCost =
5521           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5522                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5523       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5524       return CommonCost + VecCost - ScalarCost;
5525     }
5526     case Instruction::GetElementPtr: {
5527       TargetTransformInfo::OperandValueKind Op1VK =
5528           TargetTransformInfo::OK_AnyValue;
5529       TargetTransformInfo::OperandValueKind Op2VK =
5530           TargetTransformInfo::OK_UniformConstantValue;
5531 
5532       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5533           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5534       if (NeedToShuffleReuses) {
5535         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5536       }
5537       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5538       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5539           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5540       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5541       return CommonCost + VecCost - ScalarCost;
5542     }
5543     case Instruction::Load: {
5544       // Cost of wide load - cost of scalar loads.
5545       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5546       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5547           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5548       if (NeedToShuffleReuses) {
5549         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5550       }
5551       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5552       InstructionCost VecLdCost;
5553       if (E->State == TreeEntry::Vectorize) {
5554         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5555                                          CostKind, VL0);
5556       } else {
5557         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5558         Align CommonAlignment = Alignment;
5559         for (Value *V : VL)
5560           CommonAlignment =
5561               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5562         VecLdCost = TTI->getGatherScatterOpCost(
5563             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5564             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5565       }
5566       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5567       return CommonCost + VecLdCost - ScalarLdCost;
5568     }
5569     case Instruction::Store: {
5570       // We know that we can merge the stores. Calculate the cost.
5571       bool IsReorder = !E->ReorderIndices.empty();
5572       auto *SI =
5573           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5574       Align Alignment = SI->getAlign();
5575       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5576           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5577       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5578       InstructionCost VecStCost = TTI->getMemoryOpCost(
5579           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5580       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5581       return CommonCost + VecStCost - ScalarStCost;
5582     }
5583     case Instruction::Call: {
5584       CallInst *CI = cast<CallInst>(VL0);
5585       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5586 
5587       // Calculate the cost of the scalar and vector calls.
5588       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5589       InstructionCost ScalarEltCost =
5590           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5591       if (NeedToShuffleReuses) {
5592         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5593       }
5594       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5595 
5596       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5597       InstructionCost VecCallCost =
5598           std::min(VecCallCosts.first, VecCallCosts.second);
5599 
5600       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5601                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5602                         << " for " << *CI << "\n");
5603 
5604       return CommonCost + VecCallCost - ScalarCallCost;
5605     }
5606     case Instruction::ShuffleVector: {
5607       assert(E->isAltShuffle() &&
5608              ((Instruction::isBinaryOp(E->getOpcode()) &&
5609                Instruction::isBinaryOp(E->getAltOpcode())) ||
5610               (Instruction::isCast(E->getOpcode()) &&
5611                Instruction::isCast(E->getAltOpcode())) ||
5612               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5613              "Invalid Shuffle Vector Operand");
5614       InstructionCost ScalarCost = 0;
5615       if (NeedToShuffleReuses) {
5616         for (unsigned Idx : E->ReuseShuffleIndices) {
5617           Instruction *I = cast<Instruction>(VL[Idx]);
5618           CommonCost -= TTI->getInstructionCost(I, CostKind);
5619         }
5620         for (Value *V : VL) {
5621           Instruction *I = cast<Instruction>(V);
5622           CommonCost += TTI->getInstructionCost(I, CostKind);
5623         }
5624       }
5625       for (Value *V : VL) {
5626         Instruction *I = cast<Instruction>(V);
5627         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5628         ScalarCost += TTI->getInstructionCost(I, CostKind);
5629       }
5630       // VecCost is equal to sum of the cost of creating 2 vectors
5631       // and the cost of creating shuffle.
5632       InstructionCost VecCost = 0;
5633       // Try to find the previous shuffle node with the same operands and same
5634       // main/alternate ops.
5635       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5636         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5637           if (TE.get() == E)
5638             break;
5639           if (TE->isAltShuffle() &&
5640               ((TE->getOpcode() == E->getOpcode() &&
5641                 TE->getAltOpcode() == E->getAltOpcode()) ||
5642                (TE->getOpcode() == E->getAltOpcode() &&
5643                 TE->getAltOpcode() == E->getOpcode())) &&
5644               TE->hasEqualOperands(*E))
5645             return true;
5646         }
5647         return false;
5648       };
5649       if (TryFindNodeWithEqualOperands()) {
5650         LLVM_DEBUG({
5651           dbgs() << "SLP: diamond match for alternate node found.\n";
5652           E->dump();
5653         });
5654         // No need to add new vector costs here since we're going to reuse
5655         // same main/alternate vector ops, just do different shuffling.
5656       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5657         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5658         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5659                                                CostKind);
5660       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5661         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5662                                           Builder.getInt1Ty(),
5663                                           CI0->getPredicate(), CostKind, VL0);
5664         VecCost += TTI->getCmpSelInstrCost(
5665             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5666             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5667             E->getAltOp());
5668       } else {
5669         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5670         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5671         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5672         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5673         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5674                                         TTI::CastContextHint::None, CostKind);
5675         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5676                                          TTI::CastContextHint::None, CostKind);
5677       }
5678 
5679       SmallVector<int> Mask;
5680       buildShuffleEntryMask(
5681           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5682           [E](Instruction *I) {
5683             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5684             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5685           },
5686           Mask);
5687       CommonCost =
5688           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5689       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5690       return CommonCost + VecCost - ScalarCost;
5691     }
5692     default:
5693       llvm_unreachable("Unknown instruction");
5694   }
5695 }
5696 
5697 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5698   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5699                     << VectorizableTree.size() << " is fully vectorizable .\n");
5700 
5701   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5702     SmallVector<int> Mask;
5703     return TE->State == TreeEntry::NeedToGather &&
5704            !any_of(TE->Scalars,
5705                    [this](Value *V) { return EphValues.contains(V); }) &&
5706            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5707             TE->Scalars.size() < Limit ||
5708             ((TE->getOpcode() == Instruction::ExtractElement ||
5709               all_of(TE->Scalars,
5710                      [](Value *V) {
5711                        return isa<ExtractElementInst, UndefValue>(V);
5712                      })) &&
5713              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5714             (TE->State == TreeEntry::NeedToGather &&
5715              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5716   };
5717 
5718   // We only handle trees of heights 1 and 2.
5719   if (VectorizableTree.size() == 1 &&
5720       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5721        (ForReduction &&
5722         AreVectorizableGathers(VectorizableTree[0].get(),
5723                                VectorizableTree[0]->Scalars.size()) &&
5724         VectorizableTree[0]->getVectorFactor() > 2)))
5725     return true;
5726 
5727   if (VectorizableTree.size() != 2)
5728     return false;
5729 
5730   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5731   // with the second gather nodes if they have less scalar operands rather than
5732   // the initial tree element (may be profitable to shuffle the second gather)
5733   // or they are extractelements, which form shuffle.
5734   SmallVector<int> Mask;
5735   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5736       AreVectorizableGathers(VectorizableTree[1].get(),
5737                              VectorizableTree[0]->Scalars.size()))
5738     return true;
5739 
5740   // Gathering cost would be too much for tiny trees.
5741   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5742       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5743        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5744     return false;
5745 
5746   return true;
5747 }
5748 
5749 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5750                                        TargetTransformInfo *TTI,
5751                                        bool MustMatchOrInst) {
5752   // Look past the root to find a source value. Arbitrarily follow the
5753   // path through operand 0 of any 'or'. Also, peek through optional
5754   // shift-left-by-multiple-of-8-bits.
5755   Value *ZextLoad = Root;
5756   const APInt *ShAmtC;
5757   bool FoundOr = false;
5758   while (!isa<ConstantExpr>(ZextLoad) &&
5759          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5760           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5761            ShAmtC->urem(8) == 0))) {
5762     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5763     ZextLoad = BinOp->getOperand(0);
5764     if (BinOp->getOpcode() == Instruction::Or)
5765       FoundOr = true;
5766   }
5767   // Check if the input is an extended load of the required or/shift expression.
5768   Value *Load;
5769   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5770       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5771     return false;
5772 
5773   // Require that the total load bit width is a legal integer type.
5774   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5775   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5776   Type *SrcTy = Load->getType();
5777   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5778   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5779     return false;
5780 
5781   // Everything matched - assume that we can fold the whole sequence using
5782   // load combining.
5783   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5784              << *(cast<Instruction>(Root)) << "\n");
5785 
5786   return true;
5787 }
5788 
5789 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5790   if (RdxKind != RecurKind::Or)
5791     return false;
5792 
5793   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5794   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5795   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5796                                     /* MatchOr */ false);
5797 }
5798 
5799 bool BoUpSLP::isLoadCombineCandidate() const {
5800   // Peek through a final sequence of stores and check if all operations are
5801   // likely to be load-combined.
5802   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5803   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5804     Value *X;
5805     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5806         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5807       return false;
5808   }
5809   return true;
5810 }
5811 
5812 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5813   // No need to vectorize inserts of gathered values.
5814   if (VectorizableTree.size() == 2 &&
5815       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5816       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5817     return true;
5818 
5819   // We can vectorize the tree if its size is greater than or equal to the
5820   // minimum size specified by the MinTreeSize command line option.
5821   if (VectorizableTree.size() >= MinTreeSize)
5822     return false;
5823 
5824   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5825   // can vectorize it if we can prove it fully vectorizable.
5826   if (isFullyVectorizableTinyTree(ForReduction))
5827     return false;
5828 
5829   assert(VectorizableTree.empty()
5830              ? ExternalUses.empty()
5831              : true && "We shouldn't have any external users");
5832 
5833   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5834   // vectorizable.
5835   return true;
5836 }
5837 
5838 InstructionCost BoUpSLP::getSpillCost() const {
5839   // Walk from the bottom of the tree to the top, tracking which values are
5840   // live. When we see a call instruction that is not part of our tree,
5841   // query TTI to see if there is a cost to keeping values live over it
5842   // (for example, if spills and fills are required).
5843   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5844   InstructionCost Cost = 0;
5845 
5846   SmallPtrSet<Instruction*, 4> LiveValues;
5847   Instruction *PrevInst = nullptr;
5848 
5849   // The entries in VectorizableTree are not necessarily ordered by their
5850   // position in basic blocks. Collect them and order them by dominance so later
5851   // instructions are guaranteed to be visited first. For instructions in
5852   // different basic blocks, we only scan to the beginning of the block, so
5853   // their order does not matter, as long as all instructions in a basic block
5854   // are grouped together. Using dominance ensures a deterministic order.
5855   SmallVector<Instruction *, 16> OrderedScalars;
5856   for (const auto &TEPtr : VectorizableTree) {
5857     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5858     if (!Inst)
5859       continue;
5860     OrderedScalars.push_back(Inst);
5861   }
5862   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5863     auto *NodeA = DT->getNode(A->getParent());
5864     auto *NodeB = DT->getNode(B->getParent());
5865     assert(NodeA && "Should only process reachable instructions");
5866     assert(NodeB && "Should only process reachable instructions");
5867     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5868            "Different nodes should have different DFS numbers");
5869     if (NodeA != NodeB)
5870       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5871     return B->comesBefore(A);
5872   });
5873 
5874   for (Instruction *Inst : OrderedScalars) {
5875     if (!PrevInst) {
5876       PrevInst = Inst;
5877       continue;
5878     }
5879 
5880     // Update LiveValues.
5881     LiveValues.erase(PrevInst);
5882     for (auto &J : PrevInst->operands()) {
5883       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5884         LiveValues.insert(cast<Instruction>(&*J));
5885     }
5886 
5887     LLVM_DEBUG({
5888       dbgs() << "SLP: #LV: " << LiveValues.size();
5889       for (auto *X : LiveValues)
5890         dbgs() << " " << X->getName();
5891       dbgs() << ", Looking at ";
5892       Inst->dump();
5893     });
5894 
5895     // Now find the sequence of instructions between PrevInst and Inst.
5896     unsigned NumCalls = 0;
5897     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5898                                  PrevInstIt =
5899                                      PrevInst->getIterator().getReverse();
5900     while (InstIt != PrevInstIt) {
5901       if (PrevInstIt == PrevInst->getParent()->rend()) {
5902         PrevInstIt = Inst->getParent()->rbegin();
5903         continue;
5904       }
5905 
5906       // Debug information does not impact spill cost.
5907       if ((isa<CallInst>(&*PrevInstIt) &&
5908            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5909           &*PrevInstIt != PrevInst)
5910         NumCalls++;
5911 
5912       ++PrevInstIt;
5913     }
5914 
5915     if (NumCalls) {
5916       SmallVector<Type*, 4> V;
5917       for (auto *II : LiveValues) {
5918         auto *ScalarTy = II->getType();
5919         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5920           ScalarTy = VectorTy->getElementType();
5921         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5922       }
5923       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5924     }
5925 
5926     PrevInst = Inst;
5927   }
5928 
5929   return Cost;
5930 }
5931 
5932 /// Check if two insertelement instructions are from the same buildvector.
5933 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5934                                             InsertElementInst *V) {
5935   // Instructions must be from the same basic blocks.
5936   if (VU->getParent() != V->getParent())
5937     return false;
5938   // Checks if 2 insertelements are from the same buildvector.
5939   if (VU->getType() != V->getType())
5940     return false;
5941   // Multiple used inserts are separate nodes.
5942   if (!VU->hasOneUse() && !V->hasOneUse())
5943     return false;
5944   auto *IE1 = VU;
5945   auto *IE2 = V;
5946   // Go through the vector operand of insertelement instructions trying to find
5947   // either VU as the original vector for IE2 or V as the original vector for
5948   // IE1.
5949   do {
5950     if (IE2 == VU || IE1 == V)
5951       return true;
5952     if (IE1) {
5953       if (IE1 != VU && !IE1->hasOneUse())
5954         IE1 = nullptr;
5955       else
5956         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5957     }
5958     if (IE2) {
5959       if (IE2 != V && !IE2->hasOneUse())
5960         IE2 = nullptr;
5961       else
5962         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5963     }
5964   } while (IE1 || IE2);
5965   return false;
5966 }
5967 
5968 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5969   InstructionCost Cost = 0;
5970   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5971                     << VectorizableTree.size() << ".\n");
5972 
5973   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5974 
5975   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5976     TreeEntry &TE = *VectorizableTree[I].get();
5977 
5978     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5979     Cost += C;
5980     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5981                       << " for bundle that starts with " << *TE.Scalars[0]
5982                       << ".\n"
5983                       << "SLP: Current total cost = " << Cost << "\n");
5984   }
5985 
5986   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5987   InstructionCost ExtractCost = 0;
5988   SmallVector<unsigned> VF;
5989   SmallVector<SmallVector<int>> ShuffleMask;
5990   SmallVector<Value *> FirstUsers;
5991   SmallVector<APInt> DemandedElts;
5992   for (ExternalUser &EU : ExternalUses) {
5993     // We only add extract cost once for the same scalar.
5994     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5995         !ExtractCostCalculated.insert(EU.Scalar).second)
5996       continue;
5997 
5998     // Uses by ephemeral values are free (because the ephemeral value will be
5999     // removed prior to code generation, and so the extraction will be
6000     // removed as well).
6001     if (EphValues.count(EU.User))
6002       continue;
6003 
6004     // No extract cost for vector "scalar"
6005     if (isa<FixedVectorType>(EU.Scalar->getType()))
6006       continue;
6007 
6008     // Already counted the cost for external uses when tried to adjust the cost
6009     // for extractelements, no need to add it again.
6010     if (isa<ExtractElementInst>(EU.Scalar))
6011       continue;
6012 
6013     // If found user is an insertelement, do not calculate extract cost but try
6014     // to detect it as a final shuffled/identity match.
6015     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6016       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6017         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6018         if (InsertIdx) {
6019           auto *It = find_if(FirstUsers, [VU](Value *V) {
6020             return areTwoInsertFromSameBuildVector(VU,
6021                                                    cast<InsertElementInst>(V));
6022           });
6023           int VecId = -1;
6024           if (It == FirstUsers.end()) {
6025             VF.push_back(FTy->getNumElements());
6026             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6027             // Find the insertvector, vectorized in tree, if any.
6028             Value *Base = VU;
6029             while (isa<InsertElementInst>(Base)) {
6030               // Build the mask for the vectorized insertelement instructions.
6031               if (const TreeEntry *E = getTreeEntry(Base)) {
6032                 VU = cast<InsertElementInst>(Base);
6033                 do {
6034                   int Idx = E->findLaneForValue(Base);
6035                   ShuffleMask.back()[Idx] = Idx;
6036                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6037                 } while (E == getTreeEntry(Base));
6038                 break;
6039               }
6040               Base = cast<InsertElementInst>(Base)->getOperand(0);
6041             }
6042             FirstUsers.push_back(VU);
6043             DemandedElts.push_back(APInt::getZero(VF.back()));
6044             VecId = FirstUsers.size() - 1;
6045           } else {
6046             VecId = std::distance(FirstUsers.begin(), It);
6047           }
6048           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6049           DemandedElts[VecId].setBit(*InsertIdx);
6050           continue;
6051         }
6052       }
6053     }
6054 
6055     // If we plan to rewrite the tree in a smaller type, we will need to sign
6056     // extend the extracted value back to the original type. Here, we account
6057     // for the extract and the added cost of the sign extend if needed.
6058     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6059     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6060     if (MinBWs.count(ScalarRoot)) {
6061       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6062       auto Extend =
6063           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6064       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6065       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6066                                                    VecTy, EU.Lane);
6067     } else {
6068       ExtractCost +=
6069           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6070     }
6071   }
6072 
6073   InstructionCost SpillCost = getSpillCost();
6074   Cost += SpillCost + ExtractCost;
6075   if (FirstUsers.size() == 1) {
6076     int Limit = ShuffleMask.front().size() * 2;
6077     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6078         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6079       InstructionCost C = TTI->getShuffleCost(
6080           TTI::SK_PermuteSingleSrc,
6081           cast<FixedVectorType>(FirstUsers.front()->getType()),
6082           ShuffleMask.front());
6083       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6084                         << " for final shuffle of insertelement external users "
6085                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6086                         << "SLP: Current total cost = " << Cost << "\n");
6087       Cost += C;
6088     }
6089     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6090         cast<FixedVectorType>(FirstUsers.front()->getType()),
6091         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6092     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6093                       << " for insertelements gather.\n"
6094                       << "SLP: Current total cost = " << Cost << "\n");
6095     Cost -= InsertCost;
6096   } else if (FirstUsers.size() >= 2) {
6097     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6098     // Combined masks of the first 2 vectors.
6099     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6100     copy(ShuffleMask.front(), CombinedMask.begin());
6101     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6102     auto *VecTy = FixedVectorType::get(
6103         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6104         MaxVF);
6105     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6106       if (ShuffleMask[1][I] != UndefMaskElem) {
6107         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6108         CombinedDemandedElts.setBit(I);
6109       }
6110     }
6111     InstructionCost C =
6112         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6113     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6114                       << " for final shuffle of vector node and external "
6115                          "insertelement users "
6116                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6117                       << "SLP: Current total cost = " << Cost << "\n");
6118     Cost += C;
6119     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6120         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6121     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6122                       << " for insertelements gather.\n"
6123                       << "SLP: Current total cost = " << Cost << "\n");
6124     Cost -= InsertCost;
6125     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6126       // Other elements - permutation of 2 vectors (the initial one and the
6127       // next Ith incoming vector).
6128       unsigned VF = ShuffleMask[I].size();
6129       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6130         int Mask = ShuffleMask[I][Idx];
6131         if (Mask != UndefMaskElem)
6132           CombinedMask[Idx] = MaxVF + Mask;
6133         else if (CombinedMask[Idx] != UndefMaskElem)
6134           CombinedMask[Idx] = Idx;
6135       }
6136       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6137         if (CombinedMask[Idx] != UndefMaskElem)
6138           CombinedMask[Idx] = Idx;
6139       InstructionCost C =
6140           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6141       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6142                         << " for final shuffle of vector node and external "
6143                            "insertelement users "
6144                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6145                         << "SLP: Current total cost = " << Cost << "\n");
6146       Cost += C;
6147       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6148           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6149           /*Insert*/ true, /*Extract*/ false);
6150       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6151                         << " for insertelements gather.\n"
6152                         << "SLP: Current total cost = " << Cost << "\n");
6153       Cost -= InsertCost;
6154     }
6155   }
6156 
6157 #ifndef NDEBUG
6158   SmallString<256> Str;
6159   {
6160     raw_svector_ostream OS(Str);
6161     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6162        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6163        << "SLP: Total Cost = " << Cost << ".\n";
6164   }
6165   LLVM_DEBUG(dbgs() << Str);
6166   if (ViewSLPTree)
6167     ViewGraph(this, "SLP" + F->getName(), false, Str);
6168 #endif
6169 
6170   return Cost;
6171 }
6172 
6173 Optional<TargetTransformInfo::ShuffleKind>
6174 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6175                                SmallVectorImpl<const TreeEntry *> &Entries) {
6176   // TODO: currently checking only for Scalars in the tree entry, need to count
6177   // reused elements too for better cost estimation.
6178   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6179   Entries.clear();
6180   // Build a lists of values to tree entries.
6181   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6182   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6183     if (EntryPtr.get() == TE)
6184       break;
6185     if (EntryPtr->State != TreeEntry::NeedToGather)
6186       continue;
6187     for (Value *V : EntryPtr->Scalars)
6188       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6189   }
6190   // Find all tree entries used by the gathered values. If no common entries
6191   // found - not a shuffle.
6192   // Here we build a set of tree nodes for each gathered value and trying to
6193   // find the intersection between these sets. If we have at least one common
6194   // tree node for each gathered value - we have just a permutation of the
6195   // single vector. If we have 2 different sets, we're in situation where we
6196   // have a permutation of 2 input vectors.
6197   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6198   DenseMap<Value *, int> UsedValuesEntry;
6199   for (Value *V : TE->Scalars) {
6200     if (isa<UndefValue>(V))
6201       continue;
6202     // Build a list of tree entries where V is used.
6203     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6204     auto It = ValueToTEs.find(V);
6205     if (It != ValueToTEs.end())
6206       VToTEs = It->second;
6207     if (const TreeEntry *VTE = getTreeEntry(V))
6208       VToTEs.insert(VTE);
6209     if (VToTEs.empty())
6210       return None;
6211     if (UsedTEs.empty()) {
6212       // The first iteration, just insert the list of nodes to vector.
6213       UsedTEs.push_back(VToTEs);
6214     } else {
6215       // Need to check if there are any previously used tree nodes which use V.
6216       // If there are no such nodes, consider that we have another one input
6217       // vector.
6218       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6219       unsigned Idx = 0;
6220       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6221         // Do we have a non-empty intersection of previously listed tree entries
6222         // and tree entries using current V?
6223         set_intersect(VToTEs, Set);
6224         if (!VToTEs.empty()) {
6225           // Yes, write the new subset and continue analysis for the next
6226           // scalar.
6227           Set.swap(VToTEs);
6228           break;
6229         }
6230         VToTEs = SavedVToTEs;
6231         ++Idx;
6232       }
6233       // No non-empty intersection found - need to add a second set of possible
6234       // source vectors.
6235       if (Idx == UsedTEs.size()) {
6236         // If the number of input vectors is greater than 2 - not a permutation,
6237         // fallback to the regular gather.
6238         if (UsedTEs.size() == 2)
6239           return None;
6240         UsedTEs.push_back(SavedVToTEs);
6241         Idx = UsedTEs.size() - 1;
6242       }
6243       UsedValuesEntry.try_emplace(V, Idx);
6244     }
6245   }
6246 
6247   unsigned VF = 0;
6248   if (UsedTEs.size() == 1) {
6249     // Try to find the perfect match in another gather node at first.
6250     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6251       return EntryPtr->isSame(TE->Scalars);
6252     });
6253     if (It != UsedTEs.front().end()) {
6254       Entries.push_back(*It);
6255       std::iota(Mask.begin(), Mask.end(), 0);
6256       return TargetTransformInfo::SK_PermuteSingleSrc;
6257     }
6258     // No perfect match, just shuffle, so choose the first tree node.
6259     Entries.push_back(*UsedTEs.front().begin());
6260   } else {
6261     // Try to find nodes with the same vector factor.
6262     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6263     DenseMap<int, const TreeEntry *> VFToTE;
6264     for (const TreeEntry *TE : UsedTEs.front())
6265       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6266     for (const TreeEntry *TE : UsedTEs.back()) {
6267       auto It = VFToTE.find(TE->getVectorFactor());
6268       if (It != VFToTE.end()) {
6269         VF = It->first;
6270         Entries.push_back(It->second);
6271         Entries.push_back(TE);
6272         break;
6273       }
6274     }
6275     // No 2 source vectors with the same vector factor - give up and do regular
6276     // gather.
6277     if (Entries.empty())
6278       return None;
6279   }
6280 
6281   // Build a shuffle mask for better cost estimation and vector emission.
6282   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6283     Value *V = TE->Scalars[I];
6284     if (isa<UndefValue>(V))
6285       continue;
6286     unsigned Idx = UsedValuesEntry.lookup(V);
6287     const TreeEntry *VTE = Entries[Idx];
6288     int FoundLane = VTE->findLaneForValue(V);
6289     Mask[I] = Idx * VF + FoundLane;
6290     // Extra check required by isSingleSourceMaskImpl function (called by
6291     // ShuffleVectorInst::isSingleSourceMask).
6292     if (Mask[I] >= 2 * E)
6293       return None;
6294   }
6295   switch (Entries.size()) {
6296   case 1:
6297     return TargetTransformInfo::SK_PermuteSingleSrc;
6298   case 2:
6299     return TargetTransformInfo::SK_PermuteTwoSrc;
6300   default:
6301     break;
6302   }
6303   return None;
6304 }
6305 
6306 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6307                                        const APInt &ShuffledIndices,
6308                                        bool NeedToShuffle) const {
6309   InstructionCost Cost =
6310       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6311                                     /*Extract*/ false);
6312   if (NeedToShuffle)
6313     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6314   return Cost;
6315 }
6316 
6317 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6318   // Find the type of the operands in VL.
6319   Type *ScalarTy = VL[0]->getType();
6320   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6321     ScalarTy = SI->getValueOperand()->getType();
6322   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6323   bool DuplicateNonConst = false;
6324   // Find the cost of inserting/extracting values from the vector.
6325   // Check if the same elements are inserted several times and count them as
6326   // shuffle candidates.
6327   APInt ShuffledElements = APInt::getZero(VL.size());
6328   DenseSet<Value *> UniqueElements;
6329   // Iterate in reverse order to consider insert elements with the high cost.
6330   for (unsigned I = VL.size(); I > 0; --I) {
6331     unsigned Idx = I - 1;
6332     // No need to shuffle duplicates for constants.
6333     if (isConstant(VL[Idx])) {
6334       ShuffledElements.setBit(Idx);
6335       continue;
6336     }
6337     if (!UniqueElements.insert(VL[Idx]).second) {
6338       DuplicateNonConst = true;
6339       ShuffledElements.setBit(Idx);
6340     }
6341   }
6342   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6343 }
6344 
6345 // Perform operand reordering on the instructions in VL and return the reordered
6346 // operands in Left and Right.
6347 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6348                                              SmallVectorImpl<Value *> &Left,
6349                                              SmallVectorImpl<Value *> &Right,
6350                                              const DataLayout &DL,
6351                                              ScalarEvolution &SE,
6352                                              const BoUpSLP &R) {
6353   if (VL.empty())
6354     return;
6355   VLOperands Ops(VL, DL, SE, R);
6356   // Reorder the operands in place.
6357   Ops.reorder();
6358   Left = Ops.getVL(0);
6359   Right = Ops.getVL(1);
6360 }
6361 
6362 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6363   // Get the basic block this bundle is in. All instructions in the bundle
6364   // should be in this block.
6365   auto *Front = E->getMainOp();
6366   auto *BB = Front->getParent();
6367   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6368     auto *I = cast<Instruction>(V);
6369     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6370   }));
6371 
6372   // The last instruction in the bundle in program order.
6373   Instruction *LastInst = nullptr;
6374 
6375   // Find the last instruction. The common case should be that BB has been
6376   // scheduled, and the last instruction is VL.back(). So we start with
6377   // VL.back() and iterate over schedule data until we reach the end of the
6378   // bundle. The end of the bundle is marked by null ScheduleData.
6379   if (BlocksSchedules.count(BB)) {
6380     auto *Bundle =
6381         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6382     if (Bundle && Bundle->isPartOfBundle())
6383       for (; Bundle; Bundle = Bundle->NextInBundle)
6384         if (Bundle->OpValue == Bundle->Inst)
6385           LastInst = Bundle->Inst;
6386   }
6387 
6388   // LastInst can still be null at this point if there's either not an entry
6389   // for BB in BlocksSchedules or there's no ScheduleData available for
6390   // VL.back(). This can be the case if buildTree_rec aborts for various
6391   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6392   // size is reached, etc.). ScheduleData is initialized in the scheduling
6393   // "dry-run".
6394   //
6395   // If this happens, we can still find the last instruction by brute force. We
6396   // iterate forwards from Front (inclusive) until we either see all
6397   // instructions in the bundle or reach the end of the block. If Front is the
6398   // last instruction in program order, LastInst will be set to Front, and we
6399   // will visit all the remaining instructions in the block.
6400   //
6401   // One of the reasons we exit early from buildTree_rec is to place an upper
6402   // bound on compile-time. Thus, taking an additional compile-time hit here is
6403   // not ideal. However, this should be exceedingly rare since it requires that
6404   // we both exit early from buildTree_rec and that the bundle be out-of-order
6405   // (causing us to iterate all the way to the end of the block).
6406   if (!LastInst) {
6407     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6408     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6409       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6410         LastInst = &I;
6411       if (Bundle.empty())
6412         break;
6413     }
6414   }
6415   assert(LastInst && "Failed to find last instruction in bundle");
6416 
6417   // Set the insertion point after the last instruction in the bundle. Set the
6418   // debug location to Front.
6419   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6420   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6421 }
6422 
6423 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6424   // List of instructions/lanes from current block and/or the blocks which are
6425   // part of the current loop. These instructions will be inserted at the end to
6426   // make it possible to optimize loops and hoist invariant instructions out of
6427   // the loops body with better chances for success.
6428   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6429   SmallSet<int, 4> PostponedIndices;
6430   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6431   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6432     SmallPtrSet<BasicBlock *, 4> Visited;
6433     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6434       InsertBB = InsertBB->getSinglePredecessor();
6435     return InsertBB && InsertBB == InstBB;
6436   };
6437   for (int I = 0, E = VL.size(); I < E; ++I) {
6438     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6439       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6440            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6441           PostponedIndices.insert(I).second)
6442         PostponedInsts.emplace_back(Inst, I);
6443   }
6444 
6445   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6446     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6447     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6448     if (!InsElt)
6449       return Vec;
6450     GatherShuffleSeq.insert(InsElt);
6451     CSEBlocks.insert(InsElt->getParent());
6452     // Add to our 'need-to-extract' list.
6453     if (TreeEntry *Entry = getTreeEntry(V)) {
6454       // Find which lane we need to extract.
6455       unsigned FoundLane = Entry->findLaneForValue(V);
6456       ExternalUses.emplace_back(V, InsElt, FoundLane);
6457     }
6458     return Vec;
6459   };
6460   Value *Val0 =
6461       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6462   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6463   Value *Vec = PoisonValue::get(VecTy);
6464   SmallVector<int> NonConsts;
6465   // Insert constant values at first.
6466   for (int I = 0, E = VL.size(); I < E; ++I) {
6467     if (PostponedIndices.contains(I))
6468       continue;
6469     if (!isConstant(VL[I])) {
6470       NonConsts.push_back(I);
6471       continue;
6472     }
6473     Vec = CreateInsertElement(Vec, VL[I], I);
6474   }
6475   // Insert non-constant values.
6476   for (int I : NonConsts)
6477     Vec = CreateInsertElement(Vec, VL[I], I);
6478   // Append instructions, which are/may be part of the loop, in the end to make
6479   // it possible to hoist non-loop-based instructions.
6480   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6481     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6482 
6483   return Vec;
6484 }
6485 
6486 namespace {
6487 /// Merges shuffle masks and emits final shuffle instruction, if required.
6488 class ShuffleInstructionBuilder {
6489   IRBuilderBase &Builder;
6490   const unsigned VF = 0;
6491   bool IsFinalized = false;
6492   SmallVector<int, 4> Mask;
6493   /// Holds all of the instructions that we gathered.
6494   SetVector<Instruction *> &GatherShuffleSeq;
6495   /// A list of blocks that we are going to CSE.
6496   SetVector<BasicBlock *> &CSEBlocks;
6497 
6498 public:
6499   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6500                             SetVector<Instruction *> &GatherShuffleSeq,
6501                             SetVector<BasicBlock *> &CSEBlocks)
6502       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6503         CSEBlocks(CSEBlocks) {}
6504 
6505   /// Adds a mask, inverting it before applying.
6506   void addInversedMask(ArrayRef<unsigned> SubMask) {
6507     if (SubMask.empty())
6508       return;
6509     SmallVector<int, 4> NewMask;
6510     inversePermutation(SubMask, NewMask);
6511     addMask(NewMask);
6512   }
6513 
6514   /// Functions adds masks, merging them into  single one.
6515   void addMask(ArrayRef<unsigned> SubMask) {
6516     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6517     addMask(NewMask);
6518   }
6519 
6520   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6521 
6522   Value *finalize(Value *V) {
6523     IsFinalized = true;
6524     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6525     if (VF == ValueVF && Mask.empty())
6526       return V;
6527     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6528     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6529     addMask(NormalizedMask);
6530 
6531     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6532       return V;
6533     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6534     if (auto *I = dyn_cast<Instruction>(Vec)) {
6535       GatherShuffleSeq.insert(I);
6536       CSEBlocks.insert(I->getParent());
6537     }
6538     return Vec;
6539   }
6540 
6541   ~ShuffleInstructionBuilder() {
6542     assert((IsFinalized || Mask.empty()) &&
6543            "Shuffle construction must be finalized.");
6544   }
6545 };
6546 } // namespace
6547 
6548 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6549   unsigned VF = VL.size();
6550   InstructionsState S = getSameOpcode(VL);
6551   if (S.getOpcode()) {
6552     if (TreeEntry *E = getTreeEntry(S.OpValue))
6553       if (E->isSame(VL)) {
6554         Value *V = vectorizeTree(E);
6555         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6556           if (!E->ReuseShuffleIndices.empty()) {
6557             // Reshuffle to get only unique values.
6558             // If some of the scalars are duplicated in the vectorization tree
6559             // entry, we do not vectorize them but instead generate a mask for
6560             // the reuses. But if there are several users of the same entry,
6561             // they may have different vectorization factors. This is especially
6562             // important for PHI nodes. In this case, we need to adapt the
6563             // resulting instruction for the user vectorization factor and have
6564             // to reshuffle it again to take only unique elements of the vector.
6565             // Without this code the function incorrectly returns reduced vector
6566             // instruction with the same elements, not with the unique ones.
6567 
6568             // block:
6569             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6570             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6571             // ... (use %2)
6572             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6573             // br %block
6574             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6575             SmallSet<int, 4> UsedIdxs;
6576             int Pos = 0;
6577             int Sz = VL.size();
6578             for (int Idx : E->ReuseShuffleIndices) {
6579               if (Idx != Sz && Idx != UndefMaskElem &&
6580                   UsedIdxs.insert(Idx).second)
6581                 UniqueIdxs[Idx] = Pos;
6582               ++Pos;
6583             }
6584             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6585                                             "less than original vector size.");
6586             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6587             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6588           } else {
6589             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6590                    "Expected vectorization factor less "
6591                    "than original vector size.");
6592             SmallVector<int> UniformMask(VF, 0);
6593             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6594             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6595           }
6596           if (auto *I = dyn_cast<Instruction>(V)) {
6597             GatherShuffleSeq.insert(I);
6598             CSEBlocks.insert(I->getParent());
6599           }
6600         }
6601         return V;
6602       }
6603   }
6604 
6605   // Check that every instruction appears once in this bundle.
6606   SmallVector<int> ReuseShuffleIndicies;
6607   SmallVector<Value *> UniqueValues;
6608   if (VL.size() > 2) {
6609     DenseMap<Value *, unsigned> UniquePositions;
6610     unsigned NumValues =
6611         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6612                                     return !isa<UndefValue>(V);
6613                                   }).base());
6614     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6615     int UniqueVals = 0;
6616     for (Value *V : VL.drop_back(VL.size() - VF)) {
6617       if (isa<UndefValue>(V)) {
6618         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6619         continue;
6620       }
6621       if (isConstant(V)) {
6622         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6623         UniqueValues.emplace_back(V);
6624         continue;
6625       }
6626       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6627       ReuseShuffleIndicies.emplace_back(Res.first->second);
6628       if (Res.second) {
6629         UniqueValues.emplace_back(V);
6630         ++UniqueVals;
6631       }
6632     }
6633     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6634       // Emit pure splat vector.
6635       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6636                                   UndefMaskElem);
6637     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6638       ReuseShuffleIndicies.clear();
6639       UniqueValues.clear();
6640       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6641     }
6642     UniqueValues.append(VF - UniqueValues.size(),
6643                         PoisonValue::get(VL[0]->getType()));
6644     VL = UniqueValues;
6645   }
6646 
6647   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6648                                            CSEBlocks);
6649   Value *Vec = gather(VL);
6650   if (!ReuseShuffleIndicies.empty()) {
6651     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6652     Vec = ShuffleBuilder.finalize(Vec);
6653   }
6654   return Vec;
6655 }
6656 
6657 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6658   IRBuilder<>::InsertPointGuard Guard(Builder);
6659 
6660   if (E->VectorizedValue) {
6661     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6662     return E->VectorizedValue;
6663   }
6664 
6665   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6666   unsigned VF = E->getVectorFactor();
6667   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6668                                            CSEBlocks);
6669   if (E->State == TreeEntry::NeedToGather) {
6670     if (E->getMainOp())
6671       setInsertPointAfterBundle(E);
6672     Value *Vec;
6673     SmallVector<int> Mask;
6674     SmallVector<const TreeEntry *> Entries;
6675     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6676         isGatherShuffledEntry(E, Mask, Entries);
6677     if (Shuffle.hasValue()) {
6678       assert((Entries.size() == 1 || Entries.size() == 2) &&
6679              "Expected shuffle of 1 or 2 entries.");
6680       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6681                                         Entries.back()->VectorizedValue, Mask);
6682       if (auto *I = dyn_cast<Instruction>(Vec)) {
6683         GatherShuffleSeq.insert(I);
6684         CSEBlocks.insert(I->getParent());
6685       }
6686     } else {
6687       Vec = gather(E->Scalars);
6688     }
6689     if (NeedToShuffleReuses) {
6690       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6691       Vec = ShuffleBuilder.finalize(Vec);
6692     }
6693     E->VectorizedValue = Vec;
6694     return Vec;
6695   }
6696 
6697   assert((E->State == TreeEntry::Vectorize ||
6698           E->State == TreeEntry::ScatterVectorize) &&
6699          "Unhandled state");
6700   unsigned ShuffleOrOp =
6701       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6702   Instruction *VL0 = E->getMainOp();
6703   Type *ScalarTy = VL0->getType();
6704   if (auto *Store = dyn_cast<StoreInst>(VL0))
6705     ScalarTy = Store->getValueOperand()->getType();
6706   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6707     ScalarTy = IE->getOperand(1)->getType();
6708   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6709   switch (ShuffleOrOp) {
6710     case Instruction::PHI: {
6711       assert(
6712           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6713           "PHI reordering is free.");
6714       auto *PH = cast<PHINode>(VL0);
6715       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6716       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6717       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6718       Value *V = NewPhi;
6719 
6720       // Adjust insertion point once all PHI's have been generated.
6721       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6722       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6723 
6724       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6725       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6726       V = ShuffleBuilder.finalize(V);
6727 
6728       E->VectorizedValue = V;
6729 
6730       // PHINodes may have multiple entries from the same block. We want to
6731       // visit every block once.
6732       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6733 
6734       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6735         ValueList Operands;
6736         BasicBlock *IBB = PH->getIncomingBlock(i);
6737 
6738         if (!VisitedBBs.insert(IBB).second) {
6739           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6740           continue;
6741         }
6742 
6743         Builder.SetInsertPoint(IBB->getTerminator());
6744         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6745         Value *Vec = vectorizeTree(E->getOperand(i));
6746         NewPhi->addIncoming(Vec, IBB);
6747       }
6748 
6749       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6750              "Invalid number of incoming values");
6751       return V;
6752     }
6753 
6754     case Instruction::ExtractElement: {
6755       Value *V = E->getSingleOperand(0);
6756       Builder.SetInsertPoint(VL0);
6757       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6758       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6759       V = ShuffleBuilder.finalize(V);
6760       E->VectorizedValue = V;
6761       return V;
6762     }
6763     case Instruction::ExtractValue: {
6764       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6765       Builder.SetInsertPoint(LI);
6766       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6767       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6768       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6769       Value *NewV = propagateMetadata(V, E->Scalars);
6770       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6771       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6772       NewV = ShuffleBuilder.finalize(NewV);
6773       E->VectorizedValue = NewV;
6774       return NewV;
6775     }
6776     case Instruction::InsertElement: {
6777       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6778       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6779       Value *V = vectorizeTree(E->getOperand(1));
6780 
6781       // Create InsertVector shuffle if necessary
6782       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6783         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6784       }));
6785       const unsigned NumElts =
6786           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6787       const unsigned NumScalars = E->Scalars.size();
6788 
6789       unsigned Offset = *getInsertIndex(VL0);
6790       assert(Offset < NumElts && "Failed to find vector index offset");
6791 
6792       // Create shuffle to resize vector
6793       SmallVector<int> Mask;
6794       if (!E->ReorderIndices.empty()) {
6795         inversePermutation(E->ReorderIndices, Mask);
6796         Mask.append(NumElts - NumScalars, UndefMaskElem);
6797       } else {
6798         Mask.assign(NumElts, UndefMaskElem);
6799         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6800       }
6801       // Create InsertVector shuffle if necessary
6802       bool IsIdentity = true;
6803       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6804       Mask.swap(PrevMask);
6805       for (unsigned I = 0; I < NumScalars; ++I) {
6806         Value *Scalar = E->Scalars[PrevMask[I]];
6807         unsigned InsertIdx = *getInsertIndex(Scalar);
6808         IsIdentity &= InsertIdx - Offset == I;
6809         Mask[InsertIdx - Offset] = I;
6810       }
6811       if (!IsIdentity || NumElts != NumScalars) {
6812         V = Builder.CreateShuffleVector(V, Mask);
6813         if (auto *I = dyn_cast<Instruction>(V)) {
6814           GatherShuffleSeq.insert(I);
6815           CSEBlocks.insert(I->getParent());
6816         }
6817       }
6818 
6819       if ((!IsIdentity || Offset != 0 ||
6820            !isUndefVector(FirstInsert->getOperand(0))) &&
6821           NumElts != NumScalars) {
6822         SmallVector<int> InsertMask(NumElts);
6823         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6824         for (unsigned I = 0; I < NumElts; I++) {
6825           if (Mask[I] != UndefMaskElem)
6826             InsertMask[Offset + I] = NumElts + I;
6827         }
6828 
6829         V = Builder.CreateShuffleVector(
6830             FirstInsert->getOperand(0), V, InsertMask,
6831             cast<Instruction>(E->Scalars.back())->getName());
6832         if (auto *I = dyn_cast<Instruction>(V)) {
6833           GatherShuffleSeq.insert(I);
6834           CSEBlocks.insert(I->getParent());
6835         }
6836       }
6837 
6838       ++NumVectorInstructions;
6839       E->VectorizedValue = V;
6840       return V;
6841     }
6842     case Instruction::ZExt:
6843     case Instruction::SExt:
6844     case Instruction::FPToUI:
6845     case Instruction::FPToSI:
6846     case Instruction::FPExt:
6847     case Instruction::PtrToInt:
6848     case Instruction::IntToPtr:
6849     case Instruction::SIToFP:
6850     case Instruction::UIToFP:
6851     case Instruction::Trunc:
6852     case Instruction::FPTrunc:
6853     case Instruction::BitCast: {
6854       setInsertPointAfterBundle(E);
6855 
6856       Value *InVec = vectorizeTree(E->getOperand(0));
6857 
6858       if (E->VectorizedValue) {
6859         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6860         return E->VectorizedValue;
6861       }
6862 
6863       auto *CI = cast<CastInst>(VL0);
6864       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6865       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6866       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6867       V = ShuffleBuilder.finalize(V);
6868 
6869       E->VectorizedValue = V;
6870       ++NumVectorInstructions;
6871       return V;
6872     }
6873     case Instruction::FCmp:
6874     case Instruction::ICmp: {
6875       setInsertPointAfterBundle(E);
6876 
6877       Value *L = vectorizeTree(E->getOperand(0));
6878       Value *R = vectorizeTree(E->getOperand(1));
6879 
6880       if (E->VectorizedValue) {
6881         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6882         return E->VectorizedValue;
6883       }
6884 
6885       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6886       Value *V = Builder.CreateCmp(P0, L, R);
6887       propagateIRFlags(V, E->Scalars, VL0);
6888       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6889       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6890       V = ShuffleBuilder.finalize(V);
6891 
6892       E->VectorizedValue = V;
6893       ++NumVectorInstructions;
6894       return V;
6895     }
6896     case Instruction::Select: {
6897       setInsertPointAfterBundle(E);
6898 
6899       Value *Cond = vectorizeTree(E->getOperand(0));
6900       Value *True = vectorizeTree(E->getOperand(1));
6901       Value *False = vectorizeTree(E->getOperand(2));
6902 
6903       if (E->VectorizedValue) {
6904         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6905         return E->VectorizedValue;
6906       }
6907 
6908       Value *V = Builder.CreateSelect(Cond, True, False);
6909       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6910       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6911       V = ShuffleBuilder.finalize(V);
6912 
6913       E->VectorizedValue = V;
6914       ++NumVectorInstructions;
6915       return V;
6916     }
6917     case Instruction::FNeg: {
6918       setInsertPointAfterBundle(E);
6919 
6920       Value *Op = vectorizeTree(E->getOperand(0));
6921 
6922       if (E->VectorizedValue) {
6923         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6924         return E->VectorizedValue;
6925       }
6926 
6927       Value *V = Builder.CreateUnOp(
6928           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6929       propagateIRFlags(V, E->Scalars, VL0);
6930       if (auto *I = dyn_cast<Instruction>(V))
6931         V = propagateMetadata(I, E->Scalars);
6932 
6933       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6934       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6935       V = ShuffleBuilder.finalize(V);
6936 
6937       E->VectorizedValue = V;
6938       ++NumVectorInstructions;
6939 
6940       return V;
6941     }
6942     case Instruction::Add:
6943     case Instruction::FAdd:
6944     case Instruction::Sub:
6945     case Instruction::FSub:
6946     case Instruction::Mul:
6947     case Instruction::FMul:
6948     case Instruction::UDiv:
6949     case Instruction::SDiv:
6950     case Instruction::FDiv:
6951     case Instruction::URem:
6952     case Instruction::SRem:
6953     case Instruction::FRem:
6954     case Instruction::Shl:
6955     case Instruction::LShr:
6956     case Instruction::AShr:
6957     case Instruction::And:
6958     case Instruction::Or:
6959     case Instruction::Xor: {
6960       setInsertPointAfterBundle(E);
6961 
6962       Value *LHS = vectorizeTree(E->getOperand(0));
6963       Value *RHS = vectorizeTree(E->getOperand(1));
6964 
6965       if (E->VectorizedValue) {
6966         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6967         return E->VectorizedValue;
6968       }
6969 
6970       Value *V = Builder.CreateBinOp(
6971           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6972           RHS);
6973       propagateIRFlags(V, E->Scalars, VL0);
6974       if (auto *I = dyn_cast<Instruction>(V))
6975         V = propagateMetadata(I, E->Scalars);
6976 
6977       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6978       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6979       V = ShuffleBuilder.finalize(V);
6980 
6981       E->VectorizedValue = V;
6982       ++NumVectorInstructions;
6983 
6984       return V;
6985     }
6986     case Instruction::Load: {
6987       // Loads are inserted at the head of the tree because we don't want to
6988       // sink them all the way down past store instructions.
6989       setInsertPointAfterBundle(E);
6990 
6991       LoadInst *LI = cast<LoadInst>(VL0);
6992       Instruction *NewLI;
6993       unsigned AS = LI->getPointerAddressSpace();
6994       Value *PO = LI->getPointerOperand();
6995       if (E->State == TreeEntry::Vectorize) {
6996 
6997         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6998 
6999         // The pointer operand uses an in-tree scalar so we add the new BitCast
7000         // to ExternalUses list to make sure that an extract will be generated
7001         // in the future.
7002         if (TreeEntry *Entry = getTreeEntry(PO)) {
7003           // Find which lane we need to extract.
7004           unsigned FoundLane = Entry->findLaneForValue(PO);
7005           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
7006         }
7007 
7008         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7009       } else {
7010         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7011         Value *VecPtr = vectorizeTree(E->getOperand(0));
7012         // Use the minimum alignment of the gathered loads.
7013         Align CommonAlignment = LI->getAlign();
7014         for (Value *V : E->Scalars)
7015           CommonAlignment =
7016               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7017         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7018       }
7019       Value *V = propagateMetadata(NewLI, E->Scalars);
7020 
7021       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7022       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7023       V = ShuffleBuilder.finalize(V);
7024       E->VectorizedValue = V;
7025       ++NumVectorInstructions;
7026       return V;
7027     }
7028     case Instruction::Store: {
7029       auto *SI = cast<StoreInst>(VL0);
7030       unsigned AS = SI->getPointerAddressSpace();
7031 
7032       setInsertPointAfterBundle(E);
7033 
7034       Value *VecValue = vectorizeTree(E->getOperand(0));
7035       ShuffleBuilder.addMask(E->ReorderIndices);
7036       VecValue = ShuffleBuilder.finalize(VecValue);
7037 
7038       Value *ScalarPtr = SI->getPointerOperand();
7039       Value *VecPtr = Builder.CreateBitCast(
7040           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7041       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
7042                                                  SI->getAlign());
7043 
7044       // The pointer operand uses an in-tree scalar, so add the new BitCast to
7045       // ExternalUses to make sure that an extract will be generated in the
7046       // future.
7047       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7048         // Find which lane we need to extract.
7049         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7050         ExternalUses.push_back(
7051             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
7052       }
7053 
7054       Value *V = propagateMetadata(ST, E->Scalars);
7055 
7056       E->VectorizedValue = V;
7057       ++NumVectorInstructions;
7058       return V;
7059     }
7060     case Instruction::GetElementPtr: {
7061       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7062       setInsertPointAfterBundle(E);
7063 
7064       Value *Op0 = vectorizeTree(E->getOperand(0));
7065 
7066       SmallVector<Value *> OpVecs;
7067       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7068         Value *OpVec = vectorizeTree(E->getOperand(J));
7069         OpVecs.push_back(OpVec);
7070       }
7071 
7072       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7073       if (Instruction *I = dyn_cast<Instruction>(V))
7074         V = propagateMetadata(I, E->Scalars);
7075 
7076       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7077       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7078       V = ShuffleBuilder.finalize(V);
7079 
7080       E->VectorizedValue = V;
7081       ++NumVectorInstructions;
7082 
7083       return V;
7084     }
7085     case Instruction::Call: {
7086       CallInst *CI = cast<CallInst>(VL0);
7087       setInsertPointAfterBundle(E);
7088 
7089       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7090       if (Function *FI = CI->getCalledFunction())
7091         IID = FI->getIntrinsicID();
7092 
7093       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7094 
7095       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7096       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7097                           VecCallCosts.first <= VecCallCosts.second;
7098 
7099       Value *ScalarArg = nullptr;
7100       std::vector<Value *> OpVecs;
7101       SmallVector<Type *, 2> TysForDecl =
7102           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7103       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7104         ValueList OpVL;
7105         // Some intrinsics have scalar arguments. This argument should not be
7106         // vectorized.
7107         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7108           CallInst *CEI = cast<CallInst>(VL0);
7109           ScalarArg = CEI->getArgOperand(j);
7110           OpVecs.push_back(CEI->getArgOperand(j));
7111           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7112             TysForDecl.push_back(ScalarArg->getType());
7113           continue;
7114         }
7115 
7116         Value *OpVec = vectorizeTree(E->getOperand(j));
7117         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7118         OpVecs.push_back(OpVec);
7119       }
7120 
7121       Function *CF;
7122       if (!UseIntrinsic) {
7123         VFShape Shape =
7124             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7125                                   VecTy->getNumElements())),
7126                          false /*HasGlobalPred*/);
7127         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7128       } else {
7129         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7130       }
7131 
7132       SmallVector<OperandBundleDef, 1> OpBundles;
7133       CI->getOperandBundlesAsDefs(OpBundles);
7134       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7135 
7136       // The scalar argument uses an in-tree scalar so we add the new vectorized
7137       // call to ExternalUses list to make sure that an extract will be
7138       // generated in the future.
7139       if (ScalarArg) {
7140         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7141           // Find which lane we need to extract.
7142           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7143           ExternalUses.push_back(
7144               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7145         }
7146       }
7147 
7148       propagateIRFlags(V, E->Scalars, VL0);
7149       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7150       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7151       V = ShuffleBuilder.finalize(V);
7152 
7153       E->VectorizedValue = V;
7154       ++NumVectorInstructions;
7155       return V;
7156     }
7157     case Instruction::ShuffleVector: {
7158       assert(E->isAltShuffle() &&
7159              ((Instruction::isBinaryOp(E->getOpcode()) &&
7160                Instruction::isBinaryOp(E->getAltOpcode())) ||
7161               (Instruction::isCast(E->getOpcode()) &&
7162                Instruction::isCast(E->getAltOpcode())) ||
7163               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7164              "Invalid Shuffle Vector Operand");
7165 
7166       Value *LHS = nullptr, *RHS = nullptr;
7167       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7168         setInsertPointAfterBundle(E);
7169         LHS = vectorizeTree(E->getOperand(0));
7170         RHS = vectorizeTree(E->getOperand(1));
7171       } else {
7172         setInsertPointAfterBundle(E);
7173         LHS = vectorizeTree(E->getOperand(0));
7174       }
7175 
7176       if (E->VectorizedValue) {
7177         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7178         return E->VectorizedValue;
7179       }
7180 
7181       Value *V0, *V1;
7182       if (Instruction::isBinaryOp(E->getOpcode())) {
7183         V0 = Builder.CreateBinOp(
7184             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7185         V1 = Builder.CreateBinOp(
7186             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7187       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7188         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7189         auto *AltCI = cast<CmpInst>(E->getAltOp());
7190         CmpInst::Predicate AltPred = AltCI->getPredicate();
7191         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7192       } else {
7193         V0 = Builder.CreateCast(
7194             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7195         V1 = Builder.CreateCast(
7196             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7197       }
7198       // Add V0 and V1 to later analysis to try to find and remove matching
7199       // instruction, if any.
7200       for (Value *V : {V0, V1}) {
7201         if (auto *I = dyn_cast<Instruction>(V)) {
7202           GatherShuffleSeq.insert(I);
7203           CSEBlocks.insert(I->getParent());
7204         }
7205       }
7206 
7207       // Create shuffle to take alternate operations from the vector.
7208       // Also, gather up main and alt scalar ops to propagate IR flags to
7209       // each vector operation.
7210       ValueList OpScalars, AltScalars;
7211       SmallVector<int> Mask;
7212       buildShuffleEntryMask(
7213           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7214           [E](Instruction *I) {
7215             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7216             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7217           },
7218           Mask, &OpScalars, &AltScalars);
7219 
7220       propagateIRFlags(V0, OpScalars);
7221       propagateIRFlags(V1, AltScalars);
7222 
7223       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7224       if (auto *I = dyn_cast<Instruction>(V)) {
7225         V = propagateMetadata(I, E->Scalars);
7226         GatherShuffleSeq.insert(I);
7227         CSEBlocks.insert(I->getParent());
7228       }
7229       V = ShuffleBuilder.finalize(V);
7230 
7231       E->VectorizedValue = V;
7232       ++NumVectorInstructions;
7233 
7234       return V;
7235     }
7236     default:
7237     llvm_unreachable("unknown inst");
7238   }
7239   return nullptr;
7240 }
7241 
7242 Value *BoUpSLP::vectorizeTree() {
7243   ExtraValueToDebugLocsMap ExternallyUsedValues;
7244   return vectorizeTree(ExternallyUsedValues);
7245 }
7246 
7247 Value *
7248 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7249   // All blocks must be scheduled before any instructions are inserted.
7250   for (auto &BSIter : BlocksSchedules) {
7251     scheduleBlock(BSIter.second.get());
7252   }
7253 
7254   Builder.SetInsertPoint(&F->getEntryBlock().front());
7255   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7256 
7257   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7258   // vectorized root. InstCombine will then rewrite the entire expression. We
7259   // sign extend the extracted values below.
7260   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7261   if (MinBWs.count(ScalarRoot)) {
7262     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7263       // If current instr is a phi and not the last phi, insert it after the
7264       // last phi node.
7265       if (isa<PHINode>(I))
7266         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7267       else
7268         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7269     }
7270     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7271     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7272     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7273     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7274     VectorizableTree[0]->VectorizedValue = Trunc;
7275   }
7276 
7277   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7278                     << " values .\n");
7279 
7280   // Extract all of the elements with the external uses.
7281   for (const auto &ExternalUse : ExternalUses) {
7282     Value *Scalar = ExternalUse.Scalar;
7283     llvm::User *User = ExternalUse.User;
7284 
7285     // Skip users that we already RAUW. This happens when one instruction
7286     // has multiple uses of the same value.
7287     if (User && !is_contained(Scalar->users(), User))
7288       continue;
7289     TreeEntry *E = getTreeEntry(Scalar);
7290     assert(E && "Invalid scalar");
7291     assert(E->State != TreeEntry::NeedToGather &&
7292            "Extracting from a gather list");
7293 
7294     Value *Vec = E->VectorizedValue;
7295     assert(Vec && "Can't find vectorizable value");
7296 
7297     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7298     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7299       if (Scalar->getType() != Vec->getType()) {
7300         Value *Ex;
7301         // "Reuse" the existing extract to improve final codegen.
7302         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7303           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7304                                             ES->getOperand(1));
7305         } else {
7306           Ex = Builder.CreateExtractElement(Vec, Lane);
7307         }
7308         // If necessary, sign-extend or zero-extend ScalarRoot
7309         // to the larger type.
7310         if (!MinBWs.count(ScalarRoot))
7311           return Ex;
7312         if (MinBWs[ScalarRoot].second)
7313           return Builder.CreateSExt(Ex, Scalar->getType());
7314         return Builder.CreateZExt(Ex, Scalar->getType());
7315       }
7316       assert(isa<FixedVectorType>(Scalar->getType()) &&
7317              isa<InsertElementInst>(Scalar) &&
7318              "In-tree scalar of vector type is not insertelement?");
7319       return Vec;
7320     };
7321     // If User == nullptr, the Scalar is used as extra arg. Generate
7322     // ExtractElement instruction and update the record for this scalar in
7323     // ExternallyUsedValues.
7324     if (!User) {
7325       assert(ExternallyUsedValues.count(Scalar) &&
7326              "Scalar with nullptr as an external user must be registered in "
7327              "ExternallyUsedValues map");
7328       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7329         Builder.SetInsertPoint(VecI->getParent(),
7330                                std::next(VecI->getIterator()));
7331       } else {
7332         Builder.SetInsertPoint(&F->getEntryBlock().front());
7333       }
7334       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7335       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7336       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7337       auto It = ExternallyUsedValues.find(Scalar);
7338       assert(It != ExternallyUsedValues.end() &&
7339              "Externally used scalar is not found in ExternallyUsedValues");
7340       NewInstLocs.append(It->second);
7341       ExternallyUsedValues.erase(Scalar);
7342       // Required to update internally referenced instructions.
7343       Scalar->replaceAllUsesWith(NewInst);
7344       continue;
7345     }
7346 
7347     // Generate extracts for out-of-tree users.
7348     // Find the insertion point for the extractelement lane.
7349     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7350       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7351         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7352           if (PH->getIncomingValue(i) == Scalar) {
7353             Instruction *IncomingTerminator =
7354                 PH->getIncomingBlock(i)->getTerminator();
7355             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7356               Builder.SetInsertPoint(VecI->getParent(),
7357                                      std::next(VecI->getIterator()));
7358             } else {
7359               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7360             }
7361             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7362             CSEBlocks.insert(PH->getIncomingBlock(i));
7363             PH->setOperand(i, NewInst);
7364           }
7365         }
7366       } else {
7367         Builder.SetInsertPoint(cast<Instruction>(User));
7368         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7369         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7370         User->replaceUsesOfWith(Scalar, NewInst);
7371       }
7372     } else {
7373       Builder.SetInsertPoint(&F->getEntryBlock().front());
7374       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7375       CSEBlocks.insert(&F->getEntryBlock());
7376       User->replaceUsesOfWith(Scalar, NewInst);
7377     }
7378 
7379     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7380   }
7381 
7382   // For each vectorized value:
7383   for (auto &TEPtr : VectorizableTree) {
7384     TreeEntry *Entry = TEPtr.get();
7385 
7386     // No need to handle users of gathered values.
7387     if (Entry->State == TreeEntry::NeedToGather)
7388       continue;
7389 
7390     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7391 
7392     // For each lane:
7393     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7394       Value *Scalar = Entry->Scalars[Lane];
7395 
7396 #ifndef NDEBUG
7397       Type *Ty = Scalar->getType();
7398       if (!Ty->isVoidTy()) {
7399         for (User *U : Scalar->users()) {
7400           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7401 
7402           // It is legal to delete users in the ignorelist.
7403           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7404                   (isa_and_nonnull<Instruction>(U) &&
7405                    isDeleted(cast<Instruction>(U)))) &&
7406                  "Deleting out-of-tree value");
7407         }
7408       }
7409 #endif
7410       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7411       eraseInstruction(cast<Instruction>(Scalar));
7412     }
7413   }
7414 
7415   Builder.ClearInsertionPoint();
7416   InstrElementSize.clear();
7417 
7418   return VectorizableTree[0]->VectorizedValue;
7419 }
7420 
7421 void BoUpSLP::optimizeGatherSequence() {
7422   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7423                     << " gather sequences instructions.\n");
7424   // LICM InsertElementInst sequences.
7425   for (Instruction *I : GatherShuffleSeq) {
7426     if (isDeleted(I))
7427       continue;
7428 
7429     // Check if this block is inside a loop.
7430     Loop *L = LI->getLoopFor(I->getParent());
7431     if (!L)
7432       continue;
7433 
7434     // Check if it has a preheader.
7435     BasicBlock *PreHeader = L->getLoopPreheader();
7436     if (!PreHeader)
7437       continue;
7438 
7439     // If the vector or the element that we insert into it are
7440     // instructions that are defined in this basic block then we can't
7441     // hoist this instruction.
7442     if (any_of(I->operands(), [L](Value *V) {
7443           auto *OpI = dyn_cast<Instruction>(V);
7444           return OpI && L->contains(OpI);
7445         }))
7446       continue;
7447 
7448     // We can hoist this instruction. Move it to the pre-header.
7449     I->moveBefore(PreHeader->getTerminator());
7450   }
7451 
7452   // Make a list of all reachable blocks in our CSE queue.
7453   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7454   CSEWorkList.reserve(CSEBlocks.size());
7455   for (BasicBlock *BB : CSEBlocks)
7456     if (DomTreeNode *N = DT->getNode(BB)) {
7457       assert(DT->isReachableFromEntry(N));
7458       CSEWorkList.push_back(N);
7459     }
7460 
7461   // Sort blocks by domination. This ensures we visit a block after all blocks
7462   // dominating it are visited.
7463   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7464     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7465            "Different nodes should have different DFS numbers");
7466     return A->getDFSNumIn() < B->getDFSNumIn();
7467   });
7468 
7469   // Less defined shuffles can be replaced by the more defined copies.
7470   // Between two shuffles one is less defined if it has the same vector operands
7471   // and its mask indeces are the same as in the first one or undefs. E.g.
7472   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7473   // poison, <0, 0, 0, 0>.
7474   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7475                                            SmallVectorImpl<int> &NewMask) {
7476     if (I1->getType() != I2->getType())
7477       return false;
7478     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7479     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7480     if (!SI1 || !SI2)
7481       return I1->isIdenticalTo(I2);
7482     if (SI1->isIdenticalTo(SI2))
7483       return true;
7484     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7485       if (SI1->getOperand(I) != SI2->getOperand(I))
7486         return false;
7487     // Check if the second instruction is more defined than the first one.
7488     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7489     ArrayRef<int> SM1 = SI1->getShuffleMask();
7490     // Count trailing undefs in the mask to check the final number of used
7491     // registers.
7492     unsigned LastUndefsCnt = 0;
7493     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7494       if (SM1[I] == UndefMaskElem)
7495         ++LastUndefsCnt;
7496       else
7497         LastUndefsCnt = 0;
7498       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7499           NewMask[I] != SM1[I])
7500         return false;
7501       if (NewMask[I] == UndefMaskElem)
7502         NewMask[I] = SM1[I];
7503     }
7504     // Check if the last undefs actually change the final number of used vector
7505     // registers.
7506     return SM1.size() - LastUndefsCnt > 1 &&
7507            TTI->getNumberOfParts(SI1->getType()) ==
7508                TTI->getNumberOfParts(
7509                    FixedVectorType::get(SI1->getType()->getElementType(),
7510                                         SM1.size() - LastUndefsCnt));
7511   };
7512   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7513   // instructions. TODO: We can further optimize this scan if we split the
7514   // instructions into different buckets based on the insert lane.
7515   SmallVector<Instruction *, 16> Visited;
7516   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7517     assert(*I &&
7518            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7519            "Worklist not sorted properly!");
7520     BasicBlock *BB = (*I)->getBlock();
7521     // For all instructions in blocks containing gather sequences:
7522     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7523       if (isDeleted(&In))
7524         continue;
7525       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7526           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7527         continue;
7528 
7529       // Check if we can replace this instruction with any of the
7530       // visited instructions.
7531       bool Replaced = false;
7532       for (Instruction *&V : Visited) {
7533         SmallVector<int> NewMask;
7534         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7535             DT->dominates(V->getParent(), In.getParent())) {
7536           In.replaceAllUsesWith(V);
7537           eraseInstruction(&In);
7538           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7539             if (!NewMask.empty())
7540               SI->setShuffleMask(NewMask);
7541           Replaced = true;
7542           break;
7543         }
7544         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7545             GatherShuffleSeq.contains(V) &&
7546             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7547             DT->dominates(In.getParent(), V->getParent())) {
7548           In.moveAfter(V);
7549           V->replaceAllUsesWith(&In);
7550           eraseInstruction(V);
7551           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7552             if (!NewMask.empty())
7553               SI->setShuffleMask(NewMask);
7554           V = &In;
7555           Replaced = true;
7556           break;
7557         }
7558       }
7559       if (!Replaced) {
7560         assert(!is_contained(Visited, &In));
7561         Visited.push_back(&In);
7562       }
7563     }
7564   }
7565   CSEBlocks.clear();
7566   GatherShuffleSeq.clear();
7567 }
7568 
7569 BoUpSLP::ScheduleData *
7570 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7571   ScheduleData *Bundle = nullptr;
7572   ScheduleData *PrevInBundle = nullptr;
7573   for (Value *V : VL) {
7574     ScheduleData *BundleMember = getScheduleData(V);
7575     assert(BundleMember &&
7576            "no ScheduleData for bundle member "
7577            "(maybe not in same basic block)");
7578     assert(BundleMember->isSchedulingEntity() &&
7579            "bundle member already part of other bundle");
7580     if (PrevInBundle) {
7581       PrevInBundle->NextInBundle = BundleMember;
7582     } else {
7583       Bundle = BundleMember;
7584     }
7585 
7586     // Group the instructions to a bundle.
7587     BundleMember->FirstInBundle = Bundle;
7588     PrevInBundle = BundleMember;
7589   }
7590   assert(Bundle && "Failed to find schedule bundle");
7591   return Bundle;
7592 }
7593 
7594 // Groups the instructions to a bundle (which is then a single scheduling entity)
7595 // and schedules instructions until the bundle gets ready.
7596 Optional<BoUpSLP::ScheduleData *>
7597 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7598                                             const InstructionsState &S) {
7599   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7600   // instructions.
7601   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7602     return nullptr;
7603 
7604   // Initialize the instruction bundle.
7605   Instruction *OldScheduleEnd = ScheduleEnd;
7606   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7607 
7608   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7609                                                          ScheduleData *Bundle) {
7610     // The scheduling region got new instructions at the lower end (or it is a
7611     // new region for the first bundle). This makes it necessary to
7612     // recalculate all dependencies.
7613     // It is seldom that this needs to be done a second time after adding the
7614     // initial bundle to the region.
7615     if (ScheduleEnd != OldScheduleEnd) {
7616       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7617         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7618       ReSchedule = true;
7619     }
7620     if (Bundle) {
7621       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7622                         << " in block " << BB->getName() << "\n");
7623       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7624     }
7625 
7626     if (ReSchedule) {
7627       resetSchedule();
7628       initialFillReadyList(ReadyInsts);
7629     }
7630 
7631     // Now try to schedule the new bundle or (if no bundle) just calculate
7632     // dependencies. As soon as the bundle is "ready" it means that there are no
7633     // cyclic dependencies and we can schedule it. Note that's important that we
7634     // don't "schedule" the bundle yet (see cancelScheduling).
7635     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7636            !ReadyInsts.empty()) {
7637       ScheduleData *Picked = ReadyInsts.pop_back_val();
7638       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7639              "must be ready to schedule");
7640       schedule(Picked, ReadyInsts);
7641     }
7642   };
7643 
7644   // Make sure that the scheduling region contains all
7645   // instructions of the bundle.
7646   for (Value *V : VL) {
7647     if (!extendSchedulingRegion(V, S)) {
7648       // If the scheduling region got new instructions at the lower end (or it
7649       // is a new region for the first bundle). This makes it necessary to
7650       // recalculate all dependencies.
7651       // Otherwise the compiler may crash trying to incorrectly calculate
7652       // dependencies and emit instruction in the wrong order at the actual
7653       // scheduling.
7654       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7655       return None;
7656     }
7657   }
7658 
7659   bool ReSchedule = false;
7660   for (Value *V : VL) {
7661     ScheduleData *BundleMember = getScheduleData(V);
7662     assert(BundleMember &&
7663            "no ScheduleData for bundle member (maybe not in same basic block)");
7664 
7665     // Make sure we don't leave the pieces of the bundle in the ready list when
7666     // whole bundle might not be ready.
7667     ReadyInsts.remove(BundleMember);
7668 
7669     if (!BundleMember->IsScheduled)
7670       continue;
7671     // A bundle member was scheduled as single instruction before and now
7672     // needs to be scheduled as part of the bundle. We just get rid of the
7673     // existing schedule.
7674     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7675                       << " was already scheduled\n");
7676     ReSchedule = true;
7677   }
7678 
7679   auto *Bundle = buildBundle(VL);
7680   TryScheduleBundleImpl(ReSchedule, Bundle);
7681   if (!Bundle->isReady()) {
7682     cancelScheduling(VL, S.OpValue);
7683     return None;
7684   }
7685   return Bundle;
7686 }
7687 
7688 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7689                                                 Value *OpValue) {
7690   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7691     return;
7692 
7693   ScheduleData *Bundle = getScheduleData(OpValue);
7694   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7695   assert(!Bundle->IsScheduled &&
7696          "Can't cancel bundle which is already scheduled");
7697   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7698          "tried to unbundle something which is not a bundle");
7699 
7700   // Remove the bundle from the ready list.
7701   if (Bundle->isReady())
7702     ReadyInsts.remove(Bundle);
7703 
7704   // Un-bundle: make single instructions out of the bundle.
7705   ScheduleData *BundleMember = Bundle;
7706   while (BundleMember) {
7707     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7708     BundleMember->FirstInBundle = BundleMember;
7709     ScheduleData *Next = BundleMember->NextInBundle;
7710     BundleMember->NextInBundle = nullptr;
7711     if (BundleMember->unscheduledDepsInBundle() == 0) {
7712       ReadyInsts.insert(BundleMember);
7713     }
7714     BundleMember = Next;
7715   }
7716 }
7717 
7718 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7719   // Allocate a new ScheduleData for the instruction.
7720   if (ChunkPos >= ChunkSize) {
7721     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7722     ChunkPos = 0;
7723   }
7724   return &(ScheduleDataChunks.back()[ChunkPos++]);
7725 }
7726 
7727 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7728                                                       const InstructionsState &S) {
7729   if (getScheduleData(V, isOneOf(S, V)))
7730     return true;
7731   Instruction *I = dyn_cast<Instruction>(V);
7732   assert(I && "bundle member must be an instruction");
7733   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7734          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7735          "be scheduled");
7736   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7737     ScheduleData *ISD = getScheduleData(I);
7738     if (!ISD)
7739       return false;
7740     assert(isInSchedulingRegion(ISD) &&
7741            "ScheduleData not in scheduling region");
7742     ScheduleData *SD = allocateScheduleDataChunks();
7743     SD->Inst = I;
7744     SD->init(SchedulingRegionID, S.OpValue);
7745     ExtraScheduleDataMap[I][S.OpValue] = SD;
7746     return true;
7747   };
7748   if (CheckSheduleForI(I))
7749     return true;
7750   if (!ScheduleStart) {
7751     // It's the first instruction in the new region.
7752     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7753     ScheduleStart = I;
7754     ScheduleEnd = I->getNextNode();
7755     if (isOneOf(S, I) != I)
7756       CheckSheduleForI(I);
7757     assert(ScheduleEnd && "tried to vectorize a terminator?");
7758     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7759     return true;
7760   }
7761   // Search up and down at the same time, because we don't know if the new
7762   // instruction is above or below the existing scheduling region.
7763   BasicBlock::reverse_iterator UpIter =
7764       ++ScheduleStart->getIterator().getReverse();
7765   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7766   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7767   BasicBlock::iterator LowerEnd = BB->end();
7768   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7769          &*DownIter != I) {
7770     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7771       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7772       return false;
7773     }
7774 
7775     ++UpIter;
7776     ++DownIter;
7777   }
7778   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7779     assert(I->getParent() == ScheduleStart->getParent() &&
7780            "Instruction is in wrong basic block.");
7781     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7782     ScheduleStart = I;
7783     if (isOneOf(S, I) != I)
7784       CheckSheduleForI(I);
7785     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7786                       << "\n");
7787     return true;
7788   }
7789   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7790          "Expected to reach top of the basic block or instruction down the "
7791          "lower end.");
7792   assert(I->getParent() == ScheduleEnd->getParent() &&
7793          "Instruction is in wrong basic block.");
7794   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7795                    nullptr);
7796   ScheduleEnd = I->getNextNode();
7797   if (isOneOf(S, I) != I)
7798     CheckSheduleForI(I);
7799   assert(ScheduleEnd && "tried to vectorize a terminator?");
7800   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7801   return true;
7802 }
7803 
7804 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7805                                                 Instruction *ToI,
7806                                                 ScheduleData *PrevLoadStore,
7807                                                 ScheduleData *NextLoadStore) {
7808   ScheduleData *CurrentLoadStore = PrevLoadStore;
7809   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7810     ScheduleData *SD = ScheduleDataMap[I];
7811     if (!SD) {
7812       SD = allocateScheduleDataChunks();
7813       ScheduleDataMap[I] = SD;
7814       SD->Inst = I;
7815     }
7816     assert(!isInSchedulingRegion(SD) &&
7817            "new ScheduleData already in scheduling region");
7818     SD->init(SchedulingRegionID, I);
7819 
7820     if (I->mayReadOrWriteMemory() &&
7821         (!isa<IntrinsicInst>(I) ||
7822          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7823           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7824               Intrinsic::pseudoprobe))) {
7825       // Update the linked list of memory accessing instructions.
7826       if (CurrentLoadStore) {
7827         CurrentLoadStore->NextLoadStore = SD;
7828       } else {
7829         FirstLoadStoreInRegion = SD;
7830       }
7831       CurrentLoadStore = SD;
7832     }
7833   }
7834   if (NextLoadStore) {
7835     if (CurrentLoadStore)
7836       CurrentLoadStore->NextLoadStore = NextLoadStore;
7837   } else {
7838     LastLoadStoreInRegion = CurrentLoadStore;
7839   }
7840 }
7841 
7842 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7843                                                      bool InsertInReadyList,
7844                                                      BoUpSLP *SLP) {
7845   assert(SD->isSchedulingEntity());
7846 
7847   SmallVector<ScheduleData *, 10> WorkList;
7848   WorkList.push_back(SD);
7849 
7850   while (!WorkList.empty()) {
7851     ScheduleData *SD = WorkList.pop_back_val();
7852     for (ScheduleData *BundleMember = SD; BundleMember;
7853          BundleMember = BundleMember->NextInBundle) {
7854       assert(isInSchedulingRegion(BundleMember));
7855       if (BundleMember->hasValidDependencies())
7856         continue;
7857 
7858       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7859                  << "\n");
7860       BundleMember->Dependencies = 0;
7861       BundleMember->resetUnscheduledDeps();
7862 
7863       // Handle def-use chain dependencies.
7864       if (BundleMember->OpValue != BundleMember->Inst) {
7865         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
7866           BundleMember->Dependencies++;
7867           ScheduleData *DestBundle = UseSD->FirstInBundle;
7868           if (!DestBundle->IsScheduled)
7869             BundleMember->incrementUnscheduledDeps(1);
7870           if (!DestBundle->hasValidDependencies())
7871             WorkList.push_back(DestBundle);
7872         }
7873       } else {
7874         for (User *U : BundleMember->Inst->users()) {
7875           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
7876             BundleMember->Dependencies++;
7877             ScheduleData *DestBundle = UseSD->FirstInBundle;
7878             if (!DestBundle->IsScheduled)
7879               BundleMember->incrementUnscheduledDeps(1);
7880             if (!DestBundle->hasValidDependencies())
7881               WorkList.push_back(DestBundle);
7882           }
7883         }
7884       }
7885 
7886       // Handle the memory dependencies (if any).
7887       ScheduleData *DepDest = BundleMember->NextLoadStore;
7888       if (!DepDest)
7889         continue;
7890       Instruction *SrcInst = BundleMember->Inst;
7891       assert(SrcInst->mayReadOrWriteMemory() &&
7892              "NextLoadStore list for non memory effecting bundle?");
7893       MemoryLocation SrcLoc = getLocation(SrcInst);
7894       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7895       unsigned numAliased = 0;
7896       unsigned DistToSrc = 1;
7897 
7898       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7899         assert(isInSchedulingRegion(DepDest));
7900 
7901         // We have two limits to reduce the complexity:
7902         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7903         //    SLP->isAliased (which is the expensive part in this loop).
7904         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7905         //    the whole loop (even if the loop is fast, it's quadratic).
7906         //    It's important for the loop break condition (see below) to
7907         //    check this limit even between two read-only instructions.
7908         if (DistToSrc >= MaxMemDepDistance ||
7909             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7910              (numAliased >= AliasedCheckLimit ||
7911               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7912 
7913           // We increment the counter only if the locations are aliased
7914           // (instead of counting all alias checks). This gives a better
7915           // balance between reduced runtime and accurate dependencies.
7916           numAliased++;
7917 
7918           DepDest->MemoryDependencies.push_back(BundleMember);
7919           BundleMember->Dependencies++;
7920           ScheduleData *DestBundle = DepDest->FirstInBundle;
7921           if (!DestBundle->IsScheduled) {
7922             BundleMember->incrementUnscheduledDeps(1);
7923           }
7924           if (!DestBundle->hasValidDependencies()) {
7925             WorkList.push_back(DestBundle);
7926           }
7927         }
7928 
7929         // Example, explaining the loop break condition: Let's assume our
7930         // starting instruction is i0 and MaxMemDepDistance = 3.
7931         //
7932         //                      +--------v--v--v
7933         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7934         //             +--------^--^--^
7935         //
7936         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7937         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7938         // Previously we already added dependencies from i3 to i6,i7,i8
7939         // (because of MaxMemDepDistance). As we added a dependency from
7940         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7941         // and we can abort this loop at i6.
7942         if (DistToSrc >= 2 * MaxMemDepDistance)
7943           break;
7944         DistToSrc++;
7945       }
7946     }
7947     if (InsertInReadyList && SD->isReady()) {
7948       ReadyInsts.insert(SD);
7949       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7950                         << "\n");
7951     }
7952   }
7953 }
7954 
7955 void BoUpSLP::BlockScheduling::resetSchedule() {
7956   assert(ScheduleStart &&
7957          "tried to reset schedule on block which has not been scheduled");
7958   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7959     doForAllOpcodes(I, [&](ScheduleData *SD) {
7960       assert(isInSchedulingRegion(SD) &&
7961              "ScheduleData not in scheduling region");
7962       SD->IsScheduled = false;
7963       SD->resetUnscheduledDeps();
7964     });
7965   }
7966   ReadyInsts.clear();
7967 }
7968 
7969 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7970   if (!BS->ScheduleStart)
7971     return;
7972 
7973   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7974 
7975   // A key point - if we got here, pre-scheduling was able to find a valid
7976   // scheduling of the sub-graph of the scheduling window which consists
7977   // of all vector bundles and their transitive users.  As such, we do not
7978   // need to reschedule anything *outside of* that subgraph.
7979 
7980   BS->resetSchedule();
7981 
7982   // For the real scheduling we use a more sophisticated ready-list: it is
7983   // sorted by the original instruction location. This lets the final schedule
7984   // be as  close as possible to the original instruction order.
7985   DenseMap<ScheduleData *, unsigned> OriginalOrder;
7986   auto ScheduleDataCompare = [&](ScheduleData *SD1, ScheduleData *SD2) {
7987     return OriginalOrder[SD2] < OriginalOrder[SD1];
7988   };
7989   std::set<ScheduleData *, decltype(ScheduleDataCompare)>
7990     ReadyInsts(ScheduleDataCompare);
7991 
7992   // Ensure that all dependency data is updated (for nodes in the sub-graph)
7993   // and fill the ready-list with initial instructions.
7994   int Idx = 0;
7995   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7996        I = I->getNextNode()) {
7997     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
7998       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7999               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
8000              "scheduler and vectorizer bundle mismatch");
8001       OriginalOrder[SD->FirstInBundle] = Idx++;
8002 
8003       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8004         BS->calculateDependencies(SD, false, this);
8005     });
8006   }
8007   BS->initialFillReadyList(ReadyInsts);
8008 
8009   Instruction *LastScheduledInst = BS->ScheduleEnd;
8010 
8011   // Do the "real" scheduling.
8012   while (!ReadyInsts.empty()) {
8013     ScheduleData *picked = *ReadyInsts.begin();
8014     ReadyInsts.erase(ReadyInsts.begin());
8015 
8016     // Move the scheduled instruction(s) to their dedicated places, if not
8017     // there yet.
8018     for (ScheduleData *BundleMember = picked; BundleMember;
8019          BundleMember = BundleMember->NextInBundle) {
8020       Instruction *pickedInst = BundleMember->Inst;
8021       if (pickedInst->getNextNode() != LastScheduledInst)
8022         pickedInst->moveBefore(LastScheduledInst);
8023       LastScheduledInst = pickedInst;
8024     }
8025 
8026     BS->schedule(picked, ReadyInsts);
8027   }
8028 
8029   // Check that we didn't break any of our invariants.
8030 #ifdef EXPENSIVE_CHECKS
8031   BS->verify();
8032 #endif
8033 
8034 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8035   // Check that all schedulable entities got scheduled
8036   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8037     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8038       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8039         assert(SD->IsScheduled && "must be scheduled at this point");
8040       }
8041     });
8042   }
8043 #endif
8044 
8045   // Avoid duplicate scheduling of the block.
8046   BS->ScheduleStart = nullptr;
8047 }
8048 
8049 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8050   // If V is a store, just return the width of the stored value (or value
8051   // truncated just before storing) without traversing the expression tree.
8052   // This is the common case.
8053   if (auto *Store = dyn_cast<StoreInst>(V)) {
8054     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8055       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8056     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8057   }
8058 
8059   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8060     return getVectorElementSize(IEI->getOperand(1));
8061 
8062   auto E = InstrElementSize.find(V);
8063   if (E != InstrElementSize.end())
8064     return E->second;
8065 
8066   // If V is not a store, we can traverse the expression tree to find loads
8067   // that feed it. The type of the loaded value may indicate a more suitable
8068   // width than V's type. We want to base the vector element size on the width
8069   // of memory operations where possible.
8070   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8071   SmallPtrSet<Instruction *, 16> Visited;
8072   if (auto *I = dyn_cast<Instruction>(V)) {
8073     Worklist.emplace_back(I, I->getParent());
8074     Visited.insert(I);
8075   }
8076 
8077   // Traverse the expression tree in bottom-up order looking for loads. If we
8078   // encounter an instruction we don't yet handle, we give up.
8079   auto Width = 0u;
8080   while (!Worklist.empty()) {
8081     Instruction *I;
8082     BasicBlock *Parent;
8083     std::tie(I, Parent) = Worklist.pop_back_val();
8084 
8085     // We should only be looking at scalar instructions here. If the current
8086     // instruction has a vector type, skip.
8087     auto *Ty = I->getType();
8088     if (isa<VectorType>(Ty))
8089       continue;
8090 
8091     // If the current instruction is a load, update MaxWidth to reflect the
8092     // width of the loaded value.
8093     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8094         isa<ExtractValueInst>(I))
8095       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8096 
8097     // Otherwise, we need to visit the operands of the instruction. We only
8098     // handle the interesting cases from buildTree here. If an operand is an
8099     // instruction we haven't yet visited and from the same basic block as the
8100     // user or the use is a PHI node, we add it to the worklist.
8101     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8102              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8103              isa<UnaryOperator>(I)) {
8104       for (Use &U : I->operands())
8105         if (auto *J = dyn_cast<Instruction>(U.get()))
8106           if (Visited.insert(J).second &&
8107               (isa<PHINode>(I) || J->getParent() == Parent))
8108             Worklist.emplace_back(J, J->getParent());
8109     } else {
8110       break;
8111     }
8112   }
8113 
8114   // If we didn't encounter a memory access in the expression tree, or if we
8115   // gave up for some reason, just return the width of V. Otherwise, return the
8116   // maximum width we found.
8117   if (!Width) {
8118     if (auto *CI = dyn_cast<CmpInst>(V))
8119       V = CI->getOperand(0);
8120     Width = DL->getTypeSizeInBits(V->getType());
8121   }
8122 
8123   for (Instruction *I : Visited)
8124     InstrElementSize[I] = Width;
8125 
8126   return Width;
8127 }
8128 
8129 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8130 // smaller type with a truncation. We collect the values that will be demoted
8131 // in ToDemote and additional roots that require investigating in Roots.
8132 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8133                                   SmallVectorImpl<Value *> &ToDemote,
8134                                   SmallVectorImpl<Value *> &Roots) {
8135   // We can always demote constants.
8136   if (isa<Constant>(V)) {
8137     ToDemote.push_back(V);
8138     return true;
8139   }
8140 
8141   // If the value is not an instruction in the expression with only one use, it
8142   // cannot be demoted.
8143   auto *I = dyn_cast<Instruction>(V);
8144   if (!I || !I->hasOneUse() || !Expr.count(I))
8145     return false;
8146 
8147   switch (I->getOpcode()) {
8148 
8149   // We can always demote truncations and extensions. Since truncations can
8150   // seed additional demotion, we save the truncated value.
8151   case Instruction::Trunc:
8152     Roots.push_back(I->getOperand(0));
8153     break;
8154   case Instruction::ZExt:
8155   case Instruction::SExt:
8156     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8157         isa<InsertElementInst>(I->getOperand(0)))
8158       return false;
8159     break;
8160 
8161   // We can demote certain binary operations if we can demote both of their
8162   // operands.
8163   case Instruction::Add:
8164   case Instruction::Sub:
8165   case Instruction::Mul:
8166   case Instruction::And:
8167   case Instruction::Or:
8168   case Instruction::Xor:
8169     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8170         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8171       return false;
8172     break;
8173 
8174   // We can demote selects if we can demote their true and false values.
8175   case Instruction::Select: {
8176     SelectInst *SI = cast<SelectInst>(I);
8177     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8178         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8179       return false;
8180     break;
8181   }
8182 
8183   // We can demote phis if we can demote all their incoming operands. Note that
8184   // we don't need to worry about cycles since we ensure single use above.
8185   case Instruction::PHI: {
8186     PHINode *PN = cast<PHINode>(I);
8187     for (Value *IncValue : PN->incoming_values())
8188       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8189         return false;
8190     break;
8191   }
8192 
8193   // Otherwise, conservatively give up.
8194   default:
8195     return false;
8196   }
8197 
8198   // Record the value that we can demote.
8199   ToDemote.push_back(V);
8200   return true;
8201 }
8202 
8203 void BoUpSLP::computeMinimumValueSizes() {
8204   // If there are no external uses, the expression tree must be rooted by a
8205   // store. We can't demote in-memory values, so there is nothing to do here.
8206   if (ExternalUses.empty())
8207     return;
8208 
8209   // We only attempt to truncate integer expressions.
8210   auto &TreeRoot = VectorizableTree[0]->Scalars;
8211   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8212   if (!TreeRootIT)
8213     return;
8214 
8215   // If the expression is not rooted by a store, these roots should have
8216   // external uses. We will rely on InstCombine to rewrite the expression in
8217   // the narrower type. However, InstCombine only rewrites single-use values.
8218   // This means that if a tree entry other than a root is used externally, it
8219   // must have multiple uses and InstCombine will not rewrite it. The code
8220   // below ensures that only the roots are used externally.
8221   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8222   for (auto &EU : ExternalUses)
8223     if (!Expr.erase(EU.Scalar))
8224       return;
8225   if (!Expr.empty())
8226     return;
8227 
8228   // Collect the scalar values of the vectorizable expression. We will use this
8229   // context to determine which values can be demoted. If we see a truncation,
8230   // we mark it as seeding another demotion.
8231   for (auto &EntryPtr : VectorizableTree)
8232     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8233 
8234   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8235   // have a single external user that is not in the vectorizable tree.
8236   for (auto *Root : TreeRoot)
8237     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8238       return;
8239 
8240   // Conservatively determine if we can actually truncate the roots of the
8241   // expression. Collect the values that can be demoted in ToDemote and
8242   // additional roots that require investigating in Roots.
8243   SmallVector<Value *, 32> ToDemote;
8244   SmallVector<Value *, 4> Roots;
8245   for (auto *Root : TreeRoot)
8246     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8247       return;
8248 
8249   // The maximum bit width required to represent all the values that can be
8250   // demoted without loss of precision. It would be safe to truncate the roots
8251   // of the expression to this width.
8252   auto MaxBitWidth = 8u;
8253 
8254   // We first check if all the bits of the roots are demanded. If they're not,
8255   // we can truncate the roots to this narrower type.
8256   for (auto *Root : TreeRoot) {
8257     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8258     MaxBitWidth = std::max<unsigned>(
8259         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8260   }
8261 
8262   // True if the roots can be zero-extended back to their original type, rather
8263   // than sign-extended. We know that if the leading bits are not demanded, we
8264   // can safely zero-extend. So we initialize IsKnownPositive to True.
8265   bool IsKnownPositive = true;
8266 
8267   // If all the bits of the roots are demanded, we can try a little harder to
8268   // compute a narrower type. This can happen, for example, if the roots are
8269   // getelementptr indices. InstCombine promotes these indices to the pointer
8270   // width. Thus, all their bits are technically demanded even though the
8271   // address computation might be vectorized in a smaller type.
8272   //
8273   // We start by looking at each entry that can be demoted. We compute the
8274   // maximum bit width required to store the scalar by using ValueTracking to
8275   // compute the number of high-order bits we can truncate.
8276   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8277       llvm::all_of(TreeRoot, [](Value *R) {
8278         assert(R->hasOneUse() && "Root should have only one use!");
8279         return isa<GetElementPtrInst>(R->user_back());
8280       })) {
8281     MaxBitWidth = 8u;
8282 
8283     // Determine if the sign bit of all the roots is known to be zero. If not,
8284     // IsKnownPositive is set to False.
8285     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8286       KnownBits Known = computeKnownBits(R, *DL);
8287       return Known.isNonNegative();
8288     });
8289 
8290     // Determine the maximum number of bits required to store the scalar
8291     // values.
8292     for (auto *Scalar : ToDemote) {
8293       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8294       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8295       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8296     }
8297 
8298     // If we can't prove that the sign bit is zero, we must add one to the
8299     // maximum bit width to account for the unknown sign bit. This preserves
8300     // the existing sign bit so we can safely sign-extend the root back to the
8301     // original type. Otherwise, if we know the sign bit is zero, we will
8302     // zero-extend the root instead.
8303     //
8304     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8305     //        one to the maximum bit width will yield a larger-than-necessary
8306     //        type. In general, we need to add an extra bit only if we can't
8307     //        prove that the upper bit of the original type is equal to the
8308     //        upper bit of the proposed smaller type. If these two bits are the
8309     //        same (either zero or one) we know that sign-extending from the
8310     //        smaller type will result in the same value. Here, since we can't
8311     //        yet prove this, we are just making the proposed smaller type
8312     //        larger to ensure correctness.
8313     if (!IsKnownPositive)
8314       ++MaxBitWidth;
8315   }
8316 
8317   // Round MaxBitWidth up to the next power-of-two.
8318   if (!isPowerOf2_64(MaxBitWidth))
8319     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8320 
8321   // If the maximum bit width we compute is less than the with of the roots'
8322   // type, we can proceed with the narrowing. Otherwise, do nothing.
8323   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8324     return;
8325 
8326   // If we can truncate the root, we must collect additional values that might
8327   // be demoted as a result. That is, those seeded by truncations we will
8328   // modify.
8329   while (!Roots.empty())
8330     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8331 
8332   // Finally, map the values we can demote to the maximum bit with we computed.
8333   for (auto *Scalar : ToDemote)
8334     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8335 }
8336 
8337 namespace {
8338 
8339 /// The SLPVectorizer Pass.
8340 struct SLPVectorizer : public FunctionPass {
8341   SLPVectorizerPass Impl;
8342 
8343   /// Pass identification, replacement for typeid
8344   static char ID;
8345 
8346   explicit SLPVectorizer() : FunctionPass(ID) {
8347     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8348   }
8349 
8350   bool doInitialization(Module &M) override { return false; }
8351 
8352   bool runOnFunction(Function &F) override {
8353     if (skipFunction(F))
8354       return false;
8355 
8356     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8357     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8358     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8359     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8360     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8361     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8362     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8363     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8364     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8365     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8366 
8367     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8368   }
8369 
8370   void getAnalysisUsage(AnalysisUsage &AU) const override {
8371     FunctionPass::getAnalysisUsage(AU);
8372     AU.addRequired<AssumptionCacheTracker>();
8373     AU.addRequired<ScalarEvolutionWrapperPass>();
8374     AU.addRequired<AAResultsWrapperPass>();
8375     AU.addRequired<TargetTransformInfoWrapperPass>();
8376     AU.addRequired<LoopInfoWrapperPass>();
8377     AU.addRequired<DominatorTreeWrapperPass>();
8378     AU.addRequired<DemandedBitsWrapperPass>();
8379     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8380     AU.addRequired<InjectTLIMappingsLegacy>();
8381     AU.addPreserved<LoopInfoWrapperPass>();
8382     AU.addPreserved<DominatorTreeWrapperPass>();
8383     AU.addPreserved<AAResultsWrapperPass>();
8384     AU.addPreserved<GlobalsAAWrapperPass>();
8385     AU.setPreservesCFG();
8386   }
8387 };
8388 
8389 } // end anonymous namespace
8390 
8391 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8392   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8393   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8394   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8395   auto *AA = &AM.getResult<AAManager>(F);
8396   auto *LI = &AM.getResult<LoopAnalysis>(F);
8397   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8398   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8399   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8400   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8401 
8402   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8403   if (!Changed)
8404     return PreservedAnalyses::all();
8405 
8406   PreservedAnalyses PA;
8407   PA.preserveSet<CFGAnalyses>();
8408   return PA;
8409 }
8410 
8411 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8412                                 TargetTransformInfo *TTI_,
8413                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8414                                 LoopInfo *LI_, DominatorTree *DT_,
8415                                 AssumptionCache *AC_, DemandedBits *DB_,
8416                                 OptimizationRemarkEmitter *ORE_) {
8417   if (!RunSLPVectorization)
8418     return false;
8419   SE = SE_;
8420   TTI = TTI_;
8421   TLI = TLI_;
8422   AA = AA_;
8423   LI = LI_;
8424   DT = DT_;
8425   AC = AC_;
8426   DB = DB_;
8427   DL = &F.getParent()->getDataLayout();
8428 
8429   Stores.clear();
8430   GEPs.clear();
8431   bool Changed = false;
8432 
8433   // If the target claims to have no vector registers don't attempt
8434   // vectorization.
8435   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8436     LLVM_DEBUG(
8437         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8438     return false;
8439   }
8440 
8441   // Don't vectorize when the attribute NoImplicitFloat is used.
8442   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8443     return false;
8444 
8445   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8446 
8447   // Use the bottom up slp vectorizer to construct chains that start with
8448   // store instructions.
8449   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8450 
8451   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8452   // delete instructions.
8453 
8454   // Update DFS numbers now so that we can use them for ordering.
8455   DT->updateDFSNumbers();
8456 
8457   // Scan the blocks in the function in post order.
8458   for (auto BB : post_order(&F.getEntryBlock())) {
8459     collectSeedInstructions(BB);
8460 
8461     // Vectorize trees that end at stores.
8462     if (!Stores.empty()) {
8463       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8464                         << " underlying objects.\n");
8465       Changed |= vectorizeStoreChains(R);
8466     }
8467 
8468     // Vectorize trees that end at reductions.
8469     Changed |= vectorizeChainsInBlock(BB, R);
8470 
8471     // Vectorize the index computations of getelementptr instructions. This
8472     // is primarily intended to catch gather-like idioms ending at
8473     // non-consecutive loads.
8474     if (!GEPs.empty()) {
8475       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8476                         << " underlying objects.\n");
8477       Changed |= vectorizeGEPIndices(BB, R);
8478     }
8479   }
8480 
8481   if (Changed) {
8482     R.optimizeGatherSequence();
8483     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8484   }
8485   return Changed;
8486 }
8487 
8488 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8489                                             unsigned Idx) {
8490   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8491                     << "\n");
8492   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8493   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8494   unsigned VF = Chain.size();
8495 
8496   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8497     return false;
8498 
8499   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8500                     << "\n");
8501 
8502   R.buildTree(Chain);
8503   if (R.isTreeTinyAndNotFullyVectorizable())
8504     return false;
8505   if (R.isLoadCombineCandidate())
8506     return false;
8507   R.reorderTopToBottom();
8508   R.reorderBottomToTop();
8509   R.buildExternalUses();
8510 
8511   R.computeMinimumValueSizes();
8512 
8513   InstructionCost Cost = R.getTreeCost();
8514 
8515   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8516   if (Cost < -SLPCostThreshold) {
8517     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8518 
8519     using namespace ore;
8520 
8521     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8522                                         cast<StoreInst>(Chain[0]))
8523                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8524                      << " and with tree size "
8525                      << NV("TreeSize", R.getTreeSize()));
8526 
8527     R.vectorizeTree();
8528     return true;
8529   }
8530 
8531   return false;
8532 }
8533 
8534 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8535                                         BoUpSLP &R) {
8536   // We may run into multiple chains that merge into a single chain. We mark the
8537   // stores that we vectorized so that we don't visit the same store twice.
8538   BoUpSLP::ValueSet VectorizedStores;
8539   bool Changed = false;
8540 
8541   int E = Stores.size();
8542   SmallBitVector Tails(E, false);
8543   int MaxIter = MaxStoreLookup.getValue();
8544   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8545       E, std::make_pair(E, INT_MAX));
8546   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8547   int IterCnt;
8548   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8549                                   &CheckedPairs,
8550                                   &ConsecutiveChain](int K, int Idx) {
8551     if (IterCnt >= MaxIter)
8552       return true;
8553     if (CheckedPairs[Idx].test(K))
8554       return ConsecutiveChain[K].second == 1 &&
8555              ConsecutiveChain[K].first == Idx;
8556     ++IterCnt;
8557     CheckedPairs[Idx].set(K);
8558     CheckedPairs[K].set(Idx);
8559     Optional<int> Diff = getPointersDiff(
8560         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8561         Stores[Idx]->getValueOperand()->getType(),
8562         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8563     if (!Diff || *Diff == 0)
8564       return false;
8565     int Val = *Diff;
8566     if (Val < 0) {
8567       if (ConsecutiveChain[Idx].second > -Val) {
8568         Tails.set(K);
8569         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8570       }
8571       return false;
8572     }
8573     if (ConsecutiveChain[K].second <= Val)
8574       return false;
8575 
8576     Tails.set(Idx);
8577     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8578     return Val == 1;
8579   };
8580   // Do a quadratic search on all of the given stores in reverse order and find
8581   // all of the pairs of stores that follow each other.
8582   for (int Idx = E - 1; Idx >= 0; --Idx) {
8583     // If a store has multiple consecutive store candidates, search according
8584     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8585     // This is because usually pairing with immediate succeeding or preceding
8586     // candidate create the best chance to find slp vectorization opportunity.
8587     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8588     IterCnt = 0;
8589     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8590       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8591           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8592         break;
8593   }
8594 
8595   // Tracks if we tried to vectorize stores starting from the given tail
8596   // already.
8597   SmallBitVector TriedTails(E, false);
8598   // For stores that start but don't end a link in the chain:
8599   for (int Cnt = E; Cnt > 0; --Cnt) {
8600     int I = Cnt - 1;
8601     if (ConsecutiveChain[I].first == E || Tails.test(I))
8602       continue;
8603     // We found a store instr that starts a chain. Now follow the chain and try
8604     // to vectorize it.
8605     BoUpSLP::ValueList Operands;
8606     // Collect the chain into a list.
8607     while (I != E && !VectorizedStores.count(Stores[I])) {
8608       Operands.push_back(Stores[I]);
8609       Tails.set(I);
8610       if (ConsecutiveChain[I].second != 1) {
8611         // Mark the new end in the chain and go back, if required. It might be
8612         // required if the original stores come in reversed order, for example.
8613         if (ConsecutiveChain[I].first != E &&
8614             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8615             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8616           TriedTails.set(I);
8617           Tails.reset(ConsecutiveChain[I].first);
8618           if (Cnt < ConsecutiveChain[I].first + 2)
8619             Cnt = ConsecutiveChain[I].first + 2;
8620         }
8621         break;
8622       }
8623       // Move to the next value in the chain.
8624       I = ConsecutiveChain[I].first;
8625     }
8626     assert(!Operands.empty() && "Expected non-empty list of stores.");
8627 
8628     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8629     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8630     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8631 
8632     unsigned MinVF = R.getMinVF(EltSize);
8633     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8634                               MaxElts);
8635 
8636     // FIXME: Is division-by-2 the correct step? Should we assert that the
8637     // register size is a power-of-2?
8638     unsigned StartIdx = 0;
8639     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8640       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8641         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8642         if (!VectorizedStores.count(Slice.front()) &&
8643             !VectorizedStores.count(Slice.back()) &&
8644             vectorizeStoreChain(Slice, R, Cnt)) {
8645           // Mark the vectorized stores so that we don't vectorize them again.
8646           VectorizedStores.insert(Slice.begin(), Slice.end());
8647           Changed = true;
8648           // If we vectorized initial block, no need to try to vectorize it
8649           // again.
8650           if (Cnt == StartIdx)
8651             StartIdx += Size;
8652           Cnt += Size;
8653           continue;
8654         }
8655         ++Cnt;
8656       }
8657       // Check if the whole array was vectorized already - exit.
8658       if (StartIdx >= Operands.size())
8659         break;
8660     }
8661   }
8662 
8663   return Changed;
8664 }
8665 
8666 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8667   // Initialize the collections. We will make a single pass over the block.
8668   Stores.clear();
8669   GEPs.clear();
8670 
8671   // Visit the store and getelementptr instructions in BB and organize them in
8672   // Stores and GEPs according to the underlying objects of their pointer
8673   // operands.
8674   for (Instruction &I : *BB) {
8675     // Ignore store instructions that are volatile or have a pointer operand
8676     // that doesn't point to a scalar type.
8677     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8678       if (!SI->isSimple())
8679         continue;
8680       if (!isValidElementType(SI->getValueOperand()->getType()))
8681         continue;
8682       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8683     }
8684 
8685     // Ignore getelementptr instructions that have more than one index, a
8686     // constant index, or a pointer operand that doesn't point to a scalar
8687     // type.
8688     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8689       auto Idx = GEP->idx_begin()->get();
8690       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8691         continue;
8692       if (!isValidElementType(Idx->getType()))
8693         continue;
8694       if (GEP->getType()->isVectorTy())
8695         continue;
8696       GEPs[GEP->getPointerOperand()].push_back(GEP);
8697     }
8698   }
8699 }
8700 
8701 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8702   if (!A || !B)
8703     return false;
8704   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8705     return false;
8706   Value *VL[] = {A, B};
8707   return tryToVectorizeList(VL, R);
8708 }
8709 
8710 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8711                                            bool LimitForRegisterSize) {
8712   if (VL.size() < 2)
8713     return false;
8714 
8715   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8716                     << VL.size() << ".\n");
8717 
8718   // Check that all of the parts are instructions of the same type,
8719   // we permit an alternate opcode via InstructionsState.
8720   InstructionsState S = getSameOpcode(VL);
8721   if (!S.getOpcode())
8722     return false;
8723 
8724   Instruction *I0 = cast<Instruction>(S.OpValue);
8725   // Make sure invalid types (including vector type) are rejected before
8726   // determining vectorization factor for scalar instructions.
8727   for (Value *V : VL) {
8728     Type *Ty = V->getType();
8729     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8730       // NOTE: the following will give user internal llvm type name, which may
8731       // not be useful.
8732       R.getORE()->emit([&]() {
8733         std::string type_str;
8734         llvm::raw_string_ostream rso(type_str);
8735         Ty->print(rso);
8736         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8737                << "Cannot SLP vectorize list: type "
8738                << rso.str() + " is unsupported by vectorizer";
8739       });
8740       return false;
8741     }
8742   }
8743 
8744   unsigned Sz = R.getVectorElementSize(I0);
8745   unsigned MinVF = R.getMinVF(Sz);
8746   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8747   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8748   if (MaxVF < 2) {
8749     R.getORE()->emit([&]() {
8750       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8751              << "Cannot SLP vectorize list: vectorization factor "
8752              << "less than 2 is not supported";
8753     });
8754     return false;
8755   }
8756 
8757   bool Changed = false;
8758   bool CandidateFound = false;
8759   InstructionCost MinCost = SLPCostThreshold.getValue();
8760   Type *ScalarTy = VL[0]->getType();
8761   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8762     ScalarTy = IE->getOperand(1)->getType();
8763 
8764   unsigned NextInst = 0, MaxInst = VL.size();
8765   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8766     // No actual vectorization should happen, if number of parts is the same as
8767     // provided vectorization factor (i.e. the scalar type is used for vector
8768     // code during codegen).
8769     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8770     if (TTI->getNumberOfParts(VecTy) == VF)
8771       continue;
8772     for (unsigned I = NextInst; I < MaxInst; ++I) {
8773       unsigned OpsWidth = 0;
8774 
8775       if (I + VF > MaxInst)
8776         OpsWidth = MaxInst - I;
8777       else
8778         OpsWidth = VF;
8779 
8780       if (!isPowerOf2_32(OpsWidth))
8781         continue;
8782 
8783       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8784           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8785         break;
8786 
8787       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8788       // Check that a previous iteration of this loop did not delete the Value.
8789       if (llvm::any_of(Ops, [&R](Value *V) {
8790             auto *I = dyn_cast<Instruction>(V);
8791             return I && R.isDeleted(I);
8792           }))
8793         continue;
8794 
8795       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8796                         << "\n");
8797 
8798       R.buildTree(Ops);
8799       if (R.isTreeTinyAndNotFullyVectorizable())
8800         continue;
8801       R.reorderTopToBottom();
8802       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8803       R.buildExternalUses();
8804 
8805       R.computeMinimumValueSizes();
8806       InstructionCost Cost = R.getTreeCost();
8807       CandidateFound = true;
8808       MinCost = std::min(MinCost, Cost);
8809 
8810       if (Cost < -SLPCostThreshold) {
8811         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8812         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8813                                                     cast<Instruction>(Ops[0]))
8814                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8815                                  << " and with tree size "
8816                                  << ore::NV("TreeSize", R.getTreeSize()));
8817 
8818         R.vectorizeTree();
8819         // Move to the next bundle.
8820         I += VF - 1;
8821         NextInst = I + 1;
8822         Changed = true;
8823       }
8824     }
8825   }
8826 
8827   if (!Changed && CandidateFound) {
8828     R.getORE()->emit([&]() {
8829       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8830              << "List vectorization was possible but not beneficial with cost "
8831              << ore::NV("Cost", MinCost) << " >= "
8832              << ore::NV("Treshold", -SLPCostThreshold);
8833     });
8834   } else if (!Changed) {
8835     R.getORE()->emit([&]() {
8836       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8837              << "Cannot SLP vectorize list: vectorization was impossible"
8838              << " with available vectorization factors";
8839     });
8840   }
8841   return Changed;
8842 }
8843 
8844 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8845   if (!I)
8846     return false;
8847 
8848   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8849     return false;
8850 
8851   Value *P = I->getParent();
8852 
8853   // Vectorize in current basic block only.
8854   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8855   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8856   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8857     return false;
8858 
8859   // Try to vectorize V.
8860   if (tryToVectorizePair(Op0, Op1, R))
8861     return true;
8862 
8863   auto *A = dyn_cast<BinaryOperator>(Op0);
8864   auto *B = dyn_cast<BinaryOperator>(Op1);
8865   // Try to skip B.
8866   if (B && B->hasOneUse()) {
8867     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8868     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8869     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8870       return true;
8871     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8872       return true;
8873   }
8874 
8875   // Try to skip A.
8876   if (A && A->hasOneUse()) {
8877     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8878     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8879     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8880       return true;
8881     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8882       return true;
8883   }
8884   return false;
8885 }
8886 
8887 namespace {
8888 
8889 /// Model horizontal reductions.
8890 ///
8891 /// A horizontal reduction is a tree of reduction instructions that has values
8892 /// that can be put into a vector as its leaves. For example:
8893 ///
8894 /// mul mul mul mul
8895 ///  \  /    \  /
8896 ///   +       +
8897 ///    \     /
8898 ///       +
8899 /// This tree has "mul" as its leaf values and "+" as its reduction
8900 /// instructions. A reduction can feed into a store or a binary operation
8901 /// feeding a phi.
8902 ///    ...
8903 ///    \  /
8904 ///     +
8905 ///     |
8906 ///  phi +=
8907 ///
8908 ///  Or:
8909 ///    ...
8910 ///    \  /
8911 ///     +
8912 ///     |
8913 ///   *p =
8914 ///
8915 class HorizontalReduction {
8916   using ReductionOpsType = SmallVector<Value *, 16>;
8917   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8918   ReductionOpsListType ReductionOps;
8919   SmallVector<Value *, 32> ReducedVals;
8920   // Use map vector to make stable output.
8921   MapVector<Instruction *, Value *> ExtraArgs;
8922   WeakTrackingVH ReductionRoot;
8923   /// The type of reduction operation.
8924   RecurKind RdxKind;
8925 
8926   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8927 
8928   static bool isCmpSelMinMax(Instruction *I) {
8929     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8930            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8931   }
8932 
8933   // And/or are potentially poison-safe logical patterns like:
8934   // select x, y, false
8935   // select x, true, y
8936   static bool isBoolLogicOp(Instruction *I) {
8937     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8938            match(I, m_LogicalOr(m_Value(), m_Value()));
8939   }
8940 
8941   /// Checks if instruction is associative and can be vectorized.
8942   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8943     if (Kind == RecurKind::None)
8944       return false;
8945 
8946     // Integer ops that map to select instructions or intrinsics are fine.
8947     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8948         isBoolLogicOp(I))
8949       return true;
8950 
8951     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8952       // FP min/max are associative except for NaN and -0.0. We do not
8953       // have to rule out -0.0 here because the intrinsic semantics do not
8954       // specify a fixed result for it.
8955       return I->getFastMathFlags().noNaNs();
8956     }
8957 
8958     return I->isAssociative();
8959   }
8960 
8961   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8962     // Poison-safe 'or' takes the form: select X, true, Y
8963     // To make that work with the normal operand processing, we skip the
8964     // true value operand.
8965     // TODO: Change the code and data structures to handle this without a hack.
8966     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8967       return I->getOperand(2);
8968     return I->getOperand(Index);
8969   }
8970 
8971   /// Checks if the ParentStackElem.first should be marked as a reduction
8972   /// operation with an extra argument or as extra argument itself.
8973   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8974                     Value *ExtraArg) {
8975     if (ExtraArgs.count(ParentStackElem.first)) {
8976       ExtraArgs[ParentStackElem.first] = nullptr;
8977       // We ran into something like:
8978       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8979       // The whole ParentStackElem.first should be considered as an extra value
8980       // in this case.
8981       // Do not perform analysis of remaining operands of ParentStackElem.first
8982       // instruction, this whole instruction is an extra argument.
8983       ParentStackElem.second = INVALID_OPERAND_INDEX;
8984     } else {
8985       // We ran into something like:
8986       // ParentStackElem.first += ... + ExtraArg + ...
8987       ExtraArgs[ParentStackElem.first] = ExtraArg;
8988     }
8989   }
8990 
8991   /// Creates reduction operation with the current opcode.
8992   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8993                          Value *RHS, const Twine &Name, bool UseSelect) {
8994     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8995     switch (Kind) {
8996     case RecurKind::Or:
8997       if (UseSelect &&
8998           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8999         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9000       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9001                                  Name);
9002     case RecurKind::And:
9003       if (UseSelect &&
9004           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9005         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9006       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9007                                  Name);
9008     case RecurKind::Add:
9009     case RecurKind::Mul:
9010     case RecurKind::Xor:
9011     case RecurKind::FAdd:
9012     case RecurKind::FMul:
9013       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9014                                  Name);
9015     case RecurKind::FMax:
9016       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9017     case RecurKind::FMin:
9018       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9019     case RecurKind::SMax:
9020       if (UseSelect) {
9021         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9022         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9023       }
9024       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9025     case RecurKind::SMin:
9026       if (UseSelect) {
9027         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9028         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9029       }
9030       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9031     case RecurKind::UMax:
9032       if (UseSelect) {
9033         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9034         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9035       }
9036       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9037     case RecurKind::UMin:
9038       if (UseSelect) {
9039         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9040         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9041       }
9042       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9043     default:
9044       llvm_unreachable("Unknown reduction operation.");
9045     }
9046   }
9047 
9048   /// Creates reduction operation with the current opcode with the IR flags
9049   /// from \p ReductionOps.
9050   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9051                          Value *RHS, const Twine &Name,
9052                          const ReductionOpsListType &ReductionOps) {
9053     bool UseSelect = ReductionOps.size() == 2 ||
9054                      // Logical or/and.
9055                      (ReductionOps.size() == 1 &&
9056                       isa<SelectInst>(ReductionOps.front().front()));
9057     assert((!UseSelect || ReductionOps.size() != 2 ||
9058             isa<SelectInst>(ReductionOps[1][0])) &&
9059            "Expected cmp + select pairs for reduction");
9060     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9061     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9062       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9063         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9064         propagateIRFlags(Op, ReductionOps[1]);
9065         return Op;
9066       }
9067     }
9068     propagateIRFlags(Op, ReductionOps[0]);
9069     return Op;
9070   }
9071 
9072   /// Creates reduction operation with the current opcode with the IR flags
9073   /// from \p I.
9074   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9075                          Value *RHS, const Twine &Name, Instruction *I) {
9076     auto *SelI = dyn_cast<SelectInst>(I);
9077     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9078     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9079       if (auto *Sel = dyn_cast<SelectInst>(Op))
9080         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9081     }
9082     propagateIRFlags(Op, I);
9083     return Op;
9084   }
9085 
9086   static RecurKind getRdxKind(Instruction *I) {
9087     assert(I && "Expected instruction for reduction matching");
9088     if (match(I, m_Add(m_Value(), m_Value())))
9089       return RecurKind::Add;
9090     if (match(I, m_Mul(m_Value(), m_Value())))
9091       return RecurKind::Mul;
9092     if (match(I, m_And(m_Value(), m_Value())) ||
9093         match(I, m_LogicalAnd(m_Value(), m_Value())))
9094       return RecurKind::And;
9095     if (match(I, m_Or(m_Value(), m_Value())) ||
9096         match(I, m_LogicalOr(m_Value(), m_Value())))
9097       return RecurKind::Or;
9098     if (match(I, m_Xor(m_Value(), m_Value())))
9099       return RecurKind::Xor;
9100     if (match(I, m_FAdd(m_Value(), m_Value())))
9101       return RecurKind::FAdd;
9102     if (match(I, m_FMul(m_Value(), m_Value())))
9103       return RecurKind::FMul;
9104 
9105     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9106       return RecurKind::FMax;
9107     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9108       return RecurKind::FMin;
9109 
9110     // This matches either cmp+select or intrinsics. SLP is expected to handle
9111     // either form.
9112     // TODO: If we are canonicalizing to intrinsics, we can remove several
9113     //       special-case paths that deal with selects.
9114     if (match(I, m_SMax(m_Value(), m_Value())))
9115       return RecurKind::SMax;
9116     if (match(I, m_SMin(m_Value(), m_Value())))
9117       return RecurKind::SMin;
9118     if (match(I, m_UMax(m_Value(), m_Value())))
9119       return RecurKind::UMax;
9120     if (match(I, m_UMin(m_Value(), m_Value())))
9121       return RecurKind::UMin;
9122 
9123     if (auto *Select = dyn_cast<SelectInst>(I)) {
9124       // Try harder: look for min/max pattern based on instructions producing
9125       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9126       // During the intermediate stages of SLP, it's very common to have
9127       // pattern like this (since optimizeGatherSequence is run only once
9128       // at the end):
9129       // %1 = extractelement <2 x i32> %a, i32 0
9130       // %2 = extractelement <2 x i32> %a, i32 1
9131       // %cond = icmp sgt i32 %1, %2
9132       // %3 = extractelement <2 x i32> %a, i32 0
9133       // %4 = extractelement <2 x i32> %a, i32 1
9134       // %select = select i1 %cond, i32 %3, i32 %4
9135       CmpInst::Predicate Pred;
9136       Instruction *L1;
9137       Instruction *L2;
9138 
9139       Value *LHS = Select->getTrueValue();
9140       Value *RHS = Select->getFalseValue();
9141       Value *Cond = Select->getCondition();
9142 
9143       // TODO: Support inverse predicates.
9144       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9145         if (!isa<ExtractElementInst>(RHS) ||
9146             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9147           return RecurKind::None;
9148       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9149         if (!isa<ExtractElementInst>(LHS) ||
9150             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9151           return RecurKind::None;
9152       } else {
9153         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9154           return RecurKind::None;
9155         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9156             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9157             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9158           return RecurKind::None;
9159       }
9160 
9161       switch (Pred) {
9162       default:
9163         return RecurKind::None;
9164       case CmpInst::ICMP_SGT:
9165       case CmpInst::ICMP_SGE:
9166         return RecurKind::SMax;
9167       case CmpInst::ICMP_SLT:
9168       case CmpInst::ICMP_SLE:
9169         return RecurKind::SMin;
9170       case CmpInst::ICMP_UGT:
9171       case CmpInst::ICMP_UGE:
9172         return RecurKind::UMax;
9173       case CmpInst::ICMP_ULT:
9174       case CmpInst::ICMP_ULE:
9175         return RecurKind::UMin;
9176       }
9177     }
9178     return RecurKind::None;
9179   }
9180 
9181   /// Get the index of the first operand.
9182   static unsigned getFirstOperandIndex(Instruction *I) {
9183     return isCmpSelMinMax(I) ? 1 : 0;
9184   }
9185 
9186   /// Total number of operands in the reduction operation.
9187   static unsigned getNumberOfOperands(Instruction *I) {
9188     return isCmpSelMinMax(I) ? 3 : 2;
9189   }
9190 
9191   /// Checks if the instruction is in basic block \p BB.
9192   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9193   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9194     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9195       auto *Sel = cast<SelectInst>(I);
9196       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9197       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9198     }
9199     return I->getParent() == BB;
9200   }
9201 
9202   /// Expected number of uses for reduction operations/reduced values.
9203   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9204     if (IsCmpSelMinMax) {
9205       // SelectInst must be used twice while the condition op must have single
9206       // use only.
9207       if (auto *Sel = dyn_cast<SelectInst>(I))
9208         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9209       return I->hasNUses(2);
9210     }
9211 
9212     // Arithmetic reduction operation must be used once only.
9213     return I->hasOneUse();
9214   }
9215 
9216   /// Initializes the list of reduction operations.
9217   void initReductionOps(Instruction *I) {
9218     if (isCmpSelMinMax(I))
9219       ReductionOps.assign(2, ReductionOpsType());
9220     else
9221       ReductionOps.assign(1, ReductionOpsType());
9222   }
9223 
9224   /// Add all reduction operations for the reduction instruction \p I.
9225   void addReductionOps(Instruction *I) {
9226     if (isCmpSelMinMax(I)) {
9227       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9228       ReductionOps[1].emplace_back(I);
9229     } else {
9230       ReductionOps[0].emplace_back(I);
9231     }
9232   }
9233 
9234   static Value *getLHS(RecurKind Kind, Instruction *I) {
9235     if (Kind == RecurKind::None)
9236       return nullptr;
9237     return I->getOperand(getFirstOperandIndex(I));
9238   }
9239   static Value *getRHS(RecurKind Kind, Instruction *I) {
9240     if (Kind == RecurKind::None)
9241       return nullptr;
9242     return I->getOperand(getFirstOperandIndex(I) + 1);
9243   }
9244 
9245 public:
9246   HorizontalReduction() = default;
9247 
9248   /// Try to find a reduction tree.
9249   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9250     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9251            "Phi needs to use the binary operator");
9252     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9253             isa<IntrinsicInst>(Inst)) &&
9254            "Expected binop, select, or intrinsic for reduction matching");
9255     RdxKind = getRdxKind(Inst);
9256 
9257     // We could have a initial reductions that is not an add.
9258     //  r *= v1 + v2 + v3 + v4
9259     // In such a case start looking for a tree rooted in the first '+'.
9260     if (Phi) {
9261       if (getLHS(RdxKind, Inst) == Phi) {
9262         Phi = nullptr;
9263         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9264         if (!Inst)
9265           return false;
9266         RdxKind = getRdxKind(Inst);
9267       } else if (getRHS(RdxKind, Inst) == Phi) {
9268         Phi = nullptr;
9269         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9270         if (!Inst)
9271           return false;
9272         RdxKind = getRdxKind(Inst);
9273       }
9274     }
9275 
9276     if (!isVectorizable(RdxKind, Inst))
9277       return false;
9278 
9279     // Analyze "regular" integer/FP types for reductions - no target-specific
9280     // types or pointers.
9281     Type *Ty = Inst->getType();
9282     if (!isValidElementType(Ty) || Ty->isPointerTy())
9283       return false;
9284 
9285     // Though the ultimate reduction may have multiple uses, its condition must
9286     // have only single use.
9287     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9288       if (!Sel->getCondition()->hasOneUse())
9289         return false;
9290 
9291     ReductionRoot = Inst;
9292 
9293     // The opcode for leaf values that we perform a reduction on.
9294     // For example: load(x) + load(y) + load(z) + fptoui(w)
9295     // The leaf opcode for 'w' does not match, so we don't include it as a
9296     // potential candidate for the reduction.
9297     unsigned LeafOpcode = 0;
9298 
9299     // Post-order traverse the reduction tree starting at Inst. We only handle
9300     // true trees containing binary operators or selects.
9301     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9302     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9303     initReductionOps(Inst);
9304     while (!Stack.empty()) {
9305       Instruction *TreeN = Stack.back().first;
9306       unsigned EdgeToVisit = Stack.back().second++;
9307       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9308       bool IsReducedValue = TreeRdxKind != RdxKind;
9309 
9310       // Postorder visit.
9311       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9312         if (IsReducedValue)
9313           ReducedVals.push_back(TreeN);
9314         else {
9315           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9316           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9317             // Check if TreeN is an extra argument of its parent operation.
9318             if (Stack.size() <= 1) {
9319               // TreeN can't be an extra argument as it is a root reduction
9320               // operation.
9321               return false;
9322             }
9323             // Yes, TreeN is an extra argument, do not add it to a list of
9324             // reduction operations.
9325             // Stack[Stack.size() - 2] always points to the parent operation.
9326             markExtraArg(Stack[Stack.size() - 2], TreeN);
9327             ExtraArgs.erase(TreeN);
9328           } else
9329             addReductionOps(TreeN);
9330         }
9331         // Retract.
9332         Stack.pop_back();
9333         continue;
9334       }
9335 
9336       // Visit operands.
9337       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9338       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9339       if (!EdgeInst) {
9340         // Edge value is not a reduction instruction or a leaf instruction.
9341         // (It may be a constant, function argument, or something else.)
9342         markExtraArg(Stack.back(), EdgeVal);
9343         continue;
9344       }
9345       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9346       // Continue analysis if the next operand is a reduction operation or
9347       // (possibly) a leaf value. If the leaf value opcode is not set,
9348       // the first met operation != reduction operation is considered as the
9349       // leaf opcode.
9350       // Only handle trees in the current basic block.
9351       // Each tree node needs to have minimal number of users except for the
9352       // ultimate reduction.
9353       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9354       if (EdgeInst != Phi && EdgeInst != Inst &&
9355           hasSameParent(EdgeInst, Inst->getParent()) &&
9356           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9357           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9358         if (IsRdxInst) {
9359           // We need to be able to reassociate the reduction operations.
9360           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9361             // I is an extra argument for TreeN (its parent operation).
9362             markExtraArg(Stack.back(), EdgeInst);
9363             continue;
9364           }
9365         } else if (!LeafOpcode) {
9366           LeafOpcode = EdgeInst->getOpcode();
9367         }
9368         Stack.push_back(
9369             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9370         continue;
9371       }
9372       // I is an extra argument for TreeN (its parent operation).
9373       markExtraArg(Stack.back(), EdgeInst);
9374     }
9375     return true;
9376   }
9377 
9378   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9379   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9380     // If there are a sufficient number of reduction values, reduce
9381     // to a nearby power-of-2. We can safely generate oversized
9382     // vectors and rely on the backend to split them to legal sizes.
9383     unsigned NumReducedVals = ReducedVals.size();
9384     if (NumReducedVals < 4)
9385       return nullptr;
9386 
9387     // Intersect the fast-math-flags from all reduction operations.
9388     FastMathFlags RdxFMF;
9389     RdxFMF.set();
9390     for (ReductionOpsType &RdxOp : ReductionOps) {
9391       for (Value *RdxVal : RdxOp) {
9392         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9393           RdxFMF &= FPMO->getFastMathFlags();
9394       }
9395     }
9396 
9397     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9398     Builder.setFastMathFlags(RdxFMF);
9399 
9400     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9401     // The same extra argument may be used several times, so log each attempt
9402     // to use it.
9403     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9404       assert(Pair.first && "DebugLoc must be set.");
9405       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9406     }
9407 
9408     // The compare instruction of a min/max is the insertion point for new
9409     // instructions and may be replaced with a new compare instruction.
9410     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9411       assert(isa<SelectInst>(RdxRootInst) &&
9412              "Expected min/max reduction to have select root instruction");
9413       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9414       assert(isa<Instruction>(ScalarCond) &&
9415              "Expected min/max reduction to have compare condition");
9416       return cast<Instruction>(ScalarCond);
9417     };
9418 
9419     // The reduction root is used as the insertion point for new instructions,
9420     // so set it as externally used to prevent it from being deleted.
9421     ExternallyUsedValues[ReductionRoot];
9422     SmallVector<Value *, 16> IgnoreList;
9423     for (ReductionOpsType &RdxOp : ReductionOps)
9424       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9425 
9426     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9427     if (NumReducedVals > ReduxWidth) {
9428       // In the loop below, we are building a tree based on a window of
9429       // 'ReduxWidth' values.
9430       // If the operands of those values have common traits (compare predicate,
9431       // constant operand, etc), then we want to group those together to
9432       // minimize the cost of the reduction.
9433 
9434       // TODO: This should be extended to count common operands for
9435       //       compares and binops.
9436 
9437       // Step 1: Count the number of times each compare predicate occurs.
9438       SmallDenseMap<unsigned, unsigned> PredCountMap;
9439       for (Value *RdxVal : ReducedVals) {
9440         CmpInst::Predicate Pred;
9441         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9442           ++PredCountMap[Pred];
9443       }
9444       // Step 2: Sort the values so the most common predicates come first.
9445       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9446         CmpInst::Predicate PredA, PredB;
9447         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9448             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9449           return PredCountMap[PredA] > PredCountMap[PredB];
9450         }
9451         return false;
9452       });
9453     }
9454 
9455     Value *VectorizedTree = nullptr;
9456     unsigned i = 0;
9457     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9458       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9459       V.buildTree(VL, IgnoreList);
9460       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9461         break;
9462       if (V.isLoadCombineReductionCandidate(RdxKind))
9463         break;
9464       V.reorderTopToBottom();
9465       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9466       V.buildExternalUses(ExternallyUsedValues);
9467 
9468       // For a poison-safe boolean logic reduction, do not replace select
9469       // instructions with logic ops. All reduced values will be frozen (see
9470       // below) to prevent leaking poison.
9471       if (isa<SelectInst>(ReductionRoot) &&
9472           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9473           NumReducedVals != ReduxWidth)
9474         break;
9475 
9476       V.computeMinimumValueSizes();
9477 
9478       // Estimate cost.
9479       InstructionCost TreeCost =
9480           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9481       InstructionCost ReductionCost =
9482           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9483       InstructionCost Cost = TreeCost + ReductionCost;
9484       if (!Cost.isValid()) {
9485         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9486         return nullptr;
9487       }
9488       if (Cost >= -SLPCostThreshold) {
9489         V.getORE()->emit([&]() {
9490           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9491                                           cast<Instruction>(VL[0]))
9492                  << "Vectorizing horizontal reduction is possible"
9493                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9494                  << " and threshold "
9495                  << ore::NV("Threshold", -SLPCostThreshold);
9496         });
9497         break;
9498       }
9499 
9500       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9501                         << Cost << ". (HorRdx)\n");
9502       V.getORE()->emit([&]() {
9503         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9504                                   cast<Instruction>(VL[0]))
9505                << "Vectorized horizontal reduction with cost "
9506                << ore::NV("Cost", Cost) << " and with tree size "
9507                << ore::NV("TreeSize", V.getTreeSize());
9508       });
9509 
9510       // Vectorize a tree.
9511       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9512       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9513 
9514       // Emit a reduction. If the root is a select (min/max idiom), the insert
9515       // point is the compare condition of that select.
9516       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9517       if (isCmpSelMinMax(RdxRootInst))
9518         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9519       else
9520         Builder.SetInsertPoint(RdxRootInst);
9521 
9522       // To prevent poison from leaking across what used to be sequential, safe,
9523       // scalar boolean logic operations, the reduction operand must be frozen.
9524       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9525         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9526 
9527       Value *ReducedSubTree =
9528           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9529 
9530       if (!VectorizedTree) {
9531         // Initialize the final value in the reduction.
9532         VectorizedTree = ReducedSubTree;
9533       } else {
9534         // Update the final value in the reduction.
9535         Builder.SetCurrentDebugLocation(Loc);
9536         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9537                                   ReducedSubTree, "op.rdx", ReductionOps);
9538       }
9539       i += ReduxWidth;
9540       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9541     }
9542 
9543     if (VectorizedTree) {
9544       // Finish the reduction.
9545       for (; i < NumReducedVals; ++i) {
9546         auto *I = cast<Instruction>(ReducedVals[i]);
9547         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9548         VectorizedTree =
9549             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9550       }
9551       for (auto &Pair : ExternallyUsedValues) {
9552         // Add each externally used value to the final reduction.
9553         for (auto *I : Pair.second) {
9554           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9555           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9556                                     Pair.first, "op.extra", I);
9557         }
9558       }
9559 
9560       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9561 
9562       // Mark all scalar reduction ops for deletion, they are replaced by the
9563       // vector reductions.
9564       V.eraseInstructions(IgnoreList);
9565     }
9566     return VectorizedTree;
9567   }
9568 
9569   unsigned numReductionValues() const { return ReducedVals.size(); }
9570 
9571 private:
9572   /// Calculate the cost of a reduction.
9573   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9574                                    Value *FirstReducedVal, unsigned ReduxWidth,
9575                                    FastMathFlags FMF) {
9576     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9577     Type *ScalarTy = FirstReducedVal->getType();
9578     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9579     InstructionCost VectorCost, ScalarCost;
9580     switch (RdxKind) {
9581     case RecurKind::Add:
9582     case RecurKind::Mul:
9583     case RecurKind::Or:
9584     case RecurKind::And:
9585     case RecurKind::Xor:
9586     case RecurKind::FAdd:
9587     case RecurKind::FMul: {
9588       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9589       VectorCost =
9590           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9591       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9592       break;
9593     }
9594     case RecurKind::FMax:
9595     case RecurKind::FMin: {
9596       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9597       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9598       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9599                                                /*IsUnsigned=*/false, CostKind);
9600       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9601       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9602                                            SclCondTy, RdxPred, CostKind) +
9603                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9604                                            SclCondTy, RdxPred, CostKind);
9605       break;
9606     }
9607     case RecurKind::SMax:
9608     case RecurKind::SMin:
9609     case RecurKind::UMax:
9610     case RecurKind::UMin: {
9611       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9612       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9613       bool IsUnsigned =
9614           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9615       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9616                                                CostKind);
9617       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9618       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9619                                            SclCondTy, RdxPred, CostKind) +
9620                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9621                                            SclCondTy, RdxPred, CostKind);
9622       break;
9623     }
9624     default:
9625       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9626     }
9627 
9628     // Scalar cost is repeated for N-1 elements.
9629     ScalarCost *= (ReduxWidth - 1);
9630     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9631                       << " for reduction that starts with " << *FirstReducedVal
9632                       << " (It is a splitting reduction)\n");
9633     return VectorCost - ScalarCost;
9634   }
9635 
9636   /// Emit a horizontal reduction of the vectorized value.
9637   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9638                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9639     assert(VectorizedValue && "Need to have a vectorized tree node");
9640     assert(isPowerOf2_32(ReduxWidth) &&
9641            "We only handle power-of-two reductions for now");
9642     assert(RdxKind != RecurKind::FMulAdd &&
9643            "A call to the llvm.fmuladd intrinsic is not handled yet");
9644 
9645     ++NumVectorInstructions;
9646     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9647   }
9648 };
9649 
9650 } // end anonymous namespace
9651 
9652 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9653   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9654     return cast<FixedVectorType>(IE->getType())->getNumElements();
9655 
9656   unsigned AggregateSize = 1;
9657   auto *IV = cast<InsertValueInst>(InsertInst);
9658   Type *CurrentType = IV->getType();
9659   do {
9660     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9661       for (auto *Elt : ST->elements())
9662         if (Elt != ST->getElementType(0)) // check homogeneity
9663           return None;
9664       AggregateSize *= ST->getNumElements();
9665       CurrentType = ST->getElementType(0);
9666     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9667       AggregateSize *= AT->getNumElements();
9668       CurrentType = AT->getElementType();
9669     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9670       AggregateSize *= VT->getNumElements();
9671       return AggregateSize;
9672     } else if (CurrentType->isSingleValueType()) {
9673       return AggregateSize;
9674     } else {
9675       return None;
9676     }
9677   } while (true);
9678 }
9679 
9680 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9681                                    TargetTransformInfo *TTI,
9682                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9683                                    SmallVectorImpl<Value *> &InsertElts,
9684                                    unsigned OperandOffset) {
9685   do {
9686     Value *InsertedOperand = LastInsertInst->getOperand(1);
9687     Optional<unsigned> OperandIndex =
9688         getInsertIndex(LastInsertInst, OperandOffset);
9689     if (!OperandIndex)
9690       return;
9691     if (isa<InsertElementInst>(InsertedOperand) ||
9692         isa<InsertValueInst>(InsertedOperand)) {
9693       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9694                              BuildVectorOpds, InsertElts, *OperandIndex);
9695 
9696     } else {
9697       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9698       InsertElts[*OperandIndex] = LastInsertInst;
9699     }
9700     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9701   } while (LastInsertInst != nullptr &&
9702            (isa<InsertValueInst>(LastInsertInst) ||
9703             isa<InsertElementInst>(LastInsertInst)) &&
9704            LastInsertInst->hasOneUse());
9705 }
9706 
9707 /// Recognize construction of vectors like
9708 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9709 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9710 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9711 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9712 ///  starting from the last insertelement or insertvalue instruction.
9713 ///
9714 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9715 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9716 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9717 ///
9718 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9719 ///
9720 /// \return true if it matches.
9721 static bool findBuildAggregate(Instruction *LastInsertInst,
9722                                TargetTransformInfo *TTI,
9723                                SmallVectorImpl<Value *> &BuildVectorOpds,
9724                                SmallVectorImpl<Value *> &InsertElts) {
9725 
9726   assert((isa<InsertElementInst>(LastInsertInst) ||
9727           isa<InsertValueInst>(LastInsertInst)) &&
9728          "Expected insertelement or insertvalue instruction!");
9729 
9730   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9731          "Expected empty result vectors!");
9732 
9733   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9734   if (!AggregateSize)
9735     return false;
9736   BuildVectorOpds.resize(*AggregateSize);
9737   InsertElts.resize(*AggregateSize);
9738 
9739   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9740   llvm::erase_value(BuildVectorOpds, nullptr);
9741   llvm::erase_value(InsertElts, nullptr);
9742   if (BuildVectorOpds.size() >= 2)
9743     return true;
9744 
9745   return false;
9746 }
9747 
9748 /// Try and get a reduction value from a phi node.
9749 ///
9750 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9751 /// if they come from either \p ParentBB or a containing loop latch.
9752 ///
9753 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9754 /// if not possible.
9755 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9756                                 BasicBlock *ParentBB, LoopInfo *LI) {
9757   // There are situations where the reduction value is not dominated by the
9758   // reduction phi. Vectorizing such cases has been reported to cause
9759   // miscompiles. See PR25787.
9760   auto DominatedReduxValue = [&](Value *R) {
9761     return isa<Instruction>(R) &&
9762            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9763   };
9764 
9765   Value *Rdx = nullptr;
9766 
9767   // Return the incoming value if it comes from the same BB as the phi node.
9768   if (P->getIncomingBlock(0) == ParentBB) {
9769     Rdx = P->getIncomingValue(0);
9770   } else if (P->getIncomingBlock(1) == ParentBB) {
9771     Rdx = P->getIncomingValue(1);
9772   }
9773 
9774   if (Rdx && DominatedReduxValue(Rdx))
9775     return Rdx;
9776 
9777   // Otherwise, check whether we have a loop latch to look at.
9778   Loop *BBL = LI->getLoopFor(ParentBB);
9779   if (!BBL)
9780     return nullptr;
9781   BasicBlock *BBLatch = BBL->getLoopLatch();
9782   if (!BBLatch)
9783     return nullptr;
9784 
9785   // There is a loop latch, return the incoming value if it comes from
9786   // that. This reduction pattern occasionally turns up.
9787   if (P->getIncomingBlock(0) == BBLatch) {
9788     Rdx = P->getIncomingValue(0);
9789   } else if (P->getIncomingBlock(1) == BBLatch) {
9790     Rdx = P->getIncomingValue(1);
9791   }
9792 
9793   if (Rdx && DominatedReduxValue(Rdx))
9794     return Rdx;
9795 
9796   return nullptr;
9797 }
9798 
9799 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9800   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9801     return true;
9802   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9803     return true;
9804   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9805     return true;
9806   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9807     return true;
9808   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9809     return true;
9810   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9811     return true;
9812   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9813     return true;
9814   return false;
9815 }
9816 
9817 /// Attempt to reduce a horizontal reduction.
9818 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9819 /// with reduction operators \a Root (or one of its operands) in a basic block
9820 /// \a BB, then check if it can be done. If horizontal reduction is not found
9821 /// and root instruction is a binary operation, vectorization of the operands is
9822 /// attempted.
9823 /// \returns true if a horizontal reduction was matched and reduced or operands
9824 /// of one of the binary instruction were vectorized.
9825 /// \returns false if a horizontal reduction was not matched (or not possible)
9826 /// or no vectorization of any binary operation feeding \a Root instruction was
9827 /// performed.
9828 static bool tryToVectorizeHorReductionOrInstOperands(
9829     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9830     TargetTransformInfo *TTI,
9831     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9832   if (!ShouldVectorizeHor)
9833     return false;
9834 
9835   if (!Root)
9836     return false;
9837 
9838   if (Root->getParent() != BB || isa<PHINode>(Root))
9839     return false;
9840   // Start analysis starting from Root instruction. If horizontal reduction is
9841   // found, try to vectorize it. If it is not a horizontal reduction or
9842   // vectorization is not possible or not effective, and currently analyzed
9843   // instruction is a binary operation, try to vectorize the operands, using
9844   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9845   // the same procedure considering each operand as a possible root of the
9846   // horizontal reduction.
9847   // Interrupt the process if the Root instruction itself was vectorized or all
9848   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9849   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9850   // CmpInsts so we can skip extra attempts in
9851   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9852   std::queue<std::pair<Instruction *, unsigned>> Stack;
9853   Stack.emplace(Root, 0);
9854   SmallPtrSet<Value *, 8> VisitedInstrs;
9855   SmallVector<WeakTrackingVH> PostponedInsts;
9856   bool Res = false;
9857   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9858                                      Value *&B1) -> Value * {
9859     bool IsBinop = matchRdxBop(Inst, B0, B1);
9860     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9861     if (IsBinop || IsSelect) {
9862       HorizontalReduction HorRdx;
9863       if (HorRdx.matchAssociativeReduction(P, Inst))
9864         return HorRdx.tryToReduce(R, TTI);
9865     }
9866     return nullptr;
9867   };
9868   while (!Stack.empty()) {
9869     Instruction *Inst;
9870     unsigned Level;
9871     std::tie(Inst, Level) = Stack.front();
9872     Stack.pop();
9873     // Do not try to analyze instruction that has already been vectorized.
9874     // This may happen when we vectorize instruction operands on a previous
9875     // iteration while stack was populated before that happened.
9876     if (R.isDeleted(Inst))
9877       continue;
9878     Value *B0 = nullptr, *B1 = nullptr;
9879     if (Value *V = TryToReduce(Inst, B0, B1)) {
9880       Res = true;
9881       // Set P to nullptr to avoid re-analysis of phi node in
9882       // matchAssociativeReduction function unless this is the root node.
9883       P = nullptr;
9884       if (auto *I = dyn_cast<Instruction>(V)) {
9885         // Try to find another reduction.
9886         Stack.emplace(I, Level);
9887         continue;
9888       }
9889     } else {
9890       bool IsBinop = B0 && B1;
9891       if (P && IsBinop) {
9892         Inst = dyn_cast<Instruction>(B0);
9893         if (Inst == P)
9894           Inst = dyn_cast<Instruction>(B1);
9895         if (!Inst) {
9896           // Set P to nullptr to avoid re-analysis of phi node in
9897           // matchAssociativeReduction function unless this is the root node.
9898           P = nullptr;
9899           continue;
9900         }
9901       }
9902       // Set P to nullptr to avoid re-analysis of phi node in
9903       // matchAssociativeReduction function unless this is the root node.
9904       P = nullptr;
9905       // Do not try to vectorize CmpInst operands, this is done separately.
9906       // Final attempt for binop args vectorization should happen after the loop
9907       // to try to find reductions.
9908       if (!isa<CmpInst>(Inst))
9909         PostponedInsts.push_back(Inst);
9910     }
9911 
9912     // Try to vectorize operands.
9913     // Continue analysis for the instruction from the same basic block only to
9914     // save compile time.
9915     if (++Level < RecursionMaxDepth)
9916       for (auto *Op : Inst->operand_values())
9917         if (VisitedInstrs.insert(Op).second)
9918           if (auto *I = dyn_cast<Instruction>(Op))
9919             // Do not try to vectorize CmpInst operands,  this is done
9920             // separately.
9921             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9922                 I->getParent() == BB)
9923               Stack.emplace(I, Level);
9924   }
9925   // Try to vectorized binops where reductions were not found.
9926   for (Value *V : PostponedInsts)
9927     if (auto *Inst = dyn_cast<Instruction>(V))
9928       if (!R.isDeleted(Inst))
9929         Res |= Vectorize(Inst, R);
9930   return Res;
9931 }
9932 
9933 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9934                                                  BasicBlock *BB, BoUpSLP &R,
9935                                                  TargetTransformInfo *TTI) {
9936   auto *I = dyn_cast_or_null<Instruction>(V);
9937   if (!I)
9938     return false;
9939 
9940   if (!isa<BinaryOperator>(I))
9941     P = nullptr;
9942   // Try to match and vectorize a horizontal reduction.
9943   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9944     return tryToVectorize(I, R);
9945   };
9946   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9947                                                   ExtraVectorization);
9948 }
9949 
9950 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9951                                                  BasicBlock *BB, BoUpSLP &R) {
9952   const DataLayout &DL = BB->getModule()->getDataLayout();
9953   if (!R.canMapToVector(IVI->getType(), DL))
9954     return false;
9955 
9956   SmallVector<Value *, 16> BuildVectorOpds;
9957   SmallVector<Value *, 16> BuildVectorInsts;
9958   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9959     return false;
9960 
9961   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9962   // Aggregate value is unlikely to be processed in vector register.
9963   return tryToVectorizeList(BuildVectorOpds, R);
9964 }
9965 
9966 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9967                                                    BasicBlock *BB, BoUpSLP &R) {
9968   SmallVector<Value *, 16> BuildVectorInsts;
9969   SmallVector<Value *, 16> BuildVectorOpds;
9970   SmallVector<int> Mask;
9971   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9972       (llvm::all_of(
9973            BuildVectorOpds,
9974            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9975        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9976     return false;
9977 
9978   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9979   return tryToVectorizeList(BuildVectorInsts, R);
9980 }
9981 
9982 template <typename T>
9983 static bool
9984 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9985                        function_ref<unsigned(T *)> Limit,
9986                        function_ref<bool(T *, T *)> Comparator,
9987                        function_ref<bool(T *, T *)> AreCompatible,
9988                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9989                        bool LimitForRegisterSize) {
9990   bool Changed = false;
9991   // Sort by type, parent, operands.
9992   stable_sort(Incoming, Comparator);
9993 
9994   // Try to vectorize elements base on their type.
9995   SmallVector<T *> Candidates;
9996   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9997     // Look for the next elements with the same type, parent and operand
9998     // kinds.
9999     auto *SameTypeIt = IncIt;
10000     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10001       ++SameTypeIt;
10002 
10003     // Try to vectorize them.
10004     unsigned NumElts = (SameTypeIt - IncIt);
10005     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10006                       << NumElts << ")\n");
10007     // The vectorization is a 3-state attempt:
10008     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10009     // size of maximal register at first.
10010     // 2. Try to vectorize remaining instructions with the same type, if
10011     // possible. This may result in the better vectorization results rather than
10012     // if we try just to vectorize instructions with the same/alternate opcodes.
10013     // 3. Final attempt to try to vectorize all instructions with the
10014     // same/alternate ops only, this may result in some extra final
10015     // vectorization.
10016     if (NumElts > 1 &&
10017         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10018       // Success start over because instructions might have been changed.
10019       Changed = true;
10020     } else if (NumElts < Limit(*IncIt) &&
10021                (Candidates.empty() ||
10022                 Candidates.front()->getType() == (*IncIt)->getType())) {
10023       Candidates.append(IncIt, std::next(IncIt, NumElts));
10024     }
10025     // Final attempt to vectorize instructions with the same types.
10026     if (Candidates.size() > 1 &&
10027         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10028       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10029         // Success start over because instructions might have been changed.
10030         Changed = true;
10031       } else if (LimitForRegisterSize) {
10032         // Try to vectorize using small vectors.
10033         for (auto *It = Candidates.begin(), *End = Candidates.end();
10034              It != End;) {
10035           auto *SameTypeIt = It;
10036           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10037             ++SameTypeIt;
10038           unsigned NumElts = (SameTypeIt - It);
10039           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10040                                             /*LimitForRegisterSize=*/false))
10041             Changed = true;
10042           It = SameTypeIt;
10043         }
10044       }
10045       Candidates.clear();
10046     }
10047 
10048     // Start over at the next instruction of a different type (or the end).
10049     IncIt = SameTypeIt;
10050   }
10051   return Changed;
10052 }
10053 
10054 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10055 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10056 /// operands. If IsCompatibility is false, function implements strict weak
10057 /// ordering relation between two cmp instructions, returning true if the first
10058 /// instruction is "less" than the second, i.e. its predicate is less than the
10059 /// predicate of the second or the operands IDs are less than the operands IDs
10060 /// of the second cmp instruction.
10061 template <bool IsCompatibility>
10062 static bool compareCmp(Value *V, Value *V2,
10063                        function_ref<bool(Instruction *)> IsDeleted) {
10064   auto *CI1 = cast<CmpInst>(V);
10065   auto *CI2 = cast<CmpInst>(V2);
10066   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10067     return false;
10068   if (CI1->getOperand(0)->getType()->getTypeID() <
10069       CI2->getOperand(0)->getType()->getTypeID())
10070     return !IsCompatibility;
10071   if (CI1->getOperand(0)->getType()->getTypeID() >
10072       CI2->getOperand(0)->getType()->getTypeID())
10073     return false;
10074   CmpInst::Predicate Pred1 = CI1->getPredicate();
10075   CmpInst::Predicate Pred2 = CI2->getPredicate();
10076   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10077   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10078   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10079   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10080   if (BasePred1 < BasePred2)
10081     return !IsCompatibility;
10082   if (BasePred1 > BasePred2)
10083     return false;
10084   // Compare operands.
10085   bool LEPreds = Pred1 <= Pred2;
10086   bool GEPreds = Pred1 >= Pred2;
10087   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10088     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10089     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10090     if (Op1->getValueID() < Op2->getValueID())
10091       return !IsCompatibility;
10092     if (Op1->getValueID() > Op2->getValueID())
10093       return false;
10094     if (auto *I1 = dyn_cast<Instruction>(Op1))
10095       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10096         if (I1->getParent() != I2->getParent())
10097           return false;
10098         InstructionsState S = getSameOpcode({I1, I2});
10099         if (S.getOpcode())
10100           continue;
10101         return false;
10102       }
10103   }
10104   return IsCompatibility;
10105 }
10106 
10107 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10108     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10109     bool AtTerminator) {
10110   bool OpsChanged = false;
10111   SmallVector<Instruction *, 4> PostponedCmps;
10112   for (auto *I : reverse(Instructions)) {
10113     if (R.isDeleted(I))
10114       continue;
10115     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10116       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10117     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10118       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10119     else if (isa<CmpInst>(I))
10120       PostponedCmps.push_back(I);
10121   }
10122   if (AtTerminator) {
10123     // Try to find reductions first.
10124     for (Instruction *I : PostponedCmps) {
10125       if (R.isDeleted(I))
10126         continue;
10127       for (Value *Op : I->operands())
10128         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10129     }
10130     // Try to vectorize operands as vector bundles.
10131     for (Instruction *I : PostponedCmps) {
10132       if (R.isDeleted(I))
10133         continue;
10134       OpsChanged |= tryToVectorize(I, R);
10135     }
10136     // Try to vectorize list of compares.
10137     // Sort by type, compare predicate, etc.
10138     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10139       return compareCmp<false>(V, V2,
10140                                [&R](Instruction *I) { return R.isDeleted(I); });
10141     };
10142 
10143     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10144       if (V1 == V2)
10145         return true;
10146       return compareCmp<true>(V1, V2,
10147                               [&R](Instruction *I) { return R.isDeleted(I); });
10148     };
10149     auto Limit = [&R](Value *V) {
10150       unsigned EltSize = R.getVectorElementSize(V);
10151       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10152     };
10153 
10154     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10155     OpsChanged |= tryToVectorizeSequence<Value>(
10156         Vals, Limit, CompareSorter, AreCompatibleCompares,
10157         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10158           // Exclude possible reductions from other blocks.
10159           bool ArePossiblyReducedInOtherBlock =
10160               any_of(Candidates, [](Value *V) {
10161                 return any_of(V->users(), [V](User *U) {
10162                   return isa<SelectInst>(U) &&
10163                          cast<SelectInst>(U)->getParent() !=
10164                              cast<Instruction>(V)->getParent();
10165                 });
10166               });
10167           if (ArePossiblyReducedInOtherBlock)
10168             return false;
10169           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10170         },
10171         /*LimitForRegisterSize=*/true);
10172     Instructions.clear();
10173   } else {
10174     // Insert in reverse order since the PostponedCmps vector was filled in
10175     // reverse order.
10176     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10177   }
10178   return OpsChanged;
10179 }
10180 
10181 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10182   bool Changed = false;
10183   SmallVector<Value *, 4> Incoming;
10184   SmallPtrSet<Value *, 16> VisitedInstrs;
10185   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10186   // node. Allows better to identify the chains that can be vectorized in the
10187   // better way.
10188   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10189   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10190     assert(isValidElementType(V1->getType()) &&
10191            isValidElementType(V2->getType()) &&
10192            "Expected vectorizable types only.");
10193     // It is fine to compare type IDs here, since we expect only vectorizable
10194     // types, like ints, floats and pointers, we don't care about other type.
10195     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10196       return true;
10197     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10198       return false;
10199     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10200     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10201     if (Opcodes1.size() < Opcodes2.size())
10202       return true;
10203     if (Opcodes1.size() > Opcodes2.size())
10204       return false;
10205     Optional<bool> ConstOrder;
10206     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10207       // Undefs are compatible with any other value.
10208       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10209         if (!ConstOrder)
10210           ConstOrder =
10211               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10212         continue;
10213       }
10214       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10215         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10216           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10217           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10218           if (!NodeI1)
10219             return NodeI2 != nullptr;
10220           if (!NodeI2)
10221             return false;
10222           assert((NodeI1 == NodeI2) ==
10223                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10224                  "Different nodes should have different DFS numbers");
10225           if (NodeI1 != NodeI2)
10226             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10227           InstructionsState S = getSameOpcode({I1, I2});
10228           if (S.getOpcode())
10229             continue;
10230           return I1->getOpcode() < I2->getOpcode();
10231         }
10232       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10233         if (!ConstOrder)
10234           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10235         continue;
10236       }
10237       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10238         return true;
10239       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10240         return false;
10241     }
10242     return ConstOrder && *ConstOrder;
10243   };
10244   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10245     if (V1 == V2)
10246       return true;
10247     if (V1->getType() != V2->getType())
10248       return false;
10249     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10250     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10251     if (Opcodes1.size() != Opcodes2.size())
10252       return false;
10253     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10254       // Undefs are compatible with any other value.
10255       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10256         continue;
10257       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10258         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10259           if (I1->getParent() != I2->getParent())
10260             return false;
10261           InstructionsState S = getSameOpcode({I1, I2});
10262           if (S.getOpcode())
10263             continue;
10264           return false;
10265         }
10266       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10267         continue;
10268       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10269         return false;
10270     }
10271     return true;
10272   };
10273   auto Limit = [&R](Value *V) {
10274     unsigned EltSize = R.getVectorElementSize(V);
10275     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10276   };
10277 
10278   bool HaveVectorizedPhiNodes = false;
10279   do {
10280     // Collect the incoming values from the PHIs.
10281     Incoming.clear();
10282     for (Instruction &I : *BB) {
10283       PHINode *P = dyn_cast<PHINode>(&I);
10284       if (!P)
10285         break;
10286 
10287       // No need to analyze deleted, vectorized and non-vectorizable
10288       // instructions.
10289       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10290           isValidElementType(P->getType()))
10291         Incoming.push_back(P);
10292     }
10293 
10294     // Find the corresponding non-phi nodes for better matching when trying to
10295     // build the tree.
10296     for (Value *V : Incoming) {
10297       SmallVectorImpl<Value *> &Opcodes =
10298           PHIToOpcodes.try_emplace(V).first->getSecond();
10299       if (!Opcodes.empty())
10300         continue;
10301       SmallVector<Value *, 4> Nodes(1, V);
10302       SmallPtrSet<Value *, 4> Visited;
10303       while (!Nodes.empty()) {
10304         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10305         if (!Visited.insert(PHI).second)
10306           continue;
10307         for (Value *V : PHI->incoming_values()) {
10308           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10309             Nodes.push_back(PHI1);
10310             continue;
10311           }
10312           Opcodes.emplace_back(V);
10313         }
10314       }
10315     }
10316 
10317     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10318         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10319         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10320           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10321         },
10322         /*LimitForRegisterSize=*/true);
10323     Changed |= HaveVectorizedPhiNodes;
10324     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10325   } while (HaveVectorizedPhiNodes);
10326 
10327   VisitedInstrs.clear();
10328 
10329   SmallVector<Instruction *, 8> PostProcessInstructions;
10330   SmallDenseSet<Instruction *, 4> KeyNodes;
10331   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10332     // Skip instructions with scalable type. The num of elements is unknown at
10333     // compile-time for scalable type.
10334     if (isa<ScalableVectorType>(it->getType()))
10335       continue;
10336 
10337     // Skip instructions marked for the deletion.
10338     if (R.isDeleted(&*it))
10339       continue;
10340     // We may go through BB multiple times so skip the one we have checked.
10341     if (!VisitedInstrs.insert(&*it).second) {
10342       if (it->use_empty() && KeyNodes.contains(&*it) &&
10343           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10344                                       it->isTerminator())) {
10345         // We would like to start over since some instructions are deleted
10346         // and the iterator may become invalid value.
10347         Changed = true;
10348         it = BB->begin();
10349         e = BB->end();
10350       }
10351       continue;
10352     }
10353 
10354     if (isa<DbgInfoIntrinsic>(it))
10355       continue;
10356 
10357     // Try to vectorize reductions that use PHINodes.
10358     if (PHINode *P = dyn_cast<PHINode>(it)) {
10359       // Check that the PHI is a reduction PHI.
10360       if (P->getNumIncomingValues() == 2) {
10361         // Try to match and vectorize a horizontal reduction.
10362         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10363                                      TTI)) {
10364           Changed = true;
10365           it = BB->begin();
10366           e = BB->end();
10367           continue;
10368         }
10369       }
10370       // Try to vectorize the incoming values of the PHI, to catch reductions
10371       // that feed into PHIs.
10372       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10373         // Skip if the incoming block is the current BB for now. Also, bypass
10374         // unreachable IR for efficiency and to avoid crashing.
10375         // TODO: Collect the skipped incoming values and try to vectorize them
10376         // after processing BB.
10377         if (BB == P->getIncomingBlock(I) ||
10378             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10379           continue;
10380 
10381         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10382                                             P->getIncomingBlock(I), R, TTI);
10383       }
10384       continue;
10385     }
10386 
10387     // Ran into an instruction without users, like terminator, or function call
10388     // with ignored return value, store. Ignore unused instructions (basing on
10389     // instruction type, except for CallInst and InvokeInst).
10390     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10391                             isa<InvokeInst>(it))) {
10392       KeyNodes.insert(&*it);
10393       bool OpsChanged = false;
10394       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10395         for (auto *V : it->operand_values()) {
10396           // Try to match and vectorize a horizontal reduction.
10397           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10398         }
10399       }
10400       // Start vectorization of post-process list of instructions from the
10401       // top-tree instructions to try to vectorize as many instructions as
10402       // possible.
10403       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10404                                                 it->isTerminator());
10405       if (OpsChanged) {
10406         // We would like to start over since some instructions are deleted
10407         // and the iterator may become invalid value.
10408         Changed = true;
10409         it = BB->begin();
10410         e = BB->end();
10411         continue;
10412       }
10413     }
10414 
10415     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10416         isa<InsertValueInst>(it))
10417       PostProcessInstructions.push_back(&*it);
10418   }
10419 
10420   return Changed;
10421 }
10422 
10423 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10424   auto Changed = false;
10425   for (auto &Entry : GEPs) {
10426     // If the getelementptr list has fewer than two elements, there's nothing
10427     // to do.
10428     if (Entry.second.size() < 2)
10429       continue;
10430 
10431     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10432                       << Entry.second.size() << ".\n");
10433 
10434     // Process the GEP list in chunks suitable for the target's supported
10435     // vector size. If a vector register can't hold 1 element, we are done. We
10436     // are trying to vectorize the index computations, so the maximum number of
10437     // elements is based on the size of the index expression, rather than the
10438     // size of the GEP itself (the target's pointer size).
10439     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10440     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10441     if (MaxVecRegSize < EltSize)
10442       continue;
10443 
10444     unsigned MaxElts = MaxVecRegSize / EltSize;
10445     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10446       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10447       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10448 
10449       // Initialize a set a candidate getelementptrs. Note that we use a
10450       // SetVector here to preserve program order. If the index computations
10451       // are vectorizable and begin with loads, we want to minimize the chance
10452       // of having to reorder them later.
10453       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10454 
10455       // Some of the candidates may have already been vectorized after we
10456       // initially collected them. If so, they are marked as deleted, so remove
10457       // them from the set of candidates.
10458       Candidates.remove_if(
10459           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10460 
10461       // Remove from the set of candidates all pairs of getelementptrs with
10462       // constant differences. Such getelementptrs are likely not good
10463       // candidates for vectorization in a bottom-up phase since one can be
10464       // computed from the other. We also ensure all candidate getelementptr
10465       // indices are unique.
10466       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10467         auto *GEPI = GEPList[I];
10468         if (!Candidates.count(GEPI))
10469           continue;
10470         auto *SCEVI = SE->getSCEV(GEPList[I]);
10471         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10472           auto *GEPJ = GEPList[J];
10473           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10474           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10475             Candidates.remove(GEPI);
10476             Candidates.remove(GEPJ);
10477           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10478             Candidates.remove(GEPJ);
10479           }
10480         }
10481       }
10482 
10483       // We break out of the above computation as soon as we know there are
10484       // fewer than two candidates remaining.
10485       if (Candidates.size() < 2)
10486         continue;
10487 
10488       // Add the single, non-constant index of each candidate to the bundle. We
10489       // ensured the indices met these constraints when we originally collected
10490       // the getelementptrs.
10491       SmallVector<Value *, 16> Bundle(Candidates.size());
10492       auto BundleIndex = 0u;
10493       for (auto *V : Candidates) {
10494         auto *GEP = cast<GetElementPtrInst>(V);
10495         auto *GEPIdx = GEP->idx_begin()->get();
10496         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10497         Bundle[BundleIndex++] = GEPIdx;
10498       }
10499 
10500       // Try and vectorize the indices. We are currently only interested in
10501       // gather-like cases of the form:
10502       //
10503       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10504       //
10505       // where the loads of "a", the loads of "b", and the subtractions can be
10506       // performed in parallel. It's likely that detecting this pattern in a
10507       // bottom-up phase will be simpler and less costly than building a
10508       // full-blown top-down phase beginning at the consecutive loads.
10509       Changed |= tryToVectorizeList(Bundle, R);
10510     }
10511   }
10512   return Changed;
10513 }
10514 
10515 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10516   bool Changed = false;
10517   // Sort by type, base pointers and values operand. Value operands must be
10518   // compatible (have the same opcode, same parent), otherwise it is
10519   // definitely not profitable to try to vectorize them.
10520   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10521     if (V->getPointerOperandType()->getTypeID() <
10522         V2->getPointerOperandType()->getTypeID())
10523       return true;
10524     if (V->getPointerOperandType()->getTypeID() >
10525         V2->getPointerOperandType()->getTypeID())
10526       return false;
10527     // UndefValues are compatible with all other values.
10528     if (isa<UndefValue>(V->getValueOperand()) ||
10529         isa<UndefValue>(V2->getValueOperand()))
10530       return false;
10531     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10532       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10533         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10534             DT->getNode(I1->getParent());
10535         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10536             DT->getNode(I2->getParent());
10537         assert(NodeI1 && "Should only process reachable instructions");
10538         assert(NodeI1 && "Should only process reachable instructions");
10539         assert((NodeI1 == NodeI2) ==
10540                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10541                "Different nodes should have different DFS numbers");
10542         if (NodeI1 != NodeI2)
10543           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10544         InstructionsState S = getSameOpcode({I1, I2});
10545         if (S.getOpcode())
10546           return false;
10547         return I1->getOpcode() < I2->getOpcode();
10548       }
10549     if (isa<Constant>(V->getValueOperand()) &&
10550         isa<Constant>(V2->getValueOperand()))
10551       return false;
10552     return V->getValueOperand()->getValueID() <
10553            V2->getValueOperand()->getValueID();
10554   };
10555 
10556   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10557     if (V1 == V2)
10558       return true;
10559     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10560       return false;
10561     // Undefs are compatible with any other value.
10562     if (isa<UndefValue>(V1->getValueOperand()) ||
10563         isa<UndefValue>(V2->getValueOperand()))
10564       return true;
10565     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10566       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10567         if (I1->getParent() != I2->getParent())
10568           return false;
10569         InstructionsState S = getSameOpcode({I1, I2});
10570         return S.getOpcode() > 0;
10571       }
10572     if (isa<Constant>(V1->getValueOperand()) &&
10573         isa<Constant>(V2->getValueOperand()))
10574       return true;
10575     return V1->getValueOperand()->getValueID() ==
10576            V2->getValueOperand()->getValueID();
10577   };
10578   auto Limit = [&R, this](StoreInst *SI) {
10579     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10580     return R.getMinVF(EltSize);
10581   };
10582 
10583   // Attempt to sort and vectorize each of the store-groups.
10584   for (auto &Pair : Stores) {
10585     if (Pair.second.size() < 2)
10586       continue;
10587 
10588     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10589                       << Pair.second.size() << ".\n");
10590 
10591     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10592       continue;
10593 
10594     Changed |= tryToVectorizeSequence<StoreInst>(
10595         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10596         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10597           return vectorizeStores(Candidates, R);
10598         },
10599         /*LimitForRegisterSize=*/false);
10600   }
10601   return Changed;
10602 }
10603 
10604 char SLPVectorizer::ID = 0;
10605 
10606 static const char lv_name[] = "SLP Vectorizer";
10607 
10608 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10609 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10610 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10611 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10612 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10613 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10614 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10615 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10616 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10617 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10618 
10619 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10620