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     /// Used for getting a "good" final ordering of instructions.
2628     int SchedulingPriority = 0;
2629 
2630     /// The number of dependencies. Constitutes of the number of users of the
2631     /// instruction plus the number of dependent memory instructions (if any).
2632     /// This value is calculated on demand.
2633     /// If InvalidDeps, the number of dependencies is not calculated yet.
2634     int Dependencies = InvalidDeps;
2635 
2636     /// The number of dependencies minus the number of dependencies of scheduled
2637     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2638     /// for scheduling.
2639     /// Note that this is negative as long as Dependencies is not calculated.
2640     int UnscheduledDeps = InvalidDeps;
2641 
2642     /// The lane of this node in the TreeEntry.
2643     int Lane = -1;
2644 
2645     /// True if this instruction is scheduled (or considered as scheduled in the
2646     /// dry-run).
2647     bool IsScheduled = false;
2648   };
2649 
2650 #ifndef NDEBUG
2651   friend inline raw_ostream &operator<<(raw_ostream &os,
2652                                         const BoUpSLP::ScheduleData &SD) {
2653     SD.dump(os);
2654     return os;
2655   }
2656 #endif
2657 
2658   friend struct GraphTraits<BoUpSLP *>;
2659   friend struct DOTGraphTraits<BoUpSLP *>;
2660 
2661   /// Contains all scheduling data for a basic block.
2662   struct BlockScheduling {
2663     BlockScheduling(BasicBlock *BB)
2664         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2665 
2666     void clear() {
2667       ReadyInsts.clear();
2668       ScheduleStart = nullptr;
2669       ScheduleEnd = nullptr;
2670       FirstLoadStoreInRegion = nullptr;
2671       LastLoadStoreInRegion = nullptr;
2672 
2673       // Reduce the maximum schedule region size by the size of the
2674       // previous scheduling run.
2675       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2676       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2677         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2678       ScheduleRegionSize = 0;
2679 
2680       // Make a new scheduling region, i.e. all existing ScheduleData is not
2681       // in the new region yet.
2682       ++SchedulingRegionID;
2683     }
2684 
2685     ScheduleData *getScheduleData(Instruction *I) {
2686       if (BB != I->getParent())
2687         // Avoid lookup if can't possibly be in map.
2688         return nullptr;
2689       ScheduleData *SD = ScheduleDataMap[I];
2690       if (SD && isInSchedulingRegion(SD))
2691         return SD;
2692       return nullptr;
2693     }
2694 
2695     ScheduleData *getScheduleData(Value *V) {
2696       if (auto *I = dyn_cast<Instruction>(V))
2697         return getScheduleData(I);
2698       return nullptr;
2699     }
2700 
2701     ScheduleData *getScheduleData(Value *V, Value *Key) {
2702       if (V == Key)
2703         return getScheduleData(V);
2704       auto I = ExtraScheduleDataMap.find(V);
2705       if (I != ExtraScheduleDataMap.end()) {
2706         ScheduleData *SD = I->second[Key];
2707         if (SD && isInSchedulingRegion(SD))
2708           return SD;
2709       }
2710       return nullptr;
2711     }
2712 
2713     bool isInSchedulingRegion(ScheduleData *SD) const {
2714       return SD->SchedulingRegionID == SchedulingRegionID;
2715     }
2716 
2717     /// Marks an instruction as scheduled and puts all dependent ready
2718     /// instructions into the ready-list.
2719     template <typename ReadyListType>
2720     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2721       SD->IsScheduled = true;
2722       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2723 
2724       for (ScheduleData *BundleMember = SD; BundleMember;
2725            BundleMember = BundleMember->NextInBundle) {
2726         if (BundleMember->Inst != BundleMember->OpValue)
2727           continue;
2728 
2729         // Handle the def-use chain dependencies.
2730 
2731         // Decrement the unscheduled counter and insert to ready list if ready.
2732         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2733           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2734             if (OpDef && OpDef->hasValidDependencies() &&
2735                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2736               // There are no more unscheduled dependencies after
2737               // decrementing, so we can put the dependent instruction
2738               // into the ready list.
2739               ScheduleData *DepBundle = OpDef->FirstInBundle;
2740               assert(!DepBundle->IsScheduled &&
2741                      "already scheduled bundle gets ready");
2742               ReadyList.insert(DepBundle);
2743               LLVM_DEBUG(dbgs()
2744                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2745             }
2746           });
2747         };
2748 
2749         // If BundleMember is a vector bundle, its operands may have been
2750         // reordered during buildTree(). We therefore need to get its operands
2751         // through the TreeEntry.
2752         if (TreeEntry *TE = BundleMember->TE) {
2753           int Lane = BundleMember->Lane;
2754           assert(Lane >= 0 && "Lane not set");
2755 
2756           // Since vectorization tree is being built recursively this assertion
2757           // ensures that the tree entry has all operands set before reaching
2758           // this code. Couple of exceptions known at the moment are extracts
2759           // where their second (immediate) operand is not added. Since
2760           // immediates do not affect scheduler behavior this is considered
2761           // okay.
2762           auto *In = TE->getMainOp();
2763           assert(In &&
2764                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2765                   In->getNumOperands() == TE->getNumOperands()) &&
2766                  "Missed TreeEntry operands?");
2767           (void)In; // fake use to avoid build failure when assertions disabled
2768 
2769           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2770                OpIdx != NumOperands; ++OpIdx)
2771             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2772               DecrUnsched(I);
2773         } else {
2774           // If BundleMember is a stand-alone instruction, no operand reordering
2775           // has taken place, so we directly access its operands.
2776           for (Use &U : BundleMember->Inst->operands())
2777             if (auto *I = dyn_cast<Instruction>(U.get()))
2778               DecrUnsched(I);
2779         }
2780         // Handle the memory dependencies.
2781         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2782           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2783             // There are no more unscheduled dependencies after decrementing,
2784             // so we can put the dependent instruction into the ready list.
2785             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2786             assert(!DepBundle->IsScheduled &&
2787                    "already scheduled bundle gets ready");
2788             ReadyList.insert(DepBundle);
2789             LLVM_DEBUG(dbgs()
2790                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2791           }
2792         }
2793       }
2794     }
2795 
2796     /// Verify basic self consistency properties of the data structure.
2797     void verify() {
2798       if (!ScheduleStart)
2799         return;
2800 
2801       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2802              ScheduleStart->comesBefore(ScheduleEnd) &&
2803              "Not a valid scheduling region?");
2804 
2805       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2806         auto *SD = getScheduleData(I);
2807         assert(SD && "primary scheduledata must exist in window");
2808         assert(isInSchedulingRegion(SD) &&
2809                "primary schedule data not in window?");
2810         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2811                "entire bundle in window!");
2812         (void)SD;
2813         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2814       }
2815 
2816       for (auto *SD : ReadyInsts) {
2817         assert(SD->isSchedulingEntity() && SD->isReady() &&
2818                "item in ready list not ready?");
2819         (void)SD;
2820       }
2821     }
2822 
2823     void doForAllOpcodes(Value *V,
2824                          function_ref<void(ScheduleData *SD)> Action) {
2825       if (ScheduleData *SD = getScheduleData(V))
2826         Action(SD);
2827       auto I = ExtraScheduleDataMap.find(V);
2828       if (I != ExtraScheduleDataMap.end())
2829         for (auto &P : I->second)
2830           if (isInSchedulingRegion(P.second))
2831             Action(P.second);
2832     }
2833 
2834     /// Put all instructions into the ReadyList which are ready for scheduling.
2835     template <typename ReadyListType>
2836     void initialFillReadyList(ReadyListType &ReadyList) {
2837       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2838         doForAllOpcodes(I, [&](ScheduleData *SD) {
2839           if (SD->isSchedulingEntity() && SD->isReady()) {
2840             ReadyList.insert(SD);
2841             LLVM_DEBUG(dbgs()
2842                        << "SLP:    initially in ready list: " << *SD << "\n");
2843           }
2844         });
2845       }
2846     }
2847 
2848     /// Build a bundle from the ScheduleData nodes corresponding to the
2849     /// scalar instruction for each lane.
2850     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2851 
2852     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2853     /// cyclic dependencies. This is only a dry-run, no instructions are
2854     /// actually moved at this stage.
2855     /// \returns the scheduling bundle. The returned Optional value is non-None
2856     /// if \p VL is allowed to be scheduled.
2857     Optional<ScheduleData *>
2858     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2859                       const InstructionsState &S);
2860 
2861     /// Un-bundles a group of instructions.
2862     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2863 
2864     /// Allocates schedule data chunk.
2865     ScheduleData *allocateScheduleDataChunks();
2866 
2867     /// Extends the scheduling region so that V is inside the region.
2868     /// \returns true if the region size is within the limit.
2869     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2870 
2871     /// Initialize the ScheduleData structures for new instructions in the
2872     /// scheduling region.
2873     void initScheduleData(Instruction *FromI, Instruction *ToI,
2874                           ScheduleData *PrevLoadStore,
2875                           ScheduleData *NextLoadStore);
2876 
2877     /// Updates the dependency information of a bundle and of all instructions/
2878     /// bundles which depend on the original bundle.
2879     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2880                                BoUpSLP *SLP);
2881 
2882     /// Sets all instruction in the scheduling region to un-scheduled.
2883     void resetSchedule();
2884 
2885     BasicBlock *BB;
2886 
2887     /// Simple memory allocation for ScheduleData.
2888     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2889 
2890     /// The size of a ScheduleData array in ScheduleDataChunks.
2891     int ChunkSize;
2892 
2893     /// The allocator position in the current chunk, which is the last entry
2894     /// of ScheduleDataChunks.
2895     int ChunkPos;
2896 
2897     /// Attaches ScheduleData to Instruction.
2898     /// Note that the mapping survives during all vectorization iterations, i.e.
2899     /// ScheduleData structures are recycled.
2900     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2901 
2902     /// Attaches ScheduleData to Instruction with the leading key.
2903     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2904         ExtraScheduleDataMap;
2905 
2906     /// The ready-list for scheduling (only used for the dry-run).
2907     SetVector<ScheduleData *> ReadyInsts;
2908 
2909     /// The first instruction of the scheduling region.
2910     Instruction *ScheduleStart = nullptr;
2911 
2912     /// The first instruction _after_ the scheduling region.
2913     Instruction *ScheduleEnd = nullptr;
2914 
2915     /// The first memory accessing instruction in the scheduling region
2916     /// (can be null).
2917     ScheduleData *FirstLoadStoreInRegion = nullptr;
2918 
2919     /// The last memory accessing instruction in the scheduling region
2920     /// (can be null).
2921     ScheduleData *LastLoadStoreInRegion = nullptr;
2922 
2923     /// The current size of the scheduling region.
2924     int ScheduleRegionSize = 0;
2925 
2926     /// The maximum size allowed for the scheduling region.
2927     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2928 
2929     /// The ID of the scheduling region. For a new vectorization iteration this
2930     /// is incremented which "removes" all ScheduleData from the region.
2931     /// Make sure that the initial SchedulingRegionID is greater than the
2932     /// initial SchedulingRegionID in ScheduleData (which is 0).
2933     int SchedulingRegionID = 1;
2934   };
2935 
2936   /// Attaches the BlockScheduling structures to basic blocks.
2937   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2938 
2939   /// Performs the "real" scheduling. Done before vectorization is actually
2940   /// performed in a basic block.
2941   void scheduleBlock(BlockScheduling *BS);
2942 
2943   /// List of users to ignore during scheduling and that don't need extracting.
2944   ArrayRef<Value *> UserIgnoreList;
2945 
2946   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2947   /// sorted SmallVectors of unsigned.
2948   struct OrdersTypeDenseMapInfo {
2949     static OrdersType getEmptyKey() {
2950       OrdersType V;
2951       V.push_back(~1U);
2952       return V;
2953     }
2954 
2955     static OrdersType getTombstoneKey() {
2956       OrdersType V;
2957       V.push_back(~2U);
2958       return V;
2959     }
2960 
2961     static unsigned getHashValue(const OrdersType &V) {
2962       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2963     }
2964 
2965     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2966       return LHS == RHS;
2967     }
2968   };
2969 
2970   // Analysis and block reference.
2971   Function *F;
2972   ScalarEvolution *SE;
2973   TargetTransformInfo *TTI;
2974   TargetLibraryInfo *TLI;
2975   LoopInfo *LI;
2976   DominatorTree *DT;
2977   AssumptionCache *AC;
2978   DemandedBits *DB;
2979   const DataLayout *DL;
2980   OptimizationRemarkEmitter *ORE;
2981 
2982   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2983   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2984 
2985   /// Instruction builder to construct the vectorized tree.
2986   IRBuilder<> Builder;
2987 
2988   /// A map of scalar integer values to the smallest bit width with which they
2989   /// can legally be represented. The values map to (width, signed) pairs,
2990   /// where "width" indicates the minimum bit width and "signed" is True if the
2991   /// value must be signed-extended, rather than zero-extended, back to its
2992   /// original width.
2993   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2994 };
2995 
2996 } // end namespace slpvectorizer
2997 
2998 template <> struct GraphTraits<BoUpSLP *> {
2999   using TreeEntry = BoUpSLP::TreeEntry;
3000 
3001   /// NodeRef has to be a pointer per the GraphWriter.
3002   using NodeRef = TreeEntry *;
3003 
3004   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3005 
3006   /// Add the VectorizableTree to the index iterator to be able to return
3007   /// TreeEntry pointers.
3008   struct ChildIteratorType
3009       : public iterator_adaptor_base<
3010             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3011     ContainerTy &VectorizableTree;
3012 
3013     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3014                       ContainerTy &VT)
3015         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3016 
3017     NodeRef operator*() { return I->UserTE; }
3018   };
3019 
3020   static NodeRef getEntryNode(BoUpSLP &R) {
3021     return R.VectorizableTree[0].get();
3022   }
3023 
3024   static ChildIteratorType child_begin(NodeRef N) {
3025     return {N->UserTreeIndices.begin(), N->Container};
3026   }
3027 
3028   static ChildIteratorType child_end(NodeRef N) {
3029     return {N->UserTreeIndices.end(), N->Container};
3030   }
3031 
3032   /// For the node iterator we just need to turn the TreeEntry iterator into a
3033   /// TreeEntry* iterator so that it dereferences to NodeRef.
3034   class nodes_iterator {
3035     using ItTy = ContainerTy::iterator;
3036     ItTy It;
3037 
3038   public:
3039     nodes_iterator(const ItTy &It2) : It(It2) {}
3040     NodeRef operator*() { return It->get(); }
3041     nodes_iterator operator++() {
3042       ++It;
3043       return *this;
3044     }
3045     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3046   };
3047 
3048   static nodes_iterator nodes_begin(BoUpSLP *R) {
3049     return nodes_iterator(R->VectorizableTree.begin());
3050   }
3051 
3052   static nodes_iterator nodes_end(BoUpSLP *R) {
3053     return nodes_iterator(R->VectorizableTree.end());
3054   }
3055 
3056   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3057 };
3058 
3059 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3060   using TreeEntry = BoUpSLP::TreeEntry;
3061 
3062   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3063 
3064   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3065     std::string Str;
3066     raw_string_ostream OS(Str);
3067     if (isSplat(Entry->Scalars))
3068       OS << "<splat> ";
3069     for (auto V : Entry->Scalars) {
3070       OS << *V;
3071       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3072             return EU.Scalar == V;
3073           }))
3074         OS << " <extract>";
3075       OS << "\n";
3076     }
3077     return Str;
3078   }
3079 
3080   static std::string getNodeAttributes(const TreeEntry *Entry,
3081                                        const BoUpSLP *) {
3082     if (Entry->State == TreeEntry::NeedToGather)
3083       return "color=red";
3084     return "";
3085   }
3086 };
3087 
3088 } // end namespace llvm
3089 
3090 BoUpSLP::~BoUpSLP() {
3091   for (const auto &Pair : DeletedInstructions) {
3092     // Replace operands of ignored instructions with Undefs in case if they were
3093     // marked for deletion.
3094     if (Pair.getSecond()) {
3095       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3096       Pair.getFirst()->replaceAllUsesWith(Undef);
3097     }
3098     Pair.getFirst()->dropAllReferences();
3099   }
3100   for (const auto &Pair : DeletedInstructions) {
3101     assert(Pair.getFirst()->use_empty() &&
3102            "trying to erase instruction with users.");
3103     Pair.getFirst()->eraseFromParent();
3104   }
3105 #ifdef EXPENSIVE_CHECKS
3106   // If we could guarantee that this call is not extremely slow, we could
3107   // remove the ifdef limitation (see PR47712).
3108   assert(!verifyFunction(*F, &dbgs()));
3109 #endif
3110 }
3111 
3112 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3113   for (auto *V : AV) {
3114     if (auto *I = dyn_cast<Instruction>(V))
3115       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3116   };
3117 }
3118 
3119 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3120 /// contains original mask for the scalars reused in the node. Procedure
3121 /// transform this mask in accordance with the given \p Mask.
3122 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3123   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3124          "Expected non-empty mask.");
3125   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3126   Prev.swap(Reuses);
3127   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3128     if (Mask[I] != UndefMaskElem)
3129       Reuses[Mask[I]] = Prev[I];
3130 }
3131 
3132 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3133 /// the original order of the scalars. Procedure transforms the provided order
3134 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3135 /// identity order, \p Order is cleared.
3136 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3137   assert(!Mask.empty() && "Expected non-empty mask.");
3138   SmallVector<int> MaskOrder;
3139   if (Order.empty()) {
3140     MaskOrder.resize(Mask.size());
3141     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3142   } else {
3143     inversePermutation(Order, MaskOrder);
3144   }
3145   reorderReuses(MaskOrder, Mask);
3146   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3147     Order.clear();
3148     return;
3149   }
3150   Order.assign(Mask.size(), Mask.size());
3151   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3152     if (MaskOrder[I] != UndefMaskElem)
3153       Order[MaskOrder[I]] = I;
3154   fixupOrderingIndices(Order);
3155 }
3156 
3157 Optional<BoUpSLP::OrdersType>
3158 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3159   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3160   unsigned NumScalars = TE.Scalars.size();
3161   OrdersType CurrentOrder(NumScalars, NumScalars);
3162   SmallVector<int> Positions;
3163   SmallBitVector UsedPositions(NumScalars);
3164   const TreeEntry *STE = nullptr;
3165   // Try to find all gathered scalars that are gets vectorized in other
3166   // vectorize node. Here we can have only one single tree vector node to
3167   // correctly identify order of the gathered scalars.
3168   for (unsigned I = 0; I < NumScalars; ++I) {
3169     Value *V = TE.Scalars[I];
3170     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3171       continue;
3172     if (const auto *LocalSTE = getTreeEntry(V)) {
3173       if (!STE)
3174         STE = LocalSTE;
3175       else if (STE != LocalSTE)
3176         // Take the order only from the single vector node.
3177         return None;
3178       unsigned Lane =
3179           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3180       if (Lane >= NumScalars)
3181         return None;
3182       if (CurrentOrder[Lane] != NumScalars) {
3183         if (Lane != I)
3184           continue;
3185         UsedPositions.reset(CurrentOrder[Lane]);
3186       }
3187       // The partial identity (where only some elements of the gather node are
3188       // in the identity order) is good.
3189       CurrentOrder[Lane] = I;
3190       UsedPositions.set(I);
3191     }
3192   }
3193   // Need to keep the order if we have a vector entry and at least 2 scalars or
3194   // the vectorized entry has just 2 scalars.
3195   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3196     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3197       for (unsigned I = 0; I < NumScalars; ++I)
3198         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3199           return false;
3200       return true;
3201     };
3202     if (IsIdentityOrder(CurrentOrder)) {
3203       CurrentOrder.clear();
3204       return CurrentOrder;
3205     }
3206     auto *It = CurrentOrder.begin();
3207     for (unsigned I = 0; I < NumScalars;) {
3208       if (UsedPositions.test(I)) {
3209         ++I;
3210         continue;
3211       }
3212       if (*It == NumScalars) {
3213         *It = I;
3214         ++I;
3215       }
3216       ++It;
3217     }
3218     return CurrentOrder;
3219   }
3220   return None;
3221 }
3222 
3223 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3224                                                          bool TopToBottom) {
3225   // No need to reorder if need to shuffle reuses, still need to shuffle the
3226   // node.
3227   if (!TE.ReuseShuffleIndices.empty())
3228     return None;
3229   if (TE.State == TreeEntry::Vectorize &&
3230       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3231        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3232       !TE.isAltShuffle())
3233     return TE.ReorderIndices;
3234   if (TE.State == TreeEntry::NeedToGather) {
3235     // TODO: add analysis of other gather nodes with extractelement
3236     // instructions and other values/instructions, not only undefs.
3237     if (((TE.getOpcode() == Instruction::ExtractElement &&
3238           !TE.isAltShuffle()) ||
3239          (all_of(TE.Scalars,
3240                  [](Value *V) {
3241                    return isa<UndefValue, ExtractElementInst>(V);
3242                  }) &&
3243           any_of(TE.Scalars,
3244                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3245         all_of(TE.Scalars,
3246                [](Value *V) {
3247                  auto *EE = dyn_cast<ExtractElementInst>(V);
3248                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3249                }) &&
3250         allSameType(TE.Scalars)) {
3251       // Check that gather of extractelements can be represented as
3252       // just a shuffle of a single vector.
3253       OrdersType CurrentOrder;
3254       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3255       if (Reuse || !CurrentOrder.empty()) {
3256         if (!CurrentOrder.empty())
3257           fixupOrderingIndices(CurrentOrder);
3258         return CurrentOrder;
3259       }
3260     }
3261     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3262       return CurrentOrder;
3263   }
3264   return None;
3265 }
3266 
3267 void BoUpSLP::reorderTopToBottom() {
3268   // Maps VF to the graph nodes.
3269   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3270   // ExtractElement gather nodes which can be vectorized and need to handle
3271   // their ordering.
3272   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3273   // Find all reorderable nodes with the given VF.
3274   // Currently the are vectorized stores,loads,extracts + some gathering of
3275   // extracts.
3276   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3277                                  const std::unique_ptr<TreeEntry> &TE) {
3278     if (Optional<OrdersType> CurrentOrder =
3279             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3280       // Do not include ordering for nodes used in the alt opcode vectorization,
3281       // better to reorder them during bottom-to-top stage. If follow the order
3282       // here, it causes reordering of the whole graph though actually it is
3283       // profitable just to reorder the subgraph that starts from the alternate
3284       // opcode vectorization node. Such nodes already end-up with the shuffle
3285       // instruction and it is just enough to change this shuffle rather than
3286       // rotate the scalars for the whole graph.
3287       unsigned Cnt = 0;
3288       const TreeEntry *UserTE = TE.get();
3289       while (UserTE && Cnt < RecursionMaxDepth) {
3290         if (UserTE->UserTreeIndices.size() != 1)
3291           break;
3292         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3293               return EI.UserTE->State == TreeEntry::Vectorize &&
3294                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3295             }))
3296           return;
3297         if (UserTE->UserTreeIndices.empty())
3298           UserTE = nullptr;
3299         else
3300           UserTE = UserTE->UserTreeIndices.back().UserTE;
3301         ++Cnt;
3302       }
3303       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3304       if (TE->State != TreeEntry::Vectorize)
3305         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3306     }
3307   });
3308 
3309   // Reorder the graph nodes according to their vectorization factor.
3310   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3311        VF /= 2) {
3312     auto It = VFToOrderedEntries.find(VF);
3313     if (It == VFToOrderedEntries.end())
3314       continue;
3315     // Try to find the most profitable order. We just are looking for the most
3316     // used order and reorder scalar elements in the nodes according to this
3317     // mostly used order.
3318     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3319     // All operands are reordered and used only in this node - propagate the
3320     // most used order to the user node.
3321     MapVector<OrdersType, unsigned,
3322               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3323         OrdersUses;
3324     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3325     for (const TreeEntry *OpTE : OrderedEntries) {
3326       // No need to reorder this nodes, still need to extend and to use shuffle,
3327       // just need to merge reordering shuffle and the reuse shuffle.
3328       if (!OpTE->ReuseShuffleIndices.empty())
3329         continue;
3330       // Count number of orders uses.
3331       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3332         if (OpTE->State == TreeEntry::NeedToGather)
3333           return GathersToOrders.find(OpTE)->second;
3334         return OpTE->ReorderIndices;
3335       }();
3336       // Stores actually store the mask, not the order, need to invert.
3337       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3338           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3339         SmallVector<int> Mask;
3340         inversePermutation(Order, Mask);
3341         unsigned E = Order.size();
3342         OrdersType CurrentOrder(E, E);
3343         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3344           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3345         });
3346         fixupOrderingIndices(CurrentOrder);
3347         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3348       } else {
3349         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3350       }
3351     }
3352     // Set order of the user node.
3353     if (OrdersUses.empty())
3354       continue;
3355     // Choose the most used order.
3356     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3357     unsigned Cnt = OrdersUses.front().second;
3358     for (const auto &Pair : drop_begin(OrdersUses)) {
3359       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3360         BestOrder = Pair.first;
3361         Cnt = Pair.second;
3362       }
3363     }
3364     // Set order of the user node.
3365     if (BestOrder.empty())
3366       continue;
3367     SmallVector<int> Mask;
3368     inversePermutation(BestOrder, Mask);
3369     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3370     unsigned E = BestOrder.size();
3371     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3372       return I < E ? static_cast<int>(I) : UndefMaskElem;
3373     });
3374     // Do an actual reordering, if profitable.
3375     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3376       // Just do the reordering for the nodes with the given VF.
3377       if (TE->Scalars.size() != VF) {
3378         if (TE->ReuseShuffleIndices.size() == VF) {
3379           // Need to reorder the reuses masks of the operands with smaller VF to
3380           // be able to find the match between the graph nodes and scalar
3381           // operands of the given node during vectorization/cost estimation.
3382           assert(all_of(TE->UserTreeIndices,
3383                         [VF, &TE](const EdgeInfo &EI) {
3384                           return EI.UserTE->Scalars.size() == VF ||
3385                                  EI.UserTE->Scalars.size() ==
3386                                      TE->Scalars.size();
3387                         }) &&
3388                  "All users must be of VF size.");
3389           // Update ordering of the operands with the smaller VF than the given
3390           // one.
3391           reorderReuses(TE->ReuseShuffleIndices, Mask);
3392         }
3393         continue;
3394       }
3395       if (TE->State == TreeEntry::Vectorize &&
3396           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3397               InsertElementInst>(TE->getMainOp()) &&
3398           !TE->isAltShuffle()) {
3399         // Build correct orders for extract{element,value}, loads and
3400         // stores.
3401         reorderOrder(TE->ReorderIndices, Mask);
3402         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3403           TE->reorderOperands(Mask);
3404       } else {
3405         // Reorder the node and its operands.
3406         TE->reorderOperands(Mask);
3407         assert(TE->ReorderIndices.empty() &&
3408                "Expected empty reorder sequence.");
3409         reorderScalars(TE->Scalars, Mask);
3410       }
3411       if (!TE->ReuseShuffleIndices.empty()) {
3412         // Apply reversed order to keep the original ordering of the reused
3413         // elements to avoid extra reorder indices shuffling.
3414         OrdersType CurrentOrder;
3415         reorderOrder(CurrentOrder, MaskOrder);
3416         SmallVector<int> NewReuses;
3417         inversePermutation(CurrentOrder, NewReuses);
3418         addMask(NewReuses, TE->ReuseShuffleIndices);
3419         TE->ReuseShuffleIndices.swap(NewReuses);
3420       }
3421     }
3422   }
3423 }
3424 
3425 bool BoUpSLP::canReorderOperands(
3426     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3427     ArrayRef<TreeEntry *> ReorderableGathers,
3428     SmallVectorImpl<TreeEntry *> &GatherOps) {
3429   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3430     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3431           return OpData.first == I &&
3432                  OpData.second->State == TreeEntry::Vectorize;
3433         }))
3434       continue;
3435     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3436       // Do not reorder if operand node is used by many user nodes.
3437       if (any_of(TE->UserTreeIndices,
3438                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3439         return false;
3440       // Add the node to the list of the ordered nodes with the identity
3441       // order.
3442       Edges.emplace_back(I, TE);
3443       continue;
3444     }
3445     ArrayRef<Value *> VL = UserTE->getOperand(I);
3446     TreeEntry *Gather = nullptr;
3447     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3448           assert(TE->State != TreeEntry::Vectorize &&
3449                  "Only non-vectorized nodes are expected.");
3450           if (TE->isSame(VL)) {
3451             Gather = TE;
3452             return true;
3453           }
3454           return false;
3455         }) > 1)
3456       return false;
3457     if (Gather)
3458       GatherOps.push_back(Gather);
3459   }
3460   return true;
3461 }
3462 
3463 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3464   SetVector<TreeEntry *> OrderedEntries;
3465   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3466   // Find all reorderable leaf nodes with the given VF.
3467   // Currently the are vectorized loads,extracts without alternate operands +
3468   // some gathering of extracts.
3469   SmallVector<TreeEntry *> NonVectorized;
3470   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3471                               &NonVectorized](
3472                                  const std::unique_ptr<TreeEntry> &TE) {
3473     if (TE->State != TreeEntry::Vectorize)
3474       NonVectorized.push_back(TE.get());
3475     if (Optional<OrdersType> CurrentOrder =
3476             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3477       OrderedEntries.insert(TE.get());
3478       if (TE->State != TreeEntry::Vectorize)
3479         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3480     }
3481   });
3482 
3483   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3484   // I.e., if the node has operands, that are reordered, try to make at least
3485   // one operand order in the natural order and reorder others + reorder the
3486   // user node itself.
3487   SmallPtrSet<const TreeEntry *, 4> Visited;
3488   while (!OrderedEntries.empty()) {
3489     // 1. Filter out only reordered nodes.
3490     // 2. If the entry has multiple uses - skip it and jump to the next node.
3491     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3492     SmallVector<TreeEntry *> Filtered;
3493     for (TreeEntry *TE : OrderedEntries) {
3494       if (!(TE->State == TreeEntry::Vectorize ||
3495             (TE->State == TreeEntry::NeedToGather &&
3496              GathersToOrders.count(TE))) ||
3497           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3498           !all_of(drop_begin(TE->UserTreeIndices),
3499                   [TE](const EdgeInfo &EI) {
3500                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3501                   }) ||
3502           !Visited.insert(TE).second) {
3503         Filtered.push_back(TE);
3504         continue;
3505       }
3506       // Build a map between user nodes and their operands order to speedup
3507       // search. The graph currently does not provide this dependency directly.
3508       for (EdgeInfo &EI : TE->UserTreeIndices) {
3509         TreeEntry *UserTE = EI.UserTE;
3510         auto It = Users.find(UserTE);
3511         if (It == Users.end())
3512           It = Users.insert({UserTE, {}}).first;
3513         It->second.emplace_back(EI.EdgeIdx, TE);
3514       }
3515     }
3516     // Erase filtered entries.
3517     for_each(Filtered,
3518              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3519     for (auto &Data : Users) {
3520       // Check that operands are used only in the User node.
3521       SmallVector<TreeEntry *> GatherOps;
3522       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3523                               GatherOps)) {
3524         for_each(Data.second,
3525                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3526                    OrderedEntries.remove(Op.second);
3527                  });
3528         continue;
3529       }
3530       // All operands are reordered and used only in this node - propagate the
3531       // most used order to the user node.
3532       MapVector<OrdersType, unsigned,
3533                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3534           OrdersUses;
3535       // Do the analysis for each tree entry only once, otherwise the order of
3536       // the same node my be considered several times, though might be not
3537       // profitable.
3538       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3539       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3540       for (const auto &Op : Data.second) {
3541         TreeEntry *OpTE = Op.second;
3542         if (!VisitedOps.insert(OpTE).second)
3543           continue;
3544         if (!OpTE->ReuseShuffleIndices.empty() ||
3545             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3546           continue;
3547         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3548           if (OpTE->State == TreeEntry::NeedToGather)
3549             return GathersToOrders.find(OpTE)->second;
3550           return OpTE->ReorderIndices;
3551         }();
3552         unsigned NumOps = count_if(
3553             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3554               return P.second == OpTE;
3555             });
3556         // Stores actually store the mask, not the order, need to invert.
3557         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3558             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3559           SmallVector<int> Mask;
3560           inversePermutation(Order, Mask);
3561           unsigned E = Order.size();
3562           OrdersType CurrentOrder(E, E);
3563           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3564             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3565           });
3566           fixupOrderingIndices(CurrentOrder);
3567           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3568               NumOps;
3569         } else {
3570           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3571         }
3572         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3573         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3574                                             const TreeEntry *TE) {
3575           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3576               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3577               (IgnoreReorder && TE->Idx == 0))
3578             return true;
3579           if (TE->State == TreeEntry::NeedToGather) {
3580             auto It = GathersToOrders.find(TE);
3581             if (It != GathersToOrders.end())
3582               return !It->second.empty();
3583             return true;
3584           }
3585           return false;
3586         };
3587         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3588           TreeEntry *UserTE = EI.UserTE;
3589           if (!VisitedUsers.insert(UserTE).second)
3590             continue;
3591           // May reorder user node if it requires reordering, has reused
3592           // scalars, is an alternate op vectorize node or its op nodes require
3593           // reordering.
3594           if (AllowsReordering(UserTE))
3595             continue;
3596           // Check if users allow reordering.
3597           // Currently look up just 1 level of operands to avoid increase of
3598           // the compile time.
3599           // Profitable to reorder if definitely more operands allow
3600           // reordering rather than those with natural order.
3601           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3602           if (static_cast<unsigned>(count_if(
3603                   Ops, [UserTE, &AllowsReordering](
3604                            const std::pair<unsigned, TreeEntry *> &Op) {
3605                     return AllowsReordering(Op.second) &&
3606                            all_of(Op.second->UserTreeIndices,
3607                                   [UserTE](const EdgeInfo &EI) {
3608                                     return EI.UserTE == UserTE;
3609                                   });
3610                   })) <= Ops.size() / 2)
3611             ++Res.first->second;
3612         }
3613       }
3614       // If no orders - skip current nodes and jump to the next one, if any.
3615       if (OrdersUses.empty()) {
3616         for_each(Data.second,
3617                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3618                    OrderedEntries.remove(Op.second);
3619                  });
3620         continue;
3621       }
3622       // Choose the best order.
3623       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3624       unsigned Cnt = OrdersUses.front().second;
3625       for (const auto &Pair : drop_begin(OrdersUses)) {
3626         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3627           BestOrder = Pair.first;
3628           Cnt = Pair.second;
3629         }
3630       }
3631       // Set order of the user node (reordering of operands and user nodes).
3632       if (BestOrder.empty()) {
3633         for_each(Data.second,
3634                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3635                    OrderedEntries.remove(Op.second);
3636                  });
3637         continue;
3638       }
3639       // Erase operands from OrderedEntries list and adjust their orders.
3640       VisitedOps.clear();
3641       SmallVector<int> Mask;
3642       inversePermutation(BestOrder, Mask);
3643       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3644       unsigned E = BestOrder.size();
3645       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3646         return I < E ? static_cast<int>(I) : UndefMaskElem;
3647       });
3648       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3649         TreeEntry *TE = Op.second;
3650         OrderedEntries.remove(TE);
3651         if (!VisitedOps.insert(TE).second)
3652           continue;
3653         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3654           // Just reorder reuses indices.
3655           reorderReuses(TE->ReuseShuffleIndices, Mask);
3656           continue;
3657         }
3658         // Gathers are processed separately.
3659         if (TE->State != TreeEntry::Vectorize)
3660           continue;
3661         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3662                 TE->ReorderIndices.empty()) &&
3663                "Non-matching sizes of user/operand entries.");
3664         reorderOrder(TE->ReorderIndices, Mask);
3665       }
3666       // For gathers just need to reorder its scalars.
3667       for (TreeEntry *Gather : GatherOps) {
3668         assert(Gather->ReorderIndices.empty() &&
3669                "Unexpected reordering of gathers.");
3670         if (!Gather->ReuseShuffleIndices.empty()) {
3671           // Just reorder reuses indices.
3672           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3673           continue;
3674         }
3675         reorderScalars(Gather->Scalars, Mask);
3676         OrderedEntries.remove(Gather);
3677       }
3678       // Reorder operands of the user node and set the ordering for the user
3679       // node itself.
3680       if (Data.first->State != TreeEntry::Vectorize ||
3681           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3682               Data.first->getMainOp()) ||
3683           Data.first->isAltShuffle())
3684         Data.first->reorderOperands(Mask);
3685       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3686           Data.first->isAltShuffle()) {
3687         reorderScalars(Data.first->Scalars, Mask);
3688         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3689         if (Data.first->ReuseShuffleIndices.empty() &&
3690             !Data.first->ReorderIndices.empty() &&
3691             !Data.first->isAltShuffle()) {
3692           // Insert user node to the list to try to sink reordering deeper in
3693           // the graph.
3694           OrderedEntries.insert(Data.first);
3695         }
3696       } else {
3697         reorderOrder(Data.first->ReorderIndices, Mask);
3698       }
3699     }
3700   }
3701   // If the reordering is unnecessary, just remove the reorder.
3702   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3703       VectorizableTree.front()->ReuseShuffleIndices.empty())
3704     VectorizableTree.front()->ReorderIndices.clear();
3705 }
3706 
3707 void BoUpSLP::buildExternalUses(
3708     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3709   // Collect the values that we need to extract from the tree.
3710   for (auto &TEPtr : VectorizableTree) {
3711     TreeEntry *Entry = TEPtr.get();
3712 
3713     // No need to handle users of gathered values.
3714     if (Entry->State == TreeEntry::NeedToGather)
3715       continue;
3716 
3717     // For each lane:
3718     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3719       Value *Scalar = Entry->Scalars[Lane];
3720       int FoundLane = Entry->findLaneForValue(Scalar);
3721 
3722       // Check if the scalar is externally used as an extra arg.
3723       auto ExtI = ExternallyUsedValues.find(Scalar);
3724       if (ExtI != ExternallyUsedValues.end()) {
3725         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3726                           << Lane << " from " << *Scalar << ".\n");
3727         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3728       }
3729       for (User *U : Scalar->users()) {
3730         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3731 
3732         Instruction *UserInst = dyn_cast<Instruction>(U);
3733         if (!UserInst)
3734           continue;
3735 
3736         if (isDeleted(UserInst))
3737           continue;
3738 
3739         // Skip in-tree scalars that become vectors
3740         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3741           Value *UseScalar = UseEntry->Scalars[0];
3742           // Some in-tree scalars will remain as scalar in vectorized
3743           // instructions. If that is the case, the one in Lane 0 will
3744           // be used.
3745           if (UseScalar != U ||
3746               UseEntry->State == TreeEntry::ScatterVectorize ||
3747               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3748             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3749                               << ".\n");
3750             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3751             continue;
3752           }
3753         }
3754 
3755         // Ignore users in the user ignore list.
3756         if (is_contained(UserIgnoreList, UserInst))
3757           continue;
3758 
3759         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3760                           << Lane << " from " << *Scalar << ".\n");
3761         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3762       }
3763     }
3764   }
3765 }
3766 
3767 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3768                         ArrayRef<Value *> UserIgnoreLst) {
3769   deleteTree();
3770   UserIgnoreList = UserIgnoreLst;
3771   if (!allSameType(Roots))
3772     return;
3773   buildTree_rec(Roots, 0, EdgeInfo());
3774 }
3775 
3776 namespace {
3777 /// Tracks the state we can represent the loads in the given sequence.
3778 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3779 } // anonymous namespace
3780 
3781 /// Checks if the given array of loads can be represented as a vectorized,
3782 /// scatter or just simple gather.
3783 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3784                                     const TargetTransformInfo &TTI,
3785                                     const DataLayout &DL, ScalarEvolution &SE,
3786                                     SmallVectorImpl<unsigned> &Order,
3787                                     SmallVectorImpl<Value *> &PointerOps) {
3788   // Check that a vectorized load would load the same memory as a scalar
3789   // load. For example, we don't want to vectorize loads that are smaller
3790   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3791   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3792   // from such a struct, we read/write packed bits disagreeing with the
3793   // unvectorized version.
3794   Type *ScalarTy = VL0->getType();
3795 
3796   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3797     return LoadsState::Gather;
3798 
3799   // Make sure all loads in the bundle are simple - we can't vectorize
3800   // atomic or volatile loads.
3801   PointerOps.clear();
3802   PointerOps.resize(VL.size());
3803   auto *POIter = PointerOps.begin();
3804   for (Value *V : VL) {
3805     auto *L = cast<LoadInst>(V);
3806     if (!L->isSimple())
3807       return LoadsState::Gather;
3808     *POIter = L->getPointerOperand();
3809     ++POIter;
3810   }
3811 
3812   Order.clear();
3813   // Check the order of pointer operands.
3814   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3815     Value *Ptr0;
3816     Value *PtrN;
3817     if (Order.empty()) {
3818       Ptr0 = PointerOps.front();
3819       PtrN = PointerOps.back();
3820     } else {
3821       Ptr0 = PointerOps[Order.front()];
3822       PtrN = PointerOps[Order.back()];
3823     }
3824     Optional<int> Diff =
3825         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3826     // Check that the sorted loads are consecutive.
3827     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3828       return LoadsState::Vectorize;
3829     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3830     for (Value *V : VL)
3831       CommonAlignment =
3832           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3833     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3834                                 CommonAlignment))
3835       return LoadsState::ScatterVectorize;
3836   }
3837 
3838   return LoadsState::Gather;
3839 }
3840 
3841 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3842                             const EdgeInfo &UserTreeIdx) {
3843   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3844 
3845   SmallVector<int> ReuseShuffleIndicies;
3846   SmallVector<Value *> UniqueValues;
3847   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3848                                 &UserTreeIdx,
3849                                 this](const InstructionsState &S) {
3850     // Check that every instruction appears once in this bundle.
3851     DenseMap<Value *, unsigned> UniquePositions;
3852     for (Value *V : VL) {
3853       if (isConstant(V)) {
3854         ReuseShuffleIndicies.emplace_back(
3855             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3856         UniqueValues.emplace_back(V);
3857         continue;
3858       }
3859       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3860       ReuseShuffleIndicies.emplace_back(Res.first->second);
3861       if (Res.second)
3862         UniqueValues.emplace_back(V);
3863     }
3864     size_t NumUniqueScalarValues = UniqueValues.size();
3865     if (NumUniqueScalarValues == VL.size()) {
3866       ReuseShuffleIndicies.clear();
3867     } else {
3868       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3869       if (NumUniqueScalarValues <= 1 ||
3870           (UniquePositions.size() == 1 && all_of(UniqueValues,
3871                                                  [](Value *V) {
3872                                                    return isa<UndefValue>(V) ||
3873                                                           !isConstant(V);
3874                                                  })) ||
3875           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3876         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3877         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3878         return false;
3879       }
3880       VL = UniqueValues;
3881     }
3882     return true;
3883   };
3884 
3885   InstructionsState S = getSameOpcode(VL);
3886   if (Depth == RecursionMaxDepth) {
3887     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3888     if (TryToFindDuplicates(S))
3889       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3890                    ReuseShuffleIndicies);
3891     return;
3892   }
3893 
3894   // Don't handle scalable vectors
3895   if (S.getOpcode() == Instruction::ExtractElement &&
3896       isa<ScalableVectorType>(
3897           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3898     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3899     if (TryToFindDuplicates(S))
3900       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3901                    ReuseShuffleIndicies);
3902     return;
3903   }
3904 
3905   // Don't handle vectors.
3906   if (S.OpValue->getType()->isVectorTy() &&
3907       !isa<InsertElementInst>(S.OpValue)) {
3908     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3909     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3910     return;
3911   }
3912 
3913   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3914     if (SI->getValueOperand()->getType()->isVectorTy()) {
3915       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3916       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3917       return;
3918     }
3919 
3920   // If all of the operands are identical or constant we have a simple solution.
3921   // If we deal with insert/extract instructions, they all must have constant
3922   // indices, otherwise we should gather them, not try to vectorize.
3923   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3924       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3925        !all_of(VL, isVectorLikeInstWithConstOps))) {
3926     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3927     if (TryToFindDuplicates(S))
3928       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3929                    ReuseShuffleIndicies);
3930     return;
3931   }
3932 
3933   // We now know that this is a vector of instructions of the same type from
3934   // the same block.
3935 
3936   // Don't vectorize ephemeral values.
3937   for (Value *V : VL) {
3938     if (EphValues.count(V)) {
3939       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3940                         << ") is ephemeral.\n");
3941       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3942       return;
3943     }
3944   }
3945 
3946   // Check if this is a duplicate of another entry.
3947   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3948     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3949     if (!E->isSame(VL)) {
3950       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3951       if (TryToFindDuplicates(S))
3952         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3953                      ReuseShuffleIndicies);
3954       return;
3955     }
3956     // Record the reuse of the tree node.  FIXME, currently this is only used to
3957     // properly draw the graph rather than for the actual vectorization.
3958     E->UserTreeIndices.push_back(UserTreeIdx);
3959     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3960                       << ".\n");
3961     return;
3962   }
3963 
3964   // Check that none of the instructions in the bundle are already in the tree.
3965   for (Value *V : VL) {
3966     auto *I = dyn_cast<Instruction>(V);
3967     if (!I)
3968       continue;
3969     if (getTreeEntry(I)) {
3970       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3971                         << ") is already in tree.\n");
3972       if (TryToFindDuplicates(S))
3973         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3974                      ReuseShuffleIndicies);
3975       return;
3976     }
3977   }
3978 
3979   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3980   for (Value *V : VL) {
3981     if (is_contained(UserIgnoreList, V)) {
3982       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3983       if (TryToFindDuplicates(S))
3984         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3985                      ReuseShuffleIndicies);
3986       return;
3987     }
3988   }
3989 
3990   // Check that all of the users of the scalars that we want to vectorize are
3991   // schedulable.
3992   auto *VL0 = cast<Instruction>(S.OpValue);
3993   BasicBlock *BB = VL0->getParent();
3994 
3995   if (!DT->isReachableFromEntry(BB)) {
3996     // Don't go into unreachable blocks. They may contain instructions with
3997     // dependency cycles which confuse the final scheduling.
3998     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3999     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4000     return;
4001   }
4002 
4003   // Check that every instruction appears once in this bundle.
4004   if (!TryToFindDuplicates(S))
4005     return;
4006 
4007   auto &BSRef = BlocksSchedules[BB];
4008   if (!BSRef)
4009     BSRef = std::make_unique<BlockScheduling>(BB);
4010 
4011   BlockScheduling &BS = *BSRef.get();
4012 
4013   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4014 #ifdef EXPENSIVE_CHECKS
4015   // Make sure we didn't break any internal invariants
4016   BS.verify();
4017 #endif
4018   if (!Bundle) {
4019     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4020     assert((!BS.getScheduleData(VL0) ||
4021             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4022            "tryScheduleBundle should cancelScheduling on failure");
4023     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4024                  ReuseShuffleIndicies);
4025     return;
4026   }
4027   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4028 
4029   unsigned ShuffleOrOp = S.isAltShuffle() ?
4030                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4031   switch (ShuffleOrOp) {
4032     case Instruction::PHI: {
4033       auto *PH = cast<PHINode>(VL0);
4034 
4035       // Check for terminator values (e.g. invoke).
4036       for (Value *V : VL)
4037         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4038           Instruction *Term = dyn_cast<Instruction>(
4039               cast<PHINode>(V)->getIncomingValueForBlock(
4040                   PH->getIncomingBlock(I)));
4041           if (Term && Term->isTerminator()) {
4042             LLVM_DEBUG(dbgs()
4043                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4044             BS.cancelScheduling(VL, VL0);
4045             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4046                          ReuseShuffleIndicies);
4047             return;
4048           }
4049         }
4050 
4051       TreeEntry *TE =
4052           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4053       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4054 
4055       // Keeps the reordered operands to avoid code duplication.
4056       SmallVector<ValueList, 2> OperandsVec;
4057       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4058         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4059           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4060           TE->setOperand(I, Operands);
4061           OperandsVec.push_back(Operands);
4062           continue;
4063         }
4064         ValueList Operands;
4065         // Prepare the operand vector.
4066         for (Value *V : VL)
4067           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4068               PH->getIncomingBlock(I)));
4069         TE->setOperand(I, Operands);
4070         OperandsVec.push_back(Operands);
4071       }
4072       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4073         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4074       return;
4075     }
4076     case Instruction::ExtractValue:
4077     case Instruction::ExtractElement: {
4078       OrdersType CurrentOrder;
4079       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4080       if (Reuse) {
4081         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4082         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4083                      ReuseShuffleIndicies);
4084         // This is a special case, as it does not gather, but at the same time
4085         // we are not extending buildTree_rec() towards the operands.
4086         ValueList Op0;
4087         Op0.assign(VL.size(), VL0->getOperand(0));
4088         VectorizableTree.back()->setOperand(0, Op0);
4089         return;
4090       }
4091       if (!CurrentOrder.empty()) {
4092         LLVM_DEBUG({
4093           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4094                     "with order";
4095           for (unsigned Idx : CurrentOrder)
4096             dbgs() << " " << Idx;
4097           dbgs() << "\n";
4098         });
4099         fixupOrderingIndices(CurrentOrder);
4100         // Insert new order with initial value 0, if it does not exist,
4101         // otherwise return the iterator to the existing one.
4102         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4103                      ReuseShuffleIndicies, CurrentOrder);
4104         // This is a special case, as it does not gather, but at the same time
4105         // we are not extending buildTree_rec() towards the operands.
4106         ValueList Op0;
4107         Op0.assign(VL.size(), VL0->getOperand(0));
4108         VectorizableTree.back()->setOperand(0, Op0);
4109         return;
4110       }
4111       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4112       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4113                    ReuseShuffleIndicies);
4114       BS.cancelScheduling(VL, VL0);
4115       return;
4116     }
4117     case Instruction::InsertElement: {
4118       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4119 
4120       // Check that we have a buildvector and not a shuffle of 2 or more
4121       // different vectors.
4122       ValueSet SourceVectors;
4123       for (Value *V : VL) {
4124         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4125         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4126       }
4127 
4128       if (count_if(VL, [&SourceVectors](Value *V) {
4129             return !SourceVectors.contains(V);
4130           }) >= 2) {
4131         // Found 2nd source vector - cancel.
4132         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4133                              "different source vectors.\n");
4134         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4135         BS.cancelScheduling(VL, VL0);
4136         return;
4137       }
4138 
4139       auto OrdCompare = [](const std::pair<int, int> &P1,
4140                            const std::pair<int, int> &P2) {
4141         return P1.first > P2.first;
4142       };
4143       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4144                     decltype(OrdCompare)>
4145           Indices(OrdCompare);
4146       for (int I = 0, E = VL.size(); I < E; ++I) {
4147         unsigned Idx = *getInsertIndex(VL[I]);
4148         Indices.emplace(Idx, I);
4149       }
4150       OrdersType CurrentOrder(VL.size(), VL.size());
4151       bool IsIdentity = true;
4152       for (int I = 0, E = VL.size(); I < E; ++I) {
4153         CurrentOrder[Indices.top().second] = I;
4154         IsIdentity &= Indices.top().second == I;
4155         Indices.pop();
4156       }
4157       if (IsIdentity)
4158         CurrentOrder.clear();
4159       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4160                                    None, CurrentOrder);
4161       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4162 
4163       constexpr int NumOps = 2;
4164       ValueList VectorOperands[NumOps];
4165       for (int I = 0; I < NumOps; ++I) {
4166         for (Value *V : VL)
4167           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4168 
4169         TE->setOperand(I, VectorOperands[I]);
4170       }
4171       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4172       return;
4173     }
4174     case Instruction::Load: {
4175       // Check that a vectorized load would load the same memory as a scalar
4176       // load. For example, we don't want to vectorize loads that are smaller
4177       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4178       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4179       // from such a struct, we read/write packed bits disagreeing with the
4180       // unvectorized version.
4181       SmallVector<Value *> PointerOps;
4182       OrdersType CurrentOrder;
4183       TreeEntry *TE = nullptr;
4184       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4185                                 PointerOps)) {
4186       case LoadsState::Vectorize:
4187         if (CurrentOrder.empty()) {
4188           // Original loads are consecutive and does not require reordering.
4189           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4190                             ReuseShuffleIndicies);
4191           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4192         } else {
4193           fixupOrderingIndices(CurrentOrder);
4194           // Need to reorder.
4195           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4196                             ReuseShuffleIndicies, CurrentOrder);
4197           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4198         }
4199         TE->setOperandsInOrder();
4200         break;
4201       case LoadsState::ScatterVectorize:
4202         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4203         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4204                           UserTreeIdx, ReuseShuffleIndicies);
4205         TE->setOperandsInOrder();
4206         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4207         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4208         break;
4209       case LoadsState::Gather:
4210         BS.cancelScheduling(VL, VL0);
4211         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4212                      ReuseShuffleIndicies);
4213 #ifndef NDEBUG
4214         Type *ScalarTy = VL0->getType();
4215         if (DL->getTypeSizeInBits(ScalarTy) !=
4216             DL->getTypeAllocSizeInBits(ScalarTy))
4217           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4218         else if (any_of(VL, [](Value *V) {
4219                    return !cast<LoadInst>(V)->isSimple();
4220                  }))
4221           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4222         else
4223           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4224 #endif // NDEBUG
4225         break;
4226       }
4227       return;
4228     }
4229     case Instruction::ZExt:
4230     case Instruction::SExt:
4231     case Instruction::FPToUI:
4232     case Instruction::FPToSI:
4233     case Instruction::FPExt:
4234     case Instruction::PtrToInt:
4235     case Instruction::IntToPtr:
4236     case Instruction::SIToFP:
4237     case Instruction::UIToFP:
4238     case Instruction::Trunc:
4239     case Instruction::FPTrunc:
4240     case Instruction::BitCast: {
4241       Type *SrcTy = VL0->getOperand(0)->getType();
4242       for (Value *V : VL) {
4243         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4244         if (Ty != SrcTy || !isValidElementType(Ty)) {
4245           BS.cancelScheduling(VL, VL0);
4246           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4247                        ReuseShuffleIndicies);
4248           LLVM_DEBUG(dbgs()
4249                      << "SLP: Gathering casts with different src types.\n");
4250           return;
4251         }
4252       }
4253       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4254                                    ReuseShuffleIndicies);
4255       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4256 
4257       TE->setOperandsInOrder();
4258       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4259         ValueList Operands;
4260         // Prepare the operand vector.
4261         for (Value *V : VL)
4262           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4263 
4264         buildTree_rec(Operands, Depth + 1, {TE, i});
4265       }
4266       return;
4267     }
4268     case Instruction::ICmp:
4269     case Instruction::FCmp: {
4270       // Check that all of the compares have the same predicate.
4271       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4272       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4273       Type *ComparedTy = VL0->getOperand(0)->getType();
4274       for (Value *V : VL) {
4275         CmpInst *Cmp = cast<CmpInst>(V);
4276         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4277             Cmp->getOperand(0)->getType() != ComparedTy) {
4278           BS.cancelScheduling(VL, VL0);
4279           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4280                        ReuseShuffleIndicies);
4281           LLVM_DEBUG(dbgs()
4282                      << "SLP: Gathering cmp with different predicate.\n");
4283           return;
4284         }
4285       }
4286 
4287       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4288                                    ReuseShuffleIndicies);
4289       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4290 
4291       ValueList Left, Right;
4292       if (cast<CmpInst>(VL0)->isCommutative()) {
4293         // Commutative predicate - collect + sort operands of the instructions
4294         // so that each side is more likely to have the same opcode.
4295         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4296         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4297       } else {
4298         // Collect operands - commute if it uses the swapped predicate.
4299         for (Value *V : VL) {
4300           auto *Cmp = cast<CmpInst>(V);
4301           Value *LHS = Cmp->getOperand(0);
4302           Value *RHS = Cmp->getOperand(1);
4303           if (Cmp->getPredicate() != P0)
4304             std::swap(LHS, RHS);
4305           Left.push_back(LHS);
4306           Right.push_back(RHS);
4307         }
4308       }
4309       TE->setOperand(0, Left);
4310       TE->setOperand(1, Right);
4311       buildTree_rec(Left, Depth + 1, {TE, 0});
4312       buildTree_rec(Right, Depth + 1, {TE, 1});
4313       return;
4314     }
4315     case Instruction::Select:
4316     case Instruction::FNeg:
4317     case Instruction::Add:
4318     case Instruction::FAdd:
4319     case Instruction::Sub:
4320     case Instruction::FSub:
4321     case Instruction::Mul:
4322     case Instruction::FMul:
4323     case Instruction::UDiv:
4324     case Instruction::SDiv:
4325     case Instruction::FDiv:
4326     case Instruction::URem:
4327     case Instruction::SRem:
4328     case Instruction::FRem:
4329     case Instruction::Shl:
4330     case Instruction::LShr:
4331     case Instruction::AShr:
4332     case Instruction::And:
4333     case Instruction::Or:
4334     case Instruction::Xor: {
4335       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4336                                    ReuseShuffleIndicies);
4337       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4338 
4339       // Sort operands of the instructions so that each side is more likely to
4340       // have the same opcode.
4341       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4342         ValueList Left, Right;
4343         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4344         TE->setOperand(0, Left);
4345         TE->setOperand(1, Right);
4346         buildTree_rec(Left, Depth + 1, {TE, 0});
4347         buildTree_rec(Right, Depth + 1, {TE, 1});
4348         return;
4349       }
4350 
4351       TE->setOperandsInOrder();
4352       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4353         ValueList Operands;
4354         // Prepare the operand vector.
4355         for (Value *V : VL)
4356           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4357 
4358         buildTree_rec(Operands, Depth + 1, {TE, i});
4359       }
4360       return;
4361     }
4362     case Instruction::GetElementPtr: {
4363       // We don't combine GEPs with complicated (nested) indexing.
4364       for (Value *V : VL) {
4365         if (cast<Instruction>(V)->getNumOperands() != 2) {
4366           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4367           BS.cancelScheduling(VL, VL0);
4368           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4369                        ReuseShuffleIndicies);
4370           return;
4371         }
4372       }
4373 
4374       // We can't combine several GEPs into one vector if they operate on
4375       // different types.
4376       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4377       for (Value *V : VL) {
4378         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4379         if (Ty0 != CurTy) {
4380           LLVM_DEBUG(dbgs()
4381                      << "SLP: not-vectorizable GEP (different types).\n");
4382           BS.cancelScheduling(VL, VL0);
4383           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4384                        ReuseShuffleIndicies);
4385           return;
4386         }
4387       }
4388 
4389       // We don't combine GEPs with non-constant indexes.
4390       Type *Ty1 = VL0->getOperand(1)->getType();
4391       for (Value *V : VL) {
4392         auto Op = cast<Instruction>(V)->getOperand(1);
4393         if (!isa<ConstantInt>(Op) ||
4394             (Op->getType() != Ty1 &&
4395              Op->getType()->getScalarSizeInBits() >
4396                  DL->getIndexSizeInBits(
4397                      V->getType()->getPointerAddressSpace()))) {
4398           LLVM_DEBUG(dbgs()
4399                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4400           BS.cancelScheduling(VL, VL0);
4401           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4402                        ReuseShuffleIndicies);
4403           return;
4404         }
4405       }
4406 
4407       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4408                                    ReuseShuffleIndicies);
4409       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4410       SmallVector<ValueList, 2> Operands(2);
4411       // Prepare the operand vector for pointer operands.
4412       for (Value *V : VL)
4413         Operands.front().push_back(
4414             cast<GetElementPtrInst>(V)->getPointerOperand());
4415       TE->setOperand(0, Operands.front());
4416       // Need to cast all indices to the same type before vectorization to
4417       // avoid crash.
4418       // Required to be able to find correct matches between different gather
4419       // nodes and reuse the vectorized values rather than trying to gather them
4420       // again.
4421       int IndexIdx = 1;
4422       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4423       Type *Ty = all_of(VL,
4424                         [VL0Ty, IndexIdx](Value *V) {
4425                           return VL0Ty == cast<GetElementPtrInst>(V)
4426                                               ->getOperand(IndexIdx)
4427                                               ->getType();
4428                         })
4429                      ? VL0Ty
4430                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4431                                             ->getPointerOperandType()
4432                                             ->getScalarType());
4433       // Prepare the operand vector.
4434       for (Value *V : VL) {
4435         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4436         auto *CI = cast<ConstantInt>(Op);
4437         Operands.back().push_back(ConstantExpr::getIntegerCast(
4438             CI, Ty, CI->getValue().isSignBitSet()));
4439       }
4440       TE->setOperand(IndexIdx, Operands.back());
4441 
4442       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4443         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4444       return;
4445     }
4446     case Instruction::Store: {
4447       // Check if the stores are consecutive or if we need to swizzle them.
4448       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4449       // Avoid types that are padded when being allocated as scalars, while
4450       // being packed together in a vector (such as i1).
4451       if (DL->getTypeSizeInBits(ScalarTy) !=
4452           DL->getTypeAllocSizeInBits(ScalarTy)) {
4453         BS.cancelScheduling(VL, VL0);
4454         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4455                      ReuseShuffleIndicies);
4456         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4457         return;
4458       }
4459       // Make sure all stores in the bundle are simple - we can't vectorize
4460       // atomic or volatile stores.
4461       SmallVector<Value *, 4> PointerOps(VL.size());
4462       ValueList Operands(VL.size());
4463       auto POIter = PointerOps.begin();
4464       auto OIter = Operands.begin();
4465       for (Value *V : VL) {
4466         auto *SI = cast<StoreInst>(V);
4467         if (!SI->isSimple()) {
4468           BS.cancelScheduling(VL, VL0);
4469           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4470                        ReuseShuffleIndicies);
4471           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4472           return;
4473         }
4474         *POIter = SI->getPointerOperand();
4475         *OIter = SI->getValueOperand();
4476         ++POIter;
4477         ++OIter;
4478       }
4479 
4480       OrdersType CurrentOrder;
4481       // Check the order of pointer operands.
4482       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4483         Value *Ptr0;
4484         Value *PtrN;
4485         if (CurrentOrder.empty()) {
4486           Ptr0 = PointerOps.front();
4487           PtrN = PointerOps.back();
4488         } else {
4489           Ptr0 = PointerOps[CurrentOrder.front()];
4490           PtrN = PointerOps[CurrentOrder.back()];
4491         }
4492         Optional<int> Dist =
4493             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4494         // Check that the sorted pointer operands are consecutive.
4495         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4496           if (CurrentOrder.empty()) {
4497             // Original stores are consecutive and does not require reordering.
4498             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4499                                          UserTreeIdx, ReuseShuffleIndicies);
4500             TE->setOperandsInOrder();
4501             buildTree_rec(Operands, Depth + 1, {TE, 0});
4502             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4503           } else {
4504             fixupOrderingIndices(CurrentOrder);
4505             TreeEntry *TE =
4506                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4507                              ReuseShuffleIndicies, CurrentOrder);
4508             TE->setOperandsInOrder();
4509             buildTree_rec(Operands, Depth + 1, {TE, 0});
4510             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4511           }
4512           return;
4513         }
4514       }
4515 
4516       BS.cancelScheduling(VL, VL0);
4517       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4518                    ReuseShuffleIndicies);
4519       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4520       return;
4521     }
4522     case Instruction::Call: {
4523       // Check if the calls are all to the same vectorizable intrinsic or
4524       // library function.
4525       CallInst *CI = cast<CallInst>(VL0);
4526       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4527 
4528       VFShape Shape = VFShape::get(
4529           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4530           false /*HasGlobalPred*/);
4531       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4532 
4533       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4534         BS.cancelScheduling(VL, VL0);
4535         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4536                      ReuseShuffleIndicies);
4537         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4538         return;
4539       }
4540       Function *F = CI->getCalledFunction();
4541       unsigned NumArgs = CI->arg_size();
4542       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4543       for (unsigned j = 0; j != NumArgs; ++j)
4544         if (hasVectorInstrinsicScalarOpd(ID, j))
4545           ScalarArgs[j] = CI->getArgOperand(j);
4546       for (Value *V : VL) {
4547         CallInst *CI2 = dyn_cast<CallInst>(V);
4548         if (!CI2 || CI2->getCalledFunction() != F ||
4549             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4550             (VecFunc &&
4551              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4552             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4553           BS.cancelScheduling(VL, VL0);
4554           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4555                        ReuseShuffleIndicies);
4556           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4557                             << "\n");
4558           return;
4559         }
4560         // Some intrinsics have scalar arguments and should be same in order for
4561         // them to be vectorized.
4562         for (unsigned j = 0; j != NumArgs; ++j) {
4563           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4564             Value *A1J = CI2->getArgOperand(j);
4565             if (ScalarArgs[j] != A1J) {
4566               BS.cancelScheduling(VL, VL0);
4567               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4568                            ReuseShuffleIndicies);
4569               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4570                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4571                                 << "\n");
4572               return;
4573             }
4574           }
4575         }
4576         // Verify that the bundle operands are identical between the two calls.
4577         if (CI->hasOperandBundles() &&
4578             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4579                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4580                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4581           BS.cancelScheduling(VL, VL0);
4582           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4583                        ReuseShuffleIndicies);
4584           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4585                             << *CI << "!=" << *V << '\n');
4586           return;
4587         }
4588       }
4589 
4590       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4591                                    ReuseShuffleIndicies);
4592       TE->setOperandsInOrder();
4593       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4594         // For scalar operands no need to to create an entry since no need to
4595         // vectorize it.
4596         if (hasVectorInstrinsicScalarOpd(ID, i))
4597           continue;
4598         ValueList Operands;
4599         // Prepare the operand vector.
4600         for (Value *V : VL) {
4601           auto *CI2 = cast<CallInst>(V);
4602           Operands.push_back(CI2->getArgOperand(i));
4603         }
4604         buildTree_rec(Operands, Depth + 1, {TE, i});
4605       }
4606       return;
4607     }
4608     case Instruction::ShuffleVector: {
4609       // If this is not an alternate sequence of opcode like add-sub
4610       // then do not vectorize this instruction.
4611       if (!S.isAltShuffle()) {
4612         BS.cancelScheduling(VL, VL0);
4613         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4614                      ReuseShuffleIndicies);
4615         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4616         return;
4617       }
4618       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4619                                    ReuseShuffleIndicies);
4620       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4621 
4622       // Reorder operands if reordering would enable vectorization.
4623       auto *CI = dyn_cast<CmpInst>(VL0);
4624       if (isa<BinaryOperator>(VL0) || CI) {
4625         ValueList Left, Right;
4626         if (!CI || all_of(VL, [](Value *V) {
4627               return cast<CmpInst>(V)->isCommutative();
4628             })) {
4629           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4630         } else {
4631           CmpInst::Predicate P0 = CI->getPredicate();
4632           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4633           assert(P0 != AltP0 &&
4634                  "Expected different main/alternate predicates.");
4635           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4636           Value *BaseOp0 = VL0->getOperand(0);
4637           Value *BaseOp1 = VL0->getOperand(1);
4638           // Collect operands - commute if it uses the swapped predicate or
4639           // alternate operation.
4640           for (Value *V : VL) {
4641             auto *Cmp = cast<CmpInst>(V);
4642             Value *LHS = Cmp->getOperand(0);
4643             Value *RHS = Cmp->getOperand(1);
4644             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4645             if (P0 == AltP0Swapped) {
4646               if (CI != Cmp && S.AltOp != Cmp &&
4647                   ((P0 == CurrentPred &&
4648                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4649                    (AltP0 == CurrentPred &&
4650                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4651                 std::swap(LHS, RHS);
4652             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4653               std::swap(LHS, RHS);
4654             }
4655             Left.push_back(LHS);
4656             Right.push_back(RHS);
4657           }
4658         }
4659         TE->setOperand(0, Left);
4660         TE->setOperand(1, Right);
4661         buildTree_rec(Left, Depth + 1, {TE, 0});
4662         buildTree_rec(Right, Depth + 1, {TE, 1});
4663         return;
4664       }
4665 
4666       TE->setOperandsInOrder();
4667       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4668         ValueList Operands;
4669         // Prepare the operand vector.
4670         for (Value *V : VL)
4671           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4672 
4673         buildTree_rec(Operands, Depth + 1, {TE, i});
4674       }
4675       return;
4676     }
4677     default:
4678       BS.cancelScheduling(VL, VL0);
4679       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4680                    ReuseShuffleIndicies);
4681       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4682       return;
4683   }
4684 }
4685 
4686 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4687   unsigned N = 1;
4688   Type *EltTy = T;
4689 
4690   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4691          isa<VectorType>(EltTy)) {
4692     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4693       // Check that struct is homogeneous.
4694       for (const auto *Ty : ST->elements())
4695         if (Ty != *ST->element_begin())
4696           return 0;
4697       N *= ST->getNumElements();
4698       EltTy = *ST->element_begin();
4699     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4700       N *= AT->getNumElements();
4701       EltTy = AT->getElementType();
4702     } else {
4703       auto *VT = cast<FixedVectorType>(EltTy);
4704       N *= VT->getNumElements();
4705       EltTy = VT->getElementType();
4706     }
4707   }
4708 
4709   if (!isValidElementType(EltTy))
4710     return 0;
4711   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4712   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4713     return 0;
4714   return N;
4715 }
4716 
4717 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4718                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4719   const auto *It = find_if(VL, [](Value *V) {
4720     return isa<ExtractElementInst, ExtractValueInst>(V);
4721   });
4722   assert(It != VL.end() && "Expected at least one extract instruction.");
4723   auto *E0 = cast<Instruction>(*It);
4724   assert(all_of(VL,
4725                 [](Value *V) {
4726                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4727                       V);
4728                 }) &&
4729          "Invalid opcode");
4730   // Check if all of the extracts come from the same vector and from the
4731   // correct offset.
4732   Value *Vec = E0->getOperand(0);
4733 
4734   CurrentOrder.clear();
4735 
4736   // We have to extract from a vector/aggregate with the same number of elements.
4737   unsigned NElts;
4738   if (E0->getOpcode() == Instruction::ExtractValue) {
4739     const DataLayout &DL = E0->getModule()->getDataLayout();
4740     NElts = canMapToVector(Vec->getType(), DL);
4741     if (!NElts)
4742       return false;
4743     // Check if load can be rewritten as load of vector.
4744     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4745     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4746       return false;
4747   } else {
4748     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4749   }
4750 
4751   if (NElts != VL.size())
4752     return false;
4753 
4754   // Check that all of the indices extract from the correct offset.
4755   bool ShouldKeepOrder = true;
4756   unsigned E = VL.size();
4757   // Assign to all items the initial value E + 1 so we can check if the extract
4758   // instruction index was used already.
4759   // Also, later we can check that all the indices are used and we have a
4760   // consecutive access in the extract instructions, by checking that no
4761   // element of CurrentOrder still has value E + 1.
4762   CurrentOrder.assign(E, E);
4763   unsigned I = 0;
4764   for (; I < E; ++I) {
4765     auto *Inst = dyn_cast<Instruction>(VL[I]);
4766     if (!Inst)
4767       continue;
4768     if (Inst->getOperand(0) != Vec)
4769       break;
4770     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4771       if (isa<UndefValue>(EE->getIndexOperand()))
4772         continue;
4773     Optional<unsigned> Idx = getExtractIndex(Inst);
4774     if (!Idx)
4775       break;
4776     const unsigned ExtIdx = *Idx;
4777     if (ExtIdx != I) {
4778       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4779         break;
4780       ShouldKeepOrder = false;
4781       CurrentOrder[ExtIdx] = I;
4782     } else {
4783       if (CurrentOrder[I] != E)
4784         break;
4785       CurrentOrder[I] = I;
4786     }
4787   }
4788   if (I < E) {
4789     CurrentOrder.clear();
4790     return false;
4791   }
4792   if (ShouldKeepOrder)
4793     CurrentOrder.clear();
4794 
4795   return ShouldKeepOrder;
4796 }
4797 
4798 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4799                                     ArrayRef<Value *> VectorizedVals) const {
4800   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4801          all_of(I->users(), [this](User *U) {
4802            return ScalarToTreeEntry.count(U) > 0 ||
4803                   isVectorLikeInstWithConstOps(U) ||
4804                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4805          });
4806 }
4807 
4808 static std::pair<InstructionCost, InstructionCost>
4809 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4810                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4811   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4812 
4813   // Calculate the cost of the scalar and vector calls.
4814   SmallVector<Type *, 4> VecTys;
4815   for (Use &Arg : CI->args())
4816     VecTys.push_back(
4817         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4818   FastMathFlags FMF;
4819   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4820     FMF = FPCI->getFastMathFlags();
4821   SmallVector<const Value *> Arguments(CI->args());
4822   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4823                                     dyn_cast<IntrinsicInst>(CI));
4824   auto IntrinsicCost =
4825     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4826 
4827   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4828                                      VecTy->getNumElements())),
4829                             false /*HasGlobalPred*/);
4830   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4831   auto LibCost = IntrinsicCost;
4832   if (!CI->isNoBuiltin() && VecFunc) {
4833     // Calculate the cost of the vector library call.
4834     // If the corresponding vector call is cheaper, return its cost.
4835     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4836                                     TTI::TCK_RecipThroughput);
4837   }
4838   return {IntrinsicCost, LibCost};
4839 }
4840 
4841 /// Compute the cost of creating a vector of type \p VecTy containing the
4842 /// extracted values from \p VL.
4843 static InstructionCost
4844 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4845                    TargetTransformInfo::ShuffleKind ShuffleKind,
4846                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4847   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4848 
4849   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4850       VecTy->getNumElements() < NumOfParts)
4851     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4852 
4853   bool AllConsecutive = true;
4854   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4855   unsigned Idx = -1;
4856   InstructionCost Cost = 0;
4857 
4858   // Process extracts in blocks of EltsPerVector to check if the source vector
4859   // operand can be re-used directly. If not, add the cost of creating a shuffle
4860   // to extract the values into a vector register.
4861   for (auto *V : VL) {
4862     ++Idx;
4863 
4864     // Need to exclude undefs from analysis.
4865     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4866       continue;
4867 
4868     // Reached the start of a new vector registers.
4869     if (Idx % EltsPerVector == 0) {
4870       AllConsecutive = true;
4871       continue;
4872     }
4873 
4874     // Check all extracts for a vector register on the target directly
4875     // extract values in order.
4876     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4877     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4878       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4879       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4880                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4881     }
4882 
4883     if (AllConsecutive)
4884       continue;
4885 
4886     // Skip all indices, except for the last index per vector block.
4887     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4888       continue;
4889 
4890     // If we have a series of extracts which are not consecutive and hence
4891     // cannot re-use the source vector register directly, compute the shuffle
4892     // cost to extract the a vector with EltsPerVector elements.
4893     Cost += TTI.getShuffleCost(
4894         TargetTransformInfo::SK_PermuteSingleSrc,
4895         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4896   }
4897   return Cost;
4898 }
4899 
4900 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4901 /// operations operands.
4902 static void
4903 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4904                       ArrayRef<int> ReusesIndices,
4905                       const function_ref<bool(Instruction *)> IsAltOp,
4906                       SmallVectorImpl<int> &Mask,
4907                       SmallVectorImpl<Value *> *OpScalars = nullptr,
4908                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
4909   unsigned Sz = VL.size();
4910   Mask.assign(Sz, UndefMaskElem);
4911   SmallVector<int> OrderMask;
4912   if (!ReorderIndices.empty())
4913     inversePermutation(ReorderIndices, OrderMask);
4914   for (unsigned I = 0; I < Sz; ++I) {
4915     unsigned Idx = I;
4916     if (!ReorderIndices.empty())
4917       Idx = OrderMask[I];
4918     auto *OpInst = cast<Instruction>(VL[Idx]);
4919     if (IsAltOp(OpInst)) {
4920       Mask[I] = Sz + Idx;
4921       if (AltScalars)
4922         AltScalars->push_back(OpInst);
4923     } else {
4924       Mask[I] = Idx;
4925       if (OpScalars)
4926         OpScalars->push_back(OpInst);
4927     }
4928   }
4929   if (!ReusesIndices.empty()) {
4930     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4931     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4932       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4933     });
4934     Mask.swap(NewMask);
4935   }
4936 }
4937 
4938 /// Checks if the specified instruction \p I is an alternate operation for the
4939 /// given \p MainOp and \p AltOp instructions.
4940 static bool isAlternateInstruction(const Instruction *I,
4941                                    const Instruction *MainOp,
4942                                    const Instruction *AltOp) {
4943   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
4944     auto *AltCI0 = cast<CmpInst>(AltOp);
4945     auto *CI = cast<CmpInst>(I);
4946     CmpInst::Predicate P0 = CI0->getPredicate();
4947     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
4948     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
4949     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4950     CmpInst::Predicate CurrentPred = CI->getPredicate();
4951     if (P0 == AltP0Swapped)
4952       return I == AltCI0 ||
4953              (I != MainOp &&
4954               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
4955                                    CI->getOperand(0), CI->getOperand(1)));
4956     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
4957   }
4958   return I->getOpcode() == AltOp->getOpcode();
4959 }
4960 
4961 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4962                                       ArrayRef<Value *> VectorizedVals) {
4963   ArrayRef<Value*> VL = E->Scalars;
4964 
4965   Type *ScalarTy = VL[0]->getType();
4966   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4967     ScalarTy = SI->getValueOperand()->getType();
4968   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4969     ScalarTy = CI->getOperand(0)->getType();
4970   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4971     ScalarTy = IE->getOperand(1)->getType();
4972   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4973   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4974 
4975   // If we have computed a smaller type for the expression, update VecTy so
4976   // that the costs will be accurate.
4977   if (MinBWs.count(VL[0]))
4978     VecTy = FixedVectorType::get(
4979         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4980   unsigned EntryVF = E->getVectorFactor();
4981   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4982 
4983   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4984   // FIXME: it tries to fix a problem with MSVC buildbots.
4985   TargetTransformInfo &TTIRef = *TTI;
4986   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4987                                VectorizedVals, E](InstructionCost &Cost) {
4988     DenseMap<Value *, int> ExtractVectorsTys;
4989     SmallPtrSet<Value *, 4> CheckedExtracts;
4990     for (auto *V : VL) {
4991       if (isa<UndefValue>(V))
4992         continue;
4993       // If all users of instruction are going to be vectorized and this
4994       // instruction itself is not going to be vectorized, consider this
4995       // instruction as dead and remove its cost from the final cost of the
4996       // vectorized tree.
4997       // Also, avoid adjusting the cost for extractelements with multiple uses
4998       // in different graph entries.
4999       const TreeEntry *VE = getTreeEntry(V);
5000       if (!CheckedExtracts.insert(V).second ||
5001           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5002           (VE && VE != E))
5003         continue;
5004       auto *EE = cast<ExtractElementInst>(V);
5005       Optional<unsigned> EEIdx = getExtractIndex(EE);
5006       if (!EEIdx)
5007         continue;
5008       unsigned Idx = *EEIdx;
5009       if (TTIRef.getNumberOfParts(VecTy) !=
5010           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5011         auto It =
5012             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5013         It->getSecond() = std::min<int>(It->second, Idx);
5014       }
5015       // Take credit for instruction that will become dead.
5016       if (EE->hasOneUse()) {
5017         Instruction *Ext = EE->user_back();
5018         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5019             all_of(Ext->users(),
5020                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5021           // Use getExtractWithExtendCost() to calculate the cost of
5022           // extractelement/ext pair.
5023           Cost -=
5024               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5025                                               EE->getVectorOperandType(), Idx);
5026           // Add back the cost of s|zext which is subtracted separately.
5027           Cost += TTIRef.getCastInstrCost(
5028               Ext->getOpcode(), Ext->getType(), EE->getType(),
5029               TTI::getCastContextHint(Ext), CostKind, Ext);
5030           continue;
5031         }
5032       }
5033       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5034                                         EE->getVectorOperandType(), Idx);
5035     }
5036     // Add a cost for subvector extracts/inserts if required.
5037     for (const auto &Data : ExtractVectorsTys) {
5038       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5039       unsigned NumElts = VecTy->getNumElements();
5040       if (Data.second % NumElts == 0)
5041         continue;
5042       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5043         unsigned Idx = (Data.second / NumElts) * NumElts;
5044         unsigned EENumElts = EEVTy->getNumElements();
5045         if (Idx + NumElts <= EENumElts) {
5046           Cost +=
5047               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5048                                     EEVTy, None, Idx, VecTy);
5049         } else {
5050           // Need to round up the subvector type vectorization factor to avoid a
5051           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5052           // <= EENumElts.
5053           auto *SubVT =
5054               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5055           Cost +=
5056               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5057                                     EEVTy, None, Idx, SubVT);
5058         }
5059       } else {
5060         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5061                                       VecTy, None, 0, EEVTy);
5062       }
5063     }
5064   };
5065   if (E->State == TreeEntry::NeedToGather) {
5066     if (allConstant(VL))
5067       return 0;
5068     if (isa<InsertElementInst>(VL[0]))
5069       return InstructionCost::getInvalid();
5070     SmallVector<int> Mask;
5071     SmallVector<const TreeEntry *> Entries;
5072     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5073         isGatherShuffledEntry(E, Mask, Entries);
5074     if (Shuffle.hasValue()) {
5075       InstructionCost GatherCost = 0;
5076       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5077         // Perfect match in the graph, will reuse the previously vectorized
5078         // node. Cost is 0.
5079         LLVM_DEBUG(
5080             dbgs()
5081             << "SLP: perfect diamond match for gather bundle that starts with "
5082             << *VL.front() << ".\n");
5083         if (NeedToShuffleReuses)
5084           GatherCost =
5085               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5086                                   FinalVecTy, E->ReuseShuffleIndices);
5087       } else {
5088         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5089                           << " entries for bundle that starts with "
5090                           << *VL.front() << ".\n");
5091         // Detected that instead of gather we can emit a shuffle of single/two
5092         // previously vectorized nodes. Add the cost of the permutation rather
5093         // than gather.
5094         ::addMask(Mask, E->ReuseShuffleIndices);
5095         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5096       }
5097       return GatherCost;
5098     }
5099     if ((E->getOpcode() == Instruction::ExtractElement ||
5100          all_of(E->Scalars,
5101                 [](Value *V) {
5102                   return isa<ExtractElementInst, UndefValue>(V);
5103                 })) &&
5104         allSameType(VL)) {
5105       // Check that gather of extractelements can be represented as just a
5106       // shuffle of a single/two vectors the scalars are extracted from.
5107       SmallVector<int> Mask;
5108       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5109           isFixedVectorShuffle(VL, Mask);
5110       if (ShuffleKind.hasValue()) {
5111         // Found the bunch of extractelement instructions that must be gathered
5112         // into a vector and can be represented as a permutation elements in a
5113         // single input vector or of 2 input vectors.
5114         InstructionCost Cost =
5115             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5116         AdjustExtractsCost(Cost);
5117         if (NeedToShuffleReuses)
5118           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5119                                       FinalVecTy, E->ReuseShuffleIndices);
5120         return Cost;
5121       }
5122     }
5123     if (isSplat(VL)) {
5124       // Found the broadcasting of the single scalar, calculate the cost as the
5125       // broadcast.
5126       assert(VecTy == FinalVecTy &&
5127              "No reused scalars expected for broadcast.");
5128       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5129     }
5130     InstructionCost ReuseShuffleCost = 0;
5131     if (NeedToShuffleReuses)
5132       ReuseShuffleCost = TTI->getShuffleCost(
5133           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5134     // Improve gather cost for gather of loads, if we can group some of the
5135     // loads into vector loads.
5136     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5137         !E->isAltShuffle()) {
5138       BoUpSLP::ValueSet VectorizedLoads;
5139       unsigned StartIdx = 0;
5140       unsigned VF = VL.size() / 2;
5141       unsigned VectorizedCnt = 0;
5142       unsigned ScatterVectorizeCnt = 0;
5143       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5144       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5145         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5146              Cnt += VF) {
5147           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5148           if (!VectorizedLoads.count(Slice.front()) &&
5149               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5150             SmallVector<Value *> PointerOps;
5151             OrdersType CurrentOrder;
5152             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5153                                               *SE, CurrentOrder, PointerOps);
5154             switch (LS) {
5155             case LoadsState::Vectorize:
5156             case LoadsState::ScatterVectorize:
5157               // Mark the vectorized loads so that we don't vectorize them
5158               // again.
5159               if (LS == LoadsState::Vectorize)
5160                 ++VectorizedCnt;
5161               else
5162                 ++ScatterVectorizeCnt;
5163               VectorizedLoads.insert(Slice.begin(), Slice.end());
5164               // If we vectorized initial block, no need to try to vectorize it
5165               // again.
5166               if (Cnt == StartIdx)
5167                 StartIdx += VF;
5168               break;
5169             case LoadsState::Gather:
5170               break;
5171             }
5172           }
5173         }
5174         // Check if the whole array was vectorized already - exit.
5175         if (StartIdx >= VL.size())
5176           break;
5177         // Found vectorizable parts - exit.
5178         if (!VectorizedLoads.empty())
5179           break;
5180       }
5181       if (!VectorizedLoads.empty()) {
5182         InstructionCost GatherCost = 0;
5183         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5184         bool NeedInsertSubvectorAnalysis =
5185             !NumParts || (VL.size() / VF) > NumParts;
5186         // Get the cost for gathered loads.
5187         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5188           if (VectorizedLoads.contains(VL[I]))
5189             continue;
5190           GatherCost += getGatherCost(VL.slice(I, VF));
5191         }
5192         // The cost for vectorized loads.
5193         InstructionCost ScalarsCost = 0;
5194         for (Value *V : VectorizedLoads) {
5195           auto *LI = cast<LoadInst>(V);
5196           ScalarsCost += TTI->getMemoryOpCost(
5197               Instruction::Load, LI->getType(), LI->getAlign(),
5198               LI->getPointerAddressSpace(), CostKind, LI);
5199         }
5200         auto *LI = cast<LoadInst>(E->getMainOp());
5201         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5202         Align Alignment = LI->getAlign();
5203         GatherCost +=
5204             VectorizedCnt *
5205             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5206                                  LI->getPointerAddressSpace(), CostKind, LI);
5207         GatherCost += ScatterVectorizeCnt *
5208                       TTI->getGatherScatterOpCost(
5209                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5210                           /*VariableMask=*/false, Alignment, CostKind, LI);
5211         if (NeedInsertSubvectorAnalysis) {
5212           // Add the cost for the subvectors insert.
5213           for (int I = VF, E = VL.size(); I < E; I += VF)
5214             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5215                                               None, I, LoadTy);
5216         }
5217         return ReuseShuffleCost + GatherCost - ScalarsCost;
5218       }
5219     }
5220     return ReuseShuffleCost + getGatherCost(VL);
5221   }
5222   InstructionCost CommonCost = 0;
5223   SmallVector<int> Mask;
5224   if (!E->ReorderIndices.empty()) {
5225     SmallVector<int> NewMask;
5226     if (E->getOpcode() == Instruction::Store) {
5227       // For stores the order is actually a mask.
5228       NewMask.resize(E->ReorderIndices.size());
5229       copy(E->ReorderIndices, NewMask.begin());
5230     } else {
5231       inversePermutation(E->ReorderIndices, NewMask);
5232     }
5233     ::addMask(Mask, NewMask);
5234   }
5235   if (NeedToShuffleReuses)
5236     ::addMask(Mask, E->ReuseShuffleIndices);
5237   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5238     CommonCost =
5239         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5240   assert((E->State == TreeEntry::Vectorize ||
5241           E->State == TreeEntry::ScatterVectorize) &&
5242          "Unhandled state");
5243   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5244   Instruction *VL0 = E->getMainOp();
5245   unsigned ShuffleOrOp =
5246       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5247   switch (ShuffleOrOp) {
5248     case Instruction::PHI:
5249       return 0;
5250 
5251     case Instruction::ExtractValue:
5252     case Instruction::ExtractElement: {
5253       // The common cost of removal ExtractElement/ExtractValue instructions +
5254       // the cost of shuffles, if required to resuffle the original vector.
5255       if (NeedToShuffleReuses) {
5256         unsigned Idx = 0;
5257         for (unsigned I : E->ReuseShuffleIndices) {
5258           if (ShuffleOrOp == Instruction::ExtractElement) {
5259             auto *EE = cast<ExtractElementInst>(VL[I]);
5260             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5261                                                   EE->getVectorOperandType(),
5262                                                   *getExtractIndex(EE));
5263           } else {
5264             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5265                                                   VecTy, Idx);
5266             ++Idx;
5267           }
5268         }
5269         Idx = EntryVF;
5270         for (Value *V : VL) {
5271           if (ShuffleOrOp == Instruction::ExtractElement) {
5272             auto *EE = cast<ExtractElementInst>(V);
5273             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5274                                                   EE->getVectorOperandType(),
5275                                                   *getExtractIndex(EE));
5276           } else {
5277             --Idx;
5278             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5279                                                   VecTy, Idx);
5280           }
5281         }
5282       }
5283       if (ShuffleOrOp == Instruction::ExtractValue) {
5284         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5285           auto *EI = cast<Instruction>(VL[I]);
5286           // Take credit for instruction that will become dead.
5287           if (EI->hasOneUse()) {
5288             Instruction *Ext = EI->user_back();
5289             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5290                 all_of(Ext->users(),
5291                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5292               // Use getExtractWithExtendCost() to calculate the cost of
5293               // extractelement/ext pair.
5294               CommonCost -= TTI->getExtractWithExtendCost(
5295                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5296               // Add back the cost of s|zext which is subtracted separately.
5297               CommonCost += TTI->getCastInstrCost(
5298                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5299                   TTI::getCastContextHint(Ext), CostKind, Ext);
5300               continue;
5301             }
5302           }
5303           CommonCost -=
5304               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5305         }
5306       } else {
5307         AdjustExtractsCost(CommonCost);
5308       }
5309       return CommonCost;
5310     }
5311     case Instruction::InsertElement: {
5312       assert(E->ReuseShuffleIndices.empty() &&
5313              "Unique insertelements only are expected.");
5314       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5315 
5316       unsigned const NumElts = SrcVecTy->getNumElements();
5317       unsigned const NumScalars = VL.size();
5318       APInt DemandedElts = APInt::getZero(NumElts);
5319       // TODO: Add support for Instruction::InsertValue.
5320       SmallVector<int> Mask;
5321       if (!E->ReorderIndices.empty()) {
5322         inversePermutation(E->ReorderIndices, Mask);
5323         Mask.append(NumElts - NumScalars, UndefMaskElem);
5324       } else {
5325         Mask.assign(NumElts, UndefMaskElem);
5326         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5327       }
5328       unsigned Offset = *getInsertIndex(VL0);
5329       bool IsIdentity = true;
5330       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5331       Mask.swap(PrevMask);
5332       for (unsigned I = 0; I < NumScalars; ++I) {
5333         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5334         DemandedElts.setBit(InsertIdx);
5335         IsIdentity &= InsertIdx - Offset == I;
5336         Mask[InsertIdx - Offset] = I;
5337       }
5338       assert(Offset < NumElts && "Failed to find vector index offset");
5339 
5340       InstructionCost Cost = 0;
5341       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5342                                             /*Insert*/ true, /*Extract*/ false);
5343 
5344       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5345         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5346         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5347         Cost += TTI->getShuffleCost(
5348             TargetTransformInfo::SK_PermuteSingleSrc,
5349             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5350       } else if (!IsIdentity) {
5351         auto *FirstInsert =
5352             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5353               return !is_contained(E->Scalars,
5354                                    cast<Instruction>(V)->getOperand(0));
5355             }));
5356         if (isUndefVector(FirstInsert->getOperand(0))) {
5357           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5358         } else {
5359           SmallVector<int> InsertMask(NumElts);
5360           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5361           for (unsigned I = 0; I < NumElts; I++) {
5362             if (Mask[I] != UndefMaskElem)
5363               InsertMask[Offset + I] = NumElts + I;
5364           }
5365           Cost +=
5366               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5367         }
5368       }
5369 
5370       return Cost;
5371     }
5372     case Instruction::ZExt:
5373     case Instruction::SExt:
5374     case Instruction::FPToUI:
5375     case Instruction::FPToSI:
5376     case Instruction::FPExt:
5377     case Instruction::PtrToInt:
5378     case Instruction::IntToPtr:
5379     case Instruction::SIToFP:
5380     case Instruction::UIToFP:
5381     case Instruction::Trunc:
5382     case Instruction::FPTrunc:
5383     case Instruction::BitCast: {
5384       Type *SrcTy = VL0->getOperand(0)->getType();
5385       InstructionCost ScalarEltCost =
5386           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5387                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5388       if (NeedToShuffleReuses) {
5389         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5390       }
5391 
5392       // Calculate the cost of this instruction.
5393       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5394 
5395       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5396       InstructionCost VecCost = 0;
5397       // Check if the values are candidates to demote.
5398       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5399         VecCost = CommonCost + TTI->getCastInstrCost(
5400                                    E->getOpcode(), VecTy, SrcVecTy,
5401                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5402       }
5403       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5404       return VecCost - ScalarCost;
5405     }
5406     case Instruction::FCmp:
5407     case Instruction::ICmp:
5408     case Instruction::Select: {
5409       // Calculate the cost of this instruction.
5410       InstructionCost ScalarEltCost =
5411           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5412                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5413       if (NeedToShuffleReuses) {
5414         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5415       }
5416       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5417       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5418 
5419       // Check if all entries in VL are either compares or selects with compares
5420       // as condition that have the same predicates.
5421       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5422       bool First = true;
5423       for (auto *V : VL) {
5424         CmpInst::Predicate CurrentPred;
5425         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5426         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5427              !match(V, MatchCmp)) ||
5428             (!First && VecPred != CurrentPred)) {
5429           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5430           break;
5431         }
5432         First = false;
5433         VecPred = CurrentPred;
5434       }
5435 
5436       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5437           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5438       // Check if it is possible and profitable to use min/max for selects in
5439       // VL.
5440       //
5441       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5442       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5443         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5444                                           {VecTy, VecTy});
5445         InstructionCost IntrinsicCost =
5446             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5447         // If the selects are the only uses of the compares, they will be dead
5448         // and we can adjust the cost by removing their cost.
5449         if (IntrinsicAndUse.second)
5450           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5451                                                    MaskTy, VecPred, CostKind);
5452         VecCost = std::min(VecCost, IntrinsicCost);
5453       }
5454       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5455       return CommonCost + VecCost - ScalarCost;
5456     }
5457     case Instruction::FNeg:
5458     case Instruction::Add:
5459     case Instruction::FAdd:
5460     case Instruction::Sub:
5461     case Instruction::FSub:
5462     case Instruction::Mul:
5463     case Instruction::FMul:
5464     case Instruction::UDiv:
5465     case Instruction::SDiv:
5466     case Instruction::FDiv:
5467     case Instruction::URem:
5468     case Instruction::SRem:
5469     case Instruction::FRem:
5470     case Instruction::Shl:
5471     case Instruction::LShr:
5472     case Instruction::AShr:
5473     case Instruction::And:
5474     case Instruction::Or:
5475     case Instruction::Xor: {
5476       // Certain instructions can be cheaper to vectorize if they have a
5477       // constant second vector operand.
5478       TargetTransformInfo::OperandValueKind Op1VK =
5479           TargetTransformInfo::OK_AnyValue;
5480       TargetTransformInfo::OperandValueKind Op2VK =
5481           TargetTransformInfo::OK_UniformConstantValue;
5482       TargetTransformInfo::OperandValueProperties Op1VP =
5483           TargetTransformInfo::OP_None;
5484       TargetTransformInfo::OperandValueProperties Op2VP =
5485           TargetTransformInfo::OP_PowerOf2;
5486 
5487       // If all operands are exactly the same ConstantInt then set the
5488       // operand kind to OK_UniformConstantValue.
5489       // If instead not all operands are constants, then set the operand kind
5490       // to OK_AnyValue. If all operands are constants but not the same,
5491       // then set the operand kind to OK_NonUniformConstantValue.
5492       ConstantInt *CInt0 = nullptr;
5493       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5494         const Instruction *I = cast<Instruction>(VL[i]);
5495         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5496         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5497         if (!CInt) {
5498           Op2VK = TargetTransformInfo::OK_AnyValue;
5499           Op2VP = TargetTransformInfo::OP_None;
5500           break;
5501         }
5502         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5503             !CInt->getValue().isPowerOf2())
5504           Op2VP = TargetTransformInfo::OP_None;
5505         if (i == 0) {
5506           CInt0 = CInt;
5507           continue;
5508         }
5509         if (CInt0 != CInt)
5510           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5511       }
5512 
5513       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5514       InstructionCost ScalarEltCost =
5515           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5516                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5517       if (NeedToShuffleReuses) {
5518         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5519       }
5520       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5521       InstructionCost VecCost =
5522           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5523                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5524       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5525       return CommonCost + VecCost - ScalarCost;
5526     }
5527     case Instruction::GetElementPtr: {
5528       TargetTransformInfo::OperandValueKind Op1VK =
5529           TargetTransformInfo::OK_AnyValue;
5530       TargetTransformInfo::OperandValueKind Op2VK =
5531           TargetTransformInfo::OK_UniformConstantValue;
5532 
5533       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5534           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5535       if (NeedToShuffleReuses) {
5536         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5537       }
5538       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5539       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5540           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5541       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5542       return CommonCost + VecCost - ScalarCost;
5543     }
5544     case Instruction::Load: {
5545       // Cost of wide load - cost of scalar loads.
5546       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5547       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5548           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5549       if (NeedToShuffleReuses) {
5550         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5551       }
5552       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5553       InstructionCost VecLdCost;
5554       if (E->State == TreeEntry::Vectorize) {
5555         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5556                                          CostKind, VL0);
5557       } else {
5558         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5559         Align CommonAlignment = Alignment;
5560         for (Value *V : VL)
5561           CommonAlignment =
5562               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5563         VecLdCost = TTI->getGatherScatterOpCost(
5564             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5565             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5566       }
5567       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5568       return CommonCost + VecLdCost - ScalarLdCost;
5569     }
5570     case Instruction::Store: {
5571       // We know that we can merge the stores. Calculate the cost.
5572       bool IsReorder = !E->ReorderIndices.empty();
5573       auto *SI =
5574           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5575       Align Alignment = SI->getAlign();
5576       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5577           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5578       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5579       InstructionCost VecStCost = TTI->getMemoryOpCost(
5580           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5581       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5582       return CommonCost + VecStCost - ScalarStCost;
5583     }
5584     case Instruction::Call: {
5585       CallInst *CI = cast<CallInst>(VL0);
5586       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5587 
5588       // Calculate the cost of the scalar and vector calls.
5589       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5590       InstructionCost ScalarEltCost =
5591           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5592       if (NeedToShuffleReuses) {
5593         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5594       }
5595       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5596 
5597       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5598       InstructionCost VecCallCost =
5599           std::min(VecCallCosts.first, VecCallCosts.second);
5600 
5601       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5602                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5603                         << " for " << *CI << "\n");
5604 
5605       return CommonCost + VecCallCost - ScalarCallCost;
5606     }
5607     case Instruction::ShuffleVector: {
5608       assert(E->isAltShuffle() &&
5609              ((Instruction::isBinaryOp(E->getOpcode()) &&
5610                Instruction::isBinaryOp(E->getAltOpcode())) ||
5611               (Instruction::isCast(E->getOpcode()) &&
5612                Instruction::isCast(E->getAltOpcode())) ||
5613               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5614              "Invalid Shuffle Vector Operand");
5615       InstructionCost ScalarCost = 0;
5616       if (NeedToShuffleReuses) {
5617         for (unsigned Idx : E->ReuseShuffleIndices) {
5618           Instruction *I = cast<Instruction>(VL[Idx]);
5619           CommonCost -= TTI->getInstructionCost(I, CostKind);
5620         }
5621         for (Value *V : VL) {
5622           Instruction *I = cast<Instruction>(V);
5623           CommonCost += TTI->getInstructionCost(I, CostKind);
5624         }
5625       }
5626       for (Value *V : VL) {
5627         Instruction *I = cast<Instruction>(V);
5628         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5629         ScalarCost += TTI->getInstructionCost(I, CostKind);
5630       }
5631       // VecCost is equal to sum of the cost of creating 2 vectors
5632       // and the cost of creating shuffle.
5633       InstructionCost VecCost = 0;
5634       // Try to find the previous shuffle node with the same operands and same
5635       // main/alternate ops.
5636       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5637         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5638           if (TE.get() == E)
5639             break;
5640           if (TE->isAltShuffle() &&
5641               ((TE->getOpcode() == E->getOpcode() &&
5642                 TE->getAltOpcode() == E->getAltOpcode()) ||
5643                (TE->getOpcode() == E->getAltOpcode() &&
5644                 TE->getAltOpcode() == E->getOpcode())) &&
5645               TE->hasEqualOperands(*E))
5646             return true;
5647         }
5648         return false;
5649       };
5650       if (TryFindNodeWithEqualOperands()) {
5651         LLVM_DEBUG({
5652           dbgs() << "SLP: diamond match for alternate node found.\n";
5653           E->dump();
5654         });
5655         // No need to add new vector costs here since we're going to reuse
5656         // same main/alternate vector ops, just do different shuffling.
5657       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5658         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5659         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5660                                                CostKind);
5661       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5662         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5663                                           Builder.getInt1Ty(),
5664                                           CI0->getPredicate(), CostKind, VL0);
5665         VecCost += TTI->getCmpSelInstrCost(
5666             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5667             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5668             E->getAltOp());
5669       } else {
5670         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5671         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5672         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5673         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5674         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5675                                         TTI::CastContextHint::None, CostKind);
5676         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5677                                          TTI::CastContextHint::None, CostKind);
5678       }
5679 
5680       SmallVector<int> Mask;
5681       buildShuffleEntryMask(
5682           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5683           [E](Instruction *I) {
5684             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5685             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5686           },
5687           Mask);
5688       CommonCost =
5689           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5690       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5691       return CommonCost + VecCost - ScalarCost;
5692     }
5693     default:
5694       llvm_unreachable("Unknown instruction");
5695   }
5696 }
5697 
5698 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5699   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5700                     << VectorizableTree.size() << " is fully vectorizable .\n");
5701 
5702   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5703     SmallVector<int> Mask;
5704     return TE->State == TreeEntry::NeedToGather &&
5705            !any_of(TE->Scalars,
5706                    [this](Value *V) { return EphValues.contains(V); }) &&
5707            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5708             TE->Scalars.size() < Limit ||
5709             ((TE->getOpcode() == Instruction::ExtractElement ||
5710               all_of(TE->Scalars,
5711                      [](Value *V) {
5712                        return isa<ExtractElementInst, UndefValue>(V);
5713                      })) &&
5714              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5715             (TE->State == TreeEntry::NeedToGather &&
5716              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5717   };
5718 
5719   // We only handle trees of heights 1 and 2.
5720   if (VectorizableTree.size() == 1 &&
5721       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5722        (ForReduction &&
5723         AreVectorizableGathers(VectorizableTree[0].get(),
5724                                VectorizableTree[0]->Scalars.size()) &&
5725         VectorizableTree[0]->getVectorFactor() > 2)))
5726     return true;
5727 
5728   if (VectorizableTree.size() != 2)
5729     return false;
5730 
5731   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5732   // with the second gather nodes if they have less scalar operands rather than
5733   // the initial tree element (may be profitable to shuffle the second gather)
5734   // or they are extractelements, which form shuffle.
5735   SmallVector<int> Mask;
5736   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5737       AreVectorizableGathers(VectorizableTree[1].get(),
5738                              VectorizableTree[0]->Scalars.size()))
5739     return true;
5740 
5741   // Gathering cost would be too much for tiny trees.
5742   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5743       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5744        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5745     return false;
5746 
5747   return true;
5748 }
5749 
5750 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5751                                        TargetTransformInfo *TTI,
5752                                        bool MustMatchOrInst) {
5753   // Look past the root to find a source value. Arbitrarily follow the
5754   // path through operand 0 of any 'or'. Also, peek through optional
5755   // shift-left-by-multiple-of-8-bits.
5756   Value *ZextLoad = Root;
5757   const APInt *ShAmtC;
5758   bool FoundOr = false;
5759   while (!isa<ConstantExpr>(ZextLoad) &&
5760          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5761           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5762            ShAmtC->urem(8) == 0))) {
5763     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5764     ZextLoad = BinOp->getOperand(0);
5765     if (BinOp->getOpcode() == Instruction::Or)
5766       FoundOr = true;
5767   }
5768   // Check if the input is an extended load of the required or/shift expression.
5769   Value *Load;
5770   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5771       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5772     return false;
5773 
5774   // Require that the total load bit width is a legal integer type.
5775   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5776   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5777   Type *SrcTy = Load->getType();
5778   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5779   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5780     return false;
5781 
5782   // Everything matched - assume that we can fold the whole sequence using
5783   // load combining.
5784   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5785              << *(cast<Instruction>(Root)) << "\n");
5786 
5787   return true;
5788 }
5789 
5790 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5791   if (RdxKind != RecurKind::Or)
5792     return false;
5793 
5794   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5795   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5796   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5797                                     /* MatchOr */ false);
5798 }
5799 
5800 bool BoUpSLP::isLoadCombineCandidate() const {
5801   // Peek through a final sequence of stores and check if all operations are
5802   // likely to be load-combined.
5803   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5804   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5805     Value *X;
5806     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5807         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5808       return false;
5809   }
5810   return true;
5811 }
5812 
5813 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5814   // No need to vectorize inserts of gathered values.
5815   if (VectorizableTree.size() == 2 &&
5816       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5817       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5818     return true;
5819 
5820   // We can vectorize the tree if its size is greater than or equal to the
5821   // minimum size specified by the MinTreeSize command line option.
5822   if (VectorizableTree.size() >= MinTreeSize)
5823     return false;
5824 
5825   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5826   // can vectorize it if we can prove it fully vectorizable.
5827   if (isFullyVectorizableTinyTree(ForReduction))
5828     return false;
5829 
5830   assert(VectorizableTree.empty()
5831              ? ExternalUses.empty()
5832              : true && "We shouldn't have any external users");
5833 
5834   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5835   // vectorizable.
5836   return true;
5837 }
5838 
5839 InstructionCost BoUpSLP::getSpillCost() const {
5840   // Walk from the bottom of the tree to the top, tracking which values are
5841   // live. When we see a call instruction that is not part of our tree,
5842   // query TTI to see if there is a cost to keeping values live over it
5843   // (for example, if spills and fills are required).
5844   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5845   InstructionCost Cost = 0;
5846 
5847   SmallPtrSet<Instruction*, 4> LiveValues;
5848   Instruction *PrevInst = nullptr;
5849 
5850   // The entries in VectorizableTree are not necessarily ordered by their
5851   // position in basic blocks. Collect them and order them by dominance so later
5852   // instructions are guaranteed to be visited first. For instructions in
5853   // different basic blocks, we only scan to the beginning of the block, so
5854   // their order does not matter, as long as all instructions in a basic block
5855   // are grouped together. Using dominance ensures a deterministic order.
5856   SmallVector<Instruction *, 16> OrderedScalars;
5857   for (const auto &TEPtr : VectorizableTree) {
5858     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5859     if (!Inst)
5860       continue;
5861     OrderedScalars.push_back(Inst);
5862   }
5863   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5864     auto *NodeA = DT->getNode(A->getParent());
5865     auto *NodeB = DT->getNode(B->getParent());
5866     assert(NodeA && "Should only process reachable instructions");
5867     assert(NodeB && "Should only process reachable instructions");
5868     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5869            "Different nodes should have different DFS numbers");
5870     if (NodeA != NodeB)
5871       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5872     return B->comesBefore(A);
5873   });
5874 
5875   for (Instruction *Inst : OrderedScalars) {
5876     if (!PrevInst) {
5877       PrevInst = Inst;
5878       continue;
5879     }
5880 
5881     // Update LiveValues.
5882     LiveValues.erase(PrevInst);
5883     for (auto &J : PrevInst->operands()) {
5884       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5885         LiveValues.insert(cast<Instruction>(&*J));
5886     }
5887 
5888     LLVM_DEBUG({
5889       dbgs() << "SLP: #LV: " << LiveValues.size();
5890       for (auto *X : LiveValues)
5891         dbgs() << " " << X->getName();
5892       dbgs() << ", Looking at ";
5893       Inst->dump();
5894     });
5895 
5896     // Now find the sequence of instructions between PrevInst and Inst.
5897     unsigned NumCalls = 0;
5898     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5899                                  PrevInstIt =
5900                                      PrevInst->getIterator().getReverse();
5901     while (InstIt != PrevInstIt) {
5902       if (PrevInstIt == PrevInst->getParent()->rend()) {
5903         PrevInstIt = Inst->getParent()->rbegin();
5904         continue;
5905       }
5906 
5907       // Debug information does not impact spill cost.
5908       if ((isa<CallInst>(&*PrevInstIt) &&
5909            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5910           &*PrevInstIt != PrevInst)
5911         NumCalls++;
5912 
5913       ++PrevInstIt;
5914     }
5915 
5916     if (NumCalls) {
5917       SmallVector<Type*, 4> V;
5918       for (auto *II : LiveValues) {
5919         auto *ScalarTy = II->getType();
5920         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5921           ScalarTy = VectorTy->getElementType();
5922         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5923       }
5924       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5925     }
5926 
5927     PrevInst = Inst;
5928   }
5929 
5930   return Cost;
5931 }
5932 
5933 /// Check if two insertelement instructions are from the same buildvector.
5934 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5935                                             InsertElementInst *V) {
5936   // Instructions must be from the same basic blocks.
5937   if (VU->getParent() != V->getParent())
5938     return false;
5939   // Checks if 2 insertelements are from the same buildvector.
5940   if (VU->getType() != V->getType())
5941     return false;
5942   // Multiple used inserts are separate nodes.
5943   if (!VU->hasOneUse() && !V->hasOneUse())
5944     return false;
5945   auto *IE1 = VU;
5946   auto *IE2 = V;
5947   // Go through the vector operand of insertelement instructions trying to find
5948   // either VU as the original vector for IE2 or V as the original vector for
5949   // IE1.
5950   do {
5951     if (IE2 == VU || IE1 == V)
5952       return true;
5953     if (IE1) {
5954       if (IE1 != VU && !IE1->hasOneUse())
5955         IE1 = nullptr;
5956       else
5957         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5958     }
5959     if (IE2) {
5960       if (IE2 != V && !IE2->hasOneUse())
5961         IE2 = nullptr;
5962       else
5963         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5964     }
5965   } while (IE1 || IE2);
5966   return false;
5967 }
5968 
5969 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5970   InstructionCost Cost = 0;
5971   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5972                     << VectorizableTree.size() << ".\n");
5973 
5974   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5975 
5976   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5977     TreeEntry &TE = *VectorizableTree[I].get();
5978 
5979     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5980     Cost += C;
5981     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5982                       << " for bundle that starts with " << *TE.Scalars[0]
5983                       << ".\n"
5984                       << "SLP: Current total cost = " << Cost << "\n");
5985   }
5986 
5987   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5988   InstructionCost ExtractCost = 0;
5989   SmallVector<unsigned> VF;
5990   SmallVector<SmallVector<int>> ShuffleMask;
5991   SmallVector<Value *> FirstUsers;
5992   SmallVector<APInt> DemandedElts;
5993   for (ExternalUser &EU : ExternalUses) {
5994     // We only add extract cost once for the same scalar.
5995     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5996         !ExtractCostCalculated.insert(EU.Scalar).second)
5997       continue;
5998 
5999     // Uses by ephemeral values are free (because the ephemeral value will be
6000     // removed prior to code generation, and so the extraction will be
6001     // removed as well).
6002     if (EphValues.count(EU.User))
6003       continue;
6004 
6005     // No extract cost for vector "scalar"
6006     if (isa<FixedVectorType>(EU.Scalar->getType()))
6007       continue;
6008 
6009     // Already counted the cost for external uses when tried to adjust the cost
6010     // for extractelements, no need to add it again.
6011     if (isa<ExtractElementInst>(EU.Scalar))
6012       continue;
6013 
6014     // If found user is an insertelement, do not calculate extract cost but try
6015     // to detect it as a final shuffled/identity match.
6016     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6017       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6018         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6019         if (InsertIdx) {
6020           auto *It = find_if(FirstUsers, [VU](Value *V) {
6021             return areTwoInsertFromSameBuildVector(VU,
6022                                                    cast<InsertElementInst>(V));
6023           });
6024           int VecId = -1;
6025           if (It == FirstUsers.end()) {
6026             VF.push_back(FTy->getNumElements());
6027             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6028             // Find the insertvector, vectorized in tree, if any.
6029             Value *Base = VU;
6030             while (isa<InsertElementInst>(Base)) {
6031               // Build the mask for the vectorized insertelement instructions.
6032               if (const TreeEntry *E = getTreeEntry(Base)) {
6033                 VU = cast<InsertElementInst>(Base);
6034                 do {
6035                   int Idx = E->findLaneForValue(Base);
6036                   ShuffleMask.back()[Idx] = Idx;
6037                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6038                 } while (E == getTreeEntry(Base));
6039                 break;
6040               }
6041               Base = cast<InsertElementInst>(Base)->getOperand(0);
6042             }
6043             FirstUsers.push_back(VU);
6044             DemandedElts.push_back(APInt::getZero(VF.back()));
6045             VecId = FirstUsers.size() - 1;
6046           } else {
6047             VecId = std::distance(FirstUsers.begin(), It);
6048           }
6049           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6050           DemandedElts[VecId].setBit(*InsertIdx);
6051           continue;
6052         }
6053       }
6054     }
6055 
6056     // If we plan to rewrite the tree in a smaller type, we will need to sign
6057     // extend the extracted value back to the original type. Here, we account
6058     // for the extract and the added cost of the sign extend if needed.
6059     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6060     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6061     if (MinBWs.count(ScalarRoot)) {
6062       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6063       auto Extend =
6064           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6065       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6066       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6067                                                    VecTy, EU.Lane);
6068     } else {
6069       ExtractCost +=
6070           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6071     }
6072   }
6073 
6074   InstructionCost SpillCost = getSpillCost();
6075   Cost += SpillCost + ExtractCost;
6076   if (FirstUsers.size() == 1) {
6077     int Limit = ShuffleMask.front().size() * 2;
6078     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6079         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6080       InstructionCost C = TTI->getShuffleCost(
6081           TTI::SK_PermuteSingleSrc,
6082           cast<FixedVectorType>(FirstUsers.front()->getType()),
6083           ShuffleMask.front());
6084       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6085                         << " for final shuffle of insertelement external users "
6086                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6087                         << "SLP: Current total cost = " << Cost << "\n");
6088       Cost += C;
6089     }
6090     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6091         cast<FixedVectorType>(FirstUsers.front()->getType()),
6092         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6093     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6094                       << " for insertelements gather.\n"
6095                       << "SLP: Current total cost = " << Cost << "\n");
6096     Cost -= InsertCost;
6097   } else if (FirstUsers.size() >= 2) {
6098     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6099     // Combined masks of the first 2 vectors.
6100     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6101     copy(ShuffleMask.front(), CombinedMask.begin());
6102     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6103     auto *VecTy = FixedVectorType::get(
6104         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6105         MaxVF);
6106     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6107       if (ShuffleMask[1][I] != UndefMaskElem) {
6108         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6109         CombinedDemandedElts.setBit(I);
6110       }
6111     }
6112     InstructionCost C =
6113         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6114     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6115                       << " for final shuffle of vector node and external "
6116                          "insertelement users "
6117                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6118                       << "SLP: Current total cost = " << Cost << "\n");
6119     Cost += C;
6120     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6121         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6122     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6123                       << " for insertelements gather.\n"
6124                       << "SLP: Current total cost = " << Cost << "\n");
6125     Cost -= InsertCost;
6126     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6127       // Other elements - permutation of 2 vectors (the initial one and the
6128       // next Ith incoming vector).
6129       unsigned VF = ShuffleMask[I].size();
6130       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6131         int Mask = ShuffleMask[I][Idx];
6132         if (Mask != UndefMaskElem)
6133           CombinedMask[Idx] = MaxVF + Mask;
6134         else if (CombinedMask[Idx] != UndefMaskElem)
6135           CombinedMask[Idx] = Idx;
6136       }
6137       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6138         if (CombinedMask[Idx] != UndefMaskElem)
6139           CombinedMask[Idx] = Idx;
6140       InstructionCost C =
6141           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6142       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6143                         << " for final shuffle of vector node and external "
6144                            "insertelement users "
6145                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6146                         << "SLP: Current total cost = " << Cost << "\n");
6147       Cost += C;
6148       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6149           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6150           /*Insert*/ true, /*Extract*/ false);
6151       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6152                         << " for insertelements gather.\n"
6153                         << "SLP: Current total cost = " << Cost << "\n");
6154       Cost -= InsertCost;
6155     }
6156   }
6157 
6158 #ifndef NDEBUG
6159   SmallString<256> Str;
6160   {
6161     raw_svector_ostream OS(Str);
6162     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6163        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6164        << "SLP: Total Cost = " << Cost << ".\n";
6165   }
6166   LLVM_DEBUG(dbgs() << Str);
6167   if (ViewSLPTree)
6168     ViewGraph(this, "SLP" + F->getName(), false, Str);
6169 #endif
6170 
6171   return Cost;
6172 }
6173 
6174 Optional<TargetTransformInfo::ShuffleKind>
6175 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6176                                SmallVectorImpl<const TreeEntry *> &Entries) {
6177   // TODO: currently checking only for Scalars in the tree entry, need to count
6178   // reused elements too for better cost estimation.
6179   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6180   Entries.clear();
6181   // Build a lists of values to tree entries.
6182   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6183   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6184     if (EntryPtr.get() == TE)
6185       break;
6186     if (EntryPtr->State != TreeEntry::NeedToGather)
6187       continue;
6188     for (Value *V : EntryPtr->Scalars)
6189       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6190   }
6191   // Find all tree entries used by the gathered values. If no common entries
6192   // found - not a shuffle.
6193   // Here we build a set of tree nodes for each gathered value and trying to
6194   // find the intersection between these sets. If we have at least one common
6195   // tree node for each gathered value - we have just a permutation of the
6196   // single vector. If we have 2 different sets, we're in situation where we
6197   // have a permutation of 2 input vectors.
6198   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6199   DenseMap<Value *, int> UsedValuesEntry;
6200   for (Value *V : TE->Scalars) {
6201     if (isa<UndefValue>(V))
6202       continue;
6203     // Build a list of tree entries where V is used.
6204     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6205     auto It = ValueToTEs.find(V);
6206     if (It != ValueToTEs.end())
6207       VToTEs = It->second;
6208     if (const TreeEntry *VTE = getTreeEntry(V))
6209       VToTEs.insert(VTE);
6210     if (VToTEs.empty())
6211       return None;
6212     if (UsedTEs.empty()) {
6213       // The first iteration, just insert the list of nodes to vector.
6214       UsedTEs.push_back(VToTEs);
6215     } else {
6216       // Need to check if there are any previously used tree nodes which use V.
6217       // If there are no such nodes, consider that we have another one input
6218       // vector.
6219       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6220       unsigned Idx = 0;
6221       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6222         // Do we have a non-empty intersection of previously listed tree entries
6223         // and tree entries using current V?
6224         set_intersect(VToTEs, Set);
6225         if (!VToTEs.empty()) {
6226           // Yes, write the new subset and continue analysis for the next
6227           // scalar.
6228           Set.swap(VToTEs);
6229           break;
6230         }
6231         VToTEs = SavedVToTEs;
6232         ++Idx;
6233       }
6234       // No non-empty intersection found - need to add a second set of possible
6235       // source vectors.
6236       if (Idx == UsedTEs.size()) {
6237         // If the number of input vectors is greater than 2 - not a permutation,
6238         // fallback to the regular gather.
6239         if (UsedTEs.size() == 2)
6240           return None;
6241         UsedTEs.push_back(SavedVToTEs);
6242         Idx = UsedTEs.size() - 1;
6243       }
6244       UsedValuesEntry.try_emplace(V, Idx);
6245     }
6246   }
6247 
6248   unsigned VF = 0;
6249   if (UsedTEs.size() == 1) {
6250     // Try to find the perfect match in another gather node at first.
6251     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6252       return EntryPtr->isSame(TE->Scalars);
6253     });
6254     if (It != UsedTEs.front().end()) {
6255       Entries.push_back(*It);
6256       std::iota(Mask.begin(), Mask.end(), 0);
6257       return TargetTransformInfo::SK_PermuteSingleSrc;
6258     }
6259     // No perfect match, just shuffle, so choose the first tree node.
6260     Entries.push_back(*UsedTEs.front().begin());
6261   } else {
6262     // Try to find nodes with the same vector factor.
6263     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6264     DenseMap<int, const TreeEntry *> VFToTE;
6265     for (const TreeEntry *TE : UsedTEs.front())
6266       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6267     for (const TreeEntry *TE : UsedTEs.back()) {
6268       auto It = VFToTE.find(TE->getVectorFactor());
6269       if (It != VFToTE.end()) {
6270         VF = It->first;
6271         Entries.push_back(It->second);
6272         Entries.push_back(TE);
6273         break;
6274       }
6275     }
6276     // No 2 source vectors with the same vector factor - give up and do regular
6277     // gather.
6278     if (Entries.empty())
6279       return None;
6280   }
6281 
6282   // Build a shuffle mask for better cost estimation and vector emission.
6283   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6284     Value *V = TE->Scalars[I];
6285     if (isa<UndefValue>(V))
6286       continue;
6287     unsigned Idx = UsedValuesEntry.lookup(V);
6288     const TreeEntry *VTE = Entries[Idx];
6289     int FoundLane = VTE->findLaneForValue(V);
6290     Mask[I] = Idx * VF + FoundLane;
6291     // Extra check required by isSingleSourceMaskImpl function (called by
6292     // ShuffleVectorInst::isSingleSourceMask).
6293     if (Mask[I] >= 2 * E)
6294       return None;
6295   }
6296   switch (Entries.size()) {
6297   case 1:
6298     return TargetTransformInfo::SK_PermuteSingleSrc;
6299   case 2:
6300     return TargetTransformInfo::SK_PermuteTwoSrc;
6301   default:
6302     break;
6303   }
6304   return None;
6305 }
6306 
6307 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6308                                        const APInt &ShuffledIndices,
6309                                        bool NeedToShuffle) const {
6310   InstructionCost Cost =
6311       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6312                                     /*Extract*/ false);
6313   if (NeedToShuffle)
6314     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6315   return Cost;
6316 }
6317 
6318 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6319   // Find the type of the operands in VL.
6320   Type *ScalarTy = VL[0]->getType();
6321   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6322     ScalarTy = SI->getValueOperand()->getType();
6323   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6324   bool DuplicateNonConst = false;
6325   // Find the cost of inserting/extracting values from the vector.
6326   // Check if the same elements are inserted several times and count them as
6327   // shuffle candidates.
6328   APInt ShuffledElements = APInt::getZero(VL.size());
6329   DenseSet<Value *> UniqueElements;
6330   // Iterate in reverse order to consider insert elements with the high cost.
6331   for (unsigned I = VL.size(); I > 0; --I) {
6332     unsigned Idx = I - 1;
6333     // No need to shuffle duplicates for constants.
6334     if (isConstant(VL[Idx])) {
6335       ShuffledElements.setBit(Idx);
6336       continue;
6337     }
6338     if (!UniqueElements.insert(VL[Idx]).second) {
6339       DuplicateNonConst = true;
6340       ShuffledElements.setBit(Idx);
6341     }
6342   }
6343   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6344 }
6345 
6346 // Perform operand reordering on the instructions in VL and return the reordered
6347 // operands in Left and Right.
6348 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6349                                              SmallVectorImpl<Value *> &Left,
6350                                              SmallVectorImpl<Value *> &Right,
6351                                              const DataLayout &DL,
6352                                              ScalarEvolution &SE,
6353                                              const BoUpSLP &R) {
6354   if (VL.empty())
6355     return;
6356   VLOperands Ops(VL, DL, SE, R);
6357   // Reorder the operands in place.
6358   Ops.reorder();
6359   Left = Ops.getVL(0);
6360   Right = Ops.getVL(1);
6361 }
6362 
6363 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6364   // Get the basic block this bundle is in. All instructions in the bundle
6365   // should be in this block.
6366   auto *Front = E->getMainOp();
6367   auto *BB = Front->getParent();
6368   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6369     auto *I = cast<Instruction>(V);
6370     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6371   }));
6372 
6373   // The last instruction in the bundle in program order.
6374   Instruction *LastInst = nullptr;
6375 
6376   // Find the last instruction. The common case should be that BB has been
6377   // scheduled, and the last instruction is VL.back(). So we start with
6378   // VL.back() and iterate over schedule data until we reach the end of the
6379   // bundle. The end of the bundle is marked by null ScheduleData.
6380   if (BlocksSchedules.count(BB)) {
6381     auto *Bundle =
6382         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6383     if (Bundle && Bundle->isPartOfBundle())
6384       for (; Bundle; Bundle = Bundle->NextInBundle)
6385         if (Bundle->OpValue == Bundle->Inst)
6386           LastInst = Bundle->Inst;
6387   }
6388 
6389   // LastInst can still be null at this point if there's either not an entry
6390   // for BB in BlocksSchedules or there's no ScheduleData available for
6391   // VL.back(). This can be the case if buildTree_rec aborts for various
6392   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6393   // size is reached, etc.). ScheduleData is initialized in the scheduling
6394   // "dry-run".
6395   //
6396   // If this happens, we can still find the last instruction by brute force. We
6397   // iterate forwards from Front (inclusive) until we either see all
6398   // instructions in the bundle or reach the end of the block. If Front is the
6399   // last instruction in program order, LastInst will be set to Front, and we
6400   // will visit all the remaining instructions in the block.
6401   //
6402   // One of the reasons we exit early from buildTree_rec is to place an upper
6403   // bound on compile-time. Thus, taking an additional compile-time hit here is
6404   // not ideal. However, this should be exceedingly rare since it requires that
6405   // we both exit early from buildTree_rec and that the bundle be out-of-order
6406   // (causing us to iterate all the way to the end of the block).
6407   if (!LastInst) {
6408     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6409     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6410       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6411         LastInst = &I;
6412       if (Bundle.empty())
6413         break;
6414     }
6415   }
6416   assert(LastInst && "Failed to find last instruction in bundle");
6417 
6418   // Set the insertion point after the last instruction in the bundle. Set the
6419   // debug location to Front.
6420   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6421   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6422 }
6423 
6424 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6425   // List of instructions/lanes from current block and/or the blocks which are
6426   // part of the current loop. These instructions will be inserted at the end to
6427   // make it possible to optimize loops and hoist invariant instructions out of
6428   // the loops body with better chances for success.
6429   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6430   SmallSet<int, 4> PostponedIndices;
6431   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6432   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6433     SmallPtrSet<BasicBlock *, 4> Visited;
6434     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6435       InsertBB = InsertBB->getSinglePredecessor();
6436     return InsertBB && InsertBB == InstBB;
6437   };
6438   for (int I = 0, E = VL.size(); I < E; ++I) {
6439     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6440       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6441            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6442           PostponedIndices.insert(I).second)
6443         PostponedInsts.emplace_back(Inst, I);
6444   }
6445 
6446   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6447     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6448     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6449     if (!InsElt)
6450       return Vec;
6451     GatherShuffleSeq.insert(InsElt);
6452     CSEBlocks.insert(InsElt->getParent());
6453     // Add to our 'need-to-extract' list.
6454     if (TreeEntry *Entry = getTreeEntry(V)) {
6455       // Find which lane we need to extract.
6456       unsigned FoundLane = Entry->findLaneForValue(V);
6457       ExternalUses.emplace_back(V, InsElt, FoundLane);
6458     }
6459     return Vec;
6460   };
6461   Value *Val0 =
6462       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6463   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6464   Value *Vec = PoisonValue::get(VecTy);
6465   SmallVector<int> NonConsts;
6466   // Insert constant values at first.
6467   for (int I = 0, E = VL.size(); I < E; ++I) {
6468     if (PostponedIndices.contains(I))
6469       continue;
6470     if (!isConstant(VL[I])) {
6471       NonConsts.push_back(I);
6472       continue;
6473     }
6474     Vec = CreateInsertElement(Vec, VL[I], I);
6475   }
6476   // Insert non-constant values.
6477   for (int I : NonConsts)
6478     Vec = CreateInsertElement(Vec, VL[I], I);
6479   // Append instructions, which are/may be part of the loop, in the end to make
6480   // it possible to hoist non-loop-based instructions.
6481   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6482     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6483 
6484   return Vec;
6485 }
6486 
6487 namespace {
6488 /// Merges shuffle masks and emits final shuffle instruction, if required.
6489 class ShuffleInstructionBuilder {
6490   IRBuilderBase &Builder;
6491   const unsigned VF = 0;
6492   bool IsFinalized = false;
6493   SmallVector<int, 4> Mask;
6494   /// Holds all of the instructions that we gathered.
6495   SetVector<Instruction *> &GatherShuffleSeq;
6496   /// A list of blocks that we are going to CSE.
6497   SetVector<BasicBlock *> &CSEBlocks;
6498 
6499 public:
6500   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6501                             SetVector<Instruction *> &GatherShuffleSeq,
6502                             SetVector<BasicBlock *> &CSEBlocks)
6503       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6504         CSEBlocks(CSEBlocks) {}
6505 
6506   /// Adds a mask, inverting it before applying.
6507   void addInversedMask(ArrayRef<unsigned> SubMask) {
6508     if (SubMask.empty())
6509       return;
6510     SmallVector<int, 4> NewMask;
6511     inversePermutation(SubMask, NewMask);
6512     addMask(NewMask);
6513   }
6514 
6515   /// Functions adds masks, merging them into  single one.
6516   void addMask(ArrayRef<unsigned> SubMask) {
6517     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6518     addMask(NewMask);
6519   }
6520 
6521   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6522 
6523   Value *finalize(Value *V) {
6524     IsFinalized = true;
6525     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6526     if (VF == ValueVF && Mask.empty())
6527       return V;
6528     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6529     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6530     addMask(NormalizedMask);
6531 
6532     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6533       return V;
6534     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6535     if (auto *I = dyn_cast<Instruction>(Vec)) {
6536       GatherShuffleSeq.insert(I);
6537       CSEBlocks.insert(I->getParent());
6538     }
6539     return Vec;
6540   }
6541 
6542   ~ShuffleInstructionBuilder() {
6543     assert((IsFinalized || Mask.empty()) &&
6544            "Shuffle construction must be finalized.");
6545   }
6546 };
6547 } // namespace
6548 
6549 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6550   unsigned VF = VL.size();
6551   InstructionsState S = getSameOpcode(VL);
6552   if (S.getOpcode()) {
6553     if (TreeEntry *E = getTreeEntry(S.OpValue))
6554       if (E->isSame(VL)) {
6555         Value *V = vectorizeTree(E);
6556         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6557           if (!E->ReuseShuffleIndices.empty()) {
6558             // Reshuffle to get only unique values.
6559             // If some of the scalars are duplicated in the vectorization tree
6560             // entry, we do not vectorize them but instead generate a mask for
6561             // the reuses. But if there are several users of the same entry,
6562             // they may have different vectorization factors. This is especially
6563             // important for PHI nodes. In this case, we need to adapt the
6564             // resulting instruction for the user vectorization factor and have
6565             // to reshuffle it again to take only unique elements of the vector.
6566             // Without this code the function incorrectly returns reduced vector
6567             // instruction with the same elements, not with the unique ones.
6568 
6569             // block:
6570             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6571             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6572             // ... (use %2)
6573             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6574             // br %block
6575             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6576             SmallSet<int, 4> UsedIdxs;
6577             int Pos = 0;
6578             int Sz = VL.size();
6579             for (int Idx : E->ReuseShuffleIndices) {
6580               if (Idx != Sz && Idx != UndefMaskElem &&
6581                   UsedIdxs.insert(Idx).second)
6582                 UniqueIdxs[Idx] = Pos;
6583               ++Pos;
6584             }
6585             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6586                                             "less than original vector size.");
6587             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6588             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6589           } else {
6590             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6591                    "Expected vectorization factor less "
6592                    "than original vector size.");
6593             SmallVector<int> UniformMask(VF, 0);
6594             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6595             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6596           }
6597           if (auto *I = dyn_cast<Instruction>(V)) {
6598             GatherShuffleSeq.insert(I);
6599             CSEBlocks.insert(I->getParent());
6600           }
6601         }
6602         return V;
6603       }
6604   }
6605 
6606   // Check that every instruction appears once in this bundle.
6607   SmallVector<int> ReuseShuffleIndicies;
6608   SmallVector<Value *> UniqueValues;
6609   if (VL.size() > 2) {
6610     DenseMap<Value *, unsigned> UniquePositions;
6611     unsigned NumValues =
6612         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6613                                     return !isa<UndefValue>(V);
6614                                   }).base());
6615     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6616     int UniqueVals = 0;
6617     for (Value *V : VL.drop_back(VL.size() - VF)) {
6618       if (isa<UndefValue>(V)) {
6619         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6620         continue;
6621       }
6622       if (isConstant(V)) {
6623         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6624         UniqueValues.emplace_back(V);
6625         continue;
6626       }
6627       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6628       ReuseShuffleIndicies.emplace_back(Res.first->second);
6629       if (Res.second) {
6630         UniqueValues.emplace_back(V);
6631         ++UniqueVals;
6632       }
6633     }
6634     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6635       // Emit pure splat vector.
6636       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6637                                   UndefMaskElem);
6638     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6639       ReuseShuffleIndicies.clear();
6640       UniqueValues.clear();
6641       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6642     }
6643     UniqueValues.append(VF - UniqueValues.size(),
6644                         PoisonValue::get(VL[0]->getType()));
6645     VL = UniqueValues;
6646   }
6647 
6648   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6649                                            CSEBlocks);
6650   Value *Vec = gather(VL);
6651   if (!ReuseShuffleIndicies.empty()) {
6652     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6653     Vec = ShuffleBuilder.finalize(Vec);
6654   }
6655   return Vec;
6656 }
6657 
6658 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6659   IRBuilder<>::InsertPointGuard Guard(Builder);
6660 
6661   if (E->VectorizedValue) {
6662     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6663     return E->VectorizedValue;
6664   }
6665 
6666   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6667   unsigned VF = E->getVectorFactor();
6668   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6669                                            CSEBlocks);
6670   if (E->State == TreeEntry::NeedToGather) {
6671     if (E->getMainOp())
6672       setInsertPointAfterBundle(E);
6673     Value *Vec;
6674     SmallVector<int> Mask;
6675     SmallVector<const TreeEntry *> Entries;
6676     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6677         isGatherShuffledEntry(E, Mask, Entries);
6678     if (Shuffle.hasValue()) {
6679       assert((Entries.size() == 1 || Entries.size() == 2) &&
6680              "Expected shuffle of 1 or 2 entries.");
6681       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6682                                         Entries.back()->VectorizedValue, Mask);
6683       if (auto *I = dyn_cast<Instruction>(Vec)) {
6684         GatherShuffleSeq.insert(I);
6685         CSEBlocks.insert(I->getParent());
6686       }
6687     } else {
6688       Vec = gather(E->Scalars);
6689     }
6690     if (NeedToShuffleReuses) {
6691       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6692       Vec = ShuffleBuilder.finalize(Vec);
6693     }
6694     E->VectorizedValue = Vec;
6695     return Vec;
6696   }
6697 
6698   assert((E->State == TreeEntry::Vectorize ||
6699           E->State == TreeEntry::ScatterVectorize) &&
6700          "Unhandled state");
6701   unsigned ShuffleOrOp =
6702       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6703   Instruction *VL0 = E->getMainOp();
6704   Type *ScalarTy = VL0->getType();
6705   if (auto *Store = dyn_cast<StoreInst>(VL0))
6706     ScalarTy = Store->getValueOperand()->getType();
6707   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6708     ScalarTy = IE->getOperand(1)->getType();
6709   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6710   switch (ShuffleOrOp) {
6711     case Instruction::PHI: {
6712       assert(
6713           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6714           "PHI reordering is free.");
6715       auto *PH = cast<PHINode>(VL0);
6716       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6717       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6718       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6719       Value *V = NewPhi;
6720 
6721       // Adjust insertion point once all PHI's have been generated.
6722       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6723       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6724 
6725       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6726       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6727       V = ShuffleBuilder.finalize(V);
6728 
6729       E->VectorizedValue = V;
6730 
6731       // PHINodes may have multiple entries from the same block. We want to
6732       // visit every block once.
6733       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6734 
6735       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6736         ValueList Operands;
6737         BasicBlock *IBB = PH->getIncomingBlock(i);
6738 
6739         if (!VisitedBBs.insert(IBB).second) {
6740           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6741           continue;
6742         }
6743 
6744         Builder.SetInsertPoint(IBB->getTerminator());
6745         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6746         Value *Vec = vectorizeTree(E->getOperand(i));
6747         NewPhi->addIncoming(Vec, IBB);
6748       }
6749 
6750       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6751              "Invalid number of incoming values");
6752       return V;
6753     }
6754 
6755     case Instruction::ExtractElement: {
6756       Value *V = E->getSingleOperand(0);
6757       Builder.SetInsertPoint(VL0);
6758       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6759       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6760       V = ShuffleBuilder.finalize(V);
6761       E->VectorizedValue = V;
6762       return V;
6763     }
6764     case Instruction::ExtractValue: {
6765       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6766       Builder.SetInsertPoint(LI);
6767       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6768       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6769       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6770       Value *NewV = propagateMetadata(V, E->Scalars);
6771       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6772       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6773       NewV = ShuffleBuilder.finalize(NewV);
6774       E->VectorizedValue = NewV;
6775       return NewV;
6776     }
6777     case Instruction::InsertElement: {
6778       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6779       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6780       Value *V = vectorizeTree(E->getOperand(1));
6781 
6782       // Create InsertVector shuffle if necessary
6783       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6784         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6785       }));
6786       const unsigned NumElts =
6787           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6788       const unsigned NumScalars = E->Scalars.size();
6789 
6790       unsigned Offset = *getInsertIndex(VL0);
6791       assert(Offset < NumElts && "Failed to find vector index offset");
6792 
6793       // Create shuffle to resize vector
6794       SmallVector<int> Mask;
6795       if (!E->ReorderIndices.empty()) {
6796         inversePermutation(E->ReorderIndices, Mask);
6797         Mask.append(NumElts - NumScalars, UndefMaskElem);
6798       } else {
6799         Mask.assign(NumElts, UndefMaskElem);
6800         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6801       }
6802       // Create InsertVector shuffle if necessary
6803       bool IsIdentity = true;
6804       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6805       Mask.swap(PrevMask);
6806       for (unsigned I = 0; I < NumScalars; ++I) {
6807         Value *Scalar = E->Scalars[PrevMask[I]];
6808         unsigned InsertIdx = *getInsertIndex(Scalar);
6809         IsIdentity &= InsertIdx - Offset == I;
6810         Mask[InsertIdx - Offset] = I;
6811       }
6812       if (!IsIdentity || NumElts != NumScalars) {
6813         V = Builder.CreateShuffleVector(V, Mask);
6814         if (auto *I = dyn_cast<Instruction>(V)) {
6815           GatherShuffleSeq.insert(I);
6816           CSEBlocks.insert(I->getParent());
6817         }
6818       }
6819 
6820       if ((!IsIdentity || Offset != 0 ||
6821            !isUndefVector(FirstInsert->getOperand(0))) &&
6822           NumElts != NumScalars) {
6823         SmallVector<int> InsertMask(NumElts);
6824         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6825         for (unsigned I = 0; I < NumElts; I++) {
6826           if (Mask[I] != UndefMaskElem)
6827             InsertMask[Offset + I] = NumElts + I;
6828         }
6829 
6830         V = Builder.CreateShuffleVector(
6831             FirstInsert->getOperand(0), V, InsertMask,
6832             cast<Instruction>(E->Scalars.back())->getName());
6833         if (auto *I = dyn_cast<Instruction>(V)) {
6834           GatherShuffleSeq.insert(I);
6835           CSEBlocks.insert(I->getParent());
6836         }
6837       }
6838 
6839       ++NumVectorInstructions;
6840       E->VectorizedValue = V;
6841       return V;
6842     }
6843     case Instruction::ZExt:
6844     case Instruction::SExt:
6845     case Instruction::FPToUI:
6846     case Instruction::FPToSI:
6847     case Instruction::FPExt:
6848     case Instruction::PtrToInt:
6849     case Instruction::IntToPtr:
6850     case Instruction::SIToFP:
6851     case Instruction::UIToFP:
6852     case Instruction::Trunc:
6853     case Instruction::FPTrunc:
6854     case Instruction::BitCast: {
6855       setInsertPointAfterBundle(E);
6856 
6857       Value *InVec = vectorizeTree(E->getOperand(0));
6858 
6859       if (E->VectorizedValue) {
6860         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6861         return E->VectorizedValue;
6862       }
6863 
6864       auto *CI = cast<CastInst>(VL0);
6865       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6866       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6867       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6868       V = ShuffleBuilder.finalize(V);
6869 
6870       E->VectorizedValue = V;
6871       ++NumVectorInstructions;
6872       return V;
6873     }
6874     case Instruction::FCmp:
6875     case Instruction::ICmp: {
6876       setInsertPointAfterBundle(E);
6877 
6878       Value *L = vectorizeTree(E->getOperand(0));
6879       Value *R = vectorizeTree(E->getOperand(1));
6880 
6881       if (E->VectorizedValue) {
6882         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6883         return E->VectorizedValue;
6884       }
6885 
6886       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6887       Value *V = Builder.CreateCmp(P0, L, R);
6888       propagateIRFlags(V, E->Scalars, VL0);
6889       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6890       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6891       V = ShuffleBuilder.finalize(V);
6892 
6893       E->VectorizedValue = V;
6894       ++NumVectorInstructions;
6895       return V;
6896     }
6897     case Instruction::Select: {
6898       setInsertPointAfterBundle(E);
6899 
6900       Value *Cond = vectorizeTree(E->getOperand(0));
6901       Value *True = vectorizeTree(E->getOperand(1));
6902       Value *False = vectorizeTree(E->getOperand(2));
6903 
6904       if (E->VectorizedValue) {
6905         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6906         return E->VectorizedValue;
6907       }
6908 
6909       Value *V = Builder.CreateSelect(Cond, True, False);
6910       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6911       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6912       V = ShuffleBuilder.finalize(V);
6913 
6914       E->VectorizedValue = V;
6915       ++NumVectorInstructions;
6916       return V;
6917     }
6918     case Instruction::FNeg: {
6919       setInsertPointAfterBundle(E);
6920 
6921       Value *Op = vectorizeTree(E->getOperand(0));
6922 
6923       if (E->VectorizedValue) {
6924         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6925         return E->VectorizedValue;
6926       }
6927 
6928       Value *V = Builder.CreateUnOp(
6929           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6930       propagateIRFlags(V, E->Scalars, VL0);
6931       if (auto *I = dyn_cast<Instruction>(V))
6932         V = propagateMetadata(I, E->Scalars);
6933 
6934       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6935       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6936       V = ShuffleBuilder.finalize(V);
6937 
6938       E->VectorizedValue = V;
6939       ++NumVectorInstructions;
6940 
6941       return V;
6942     }
6943     case Instruction::Add:
6944     case Instruction::FAdd:
6945     case Instruction::Sub:
6946     case Instruction::FSub:
6947     case Instruction::Mul:
6948     case Instruction::FMul:
6949     case Instruction::UDiv:
6950     case Instruction::SDiv:
6951     case Instruction::FDiv:
6952     case Instruction::URem:
6953     case Instruction::SRem:
6954     case Instruction::FRem:
6955     case Instruction::Shl:
6956     case Instruction::LShr:
6957     case Instruction::AShr:
6958     case Instruction::And:
6959     case Instruction::Or:
6960     case Instruction::Xor: {
6961       setInsertPointAfterBundle(E);
6962 
6963       Value *LHS = vectorizeTree(E->getOperand(0));
6964       Value *RHS = vectorizeTree(E->getOperand(1));
6965 
6966       if (E->VectorizedValue) {
6967         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6968         return E->VectorizedValue;
6969       }
6970 
6971       Value *V = Builder.CreateBinOp(
6972           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6973           RHS);
6974       propagateIRFlags(V, E->Scalars, VL0);
6975       if (auto *I = dyn_cast<Instruction>(V))
6976         V = propagateMetadata(I, E->Scalars);
6977 
6978       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6979       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6980       V = ShuffleBuilder.finalize(V);
6981 
6982       E->VectorizedValue = V;
6983       ++NumVectorInstructions;
6984 
6985       return V;
6986     }
6987     case Instruction::Load: {
6988       // Loads are inserted at the head of the tree because we don't want to
6989       // sink them all the way down past store instructions.
6990       setInsertPointAfterBundle(E);
6991 
6992       LoadInst *LI = cast<LoadInst>(VL0);
6993       Instruction *NewLI;
6994       unsigned AS = LI->getPointerAddressSpace();
6995       Value *PO = LI->getPointerOperand();
6996       if (E->State == TreeEntry::Vectorize) {
6997 
6998         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6999 
7000         // The pointer operand uses an in-tree scalar so we add the new BitCast
7001         // to ExternalUses list to make sure that an extract will be generated
7002         // in the future.
7003         if (TreeEntry *Entry = getTreeEntry(PO)) {
7004           // Find which lane we need to extract.
7005           unsigned FoundLane = Entry->findLaneForValue(PO);
7006           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
7007         }
7008 
7009         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7010       } else {
7011         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7012         Value *VecPtr = vectorizeTree(E->getOperand(0));
7013         // Use the minimum alignment of the gathered loads.
7014         Align CommonAlignment = LI->getAlign();
7015         for (Value *V : E->Scalars)
7016           CommonAlignment =
7017               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7018         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7019       }
7020       Value *V = propagateMetadata(NewLI, E->Scalars);
7021 
7022       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7023       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7024       V = ShuffleBuilder.finalize(V);
7025       E->VectorizedValue = V;
7026       ++NumVectorInstructions;
7027       return V;
7028     }
7029     case Instruction::Store: {
7030       auto *SI = cast<StoreInst>(VL0);
7031       unsigned AS = SI->getPointerAddressSpace();
7032 
7033       setInsertPointAfterBundle(E);
7034 
7035       Value *VecValue = vectorizeTree(E->getOperand(0));
7036       ShuffleBuilder.addMask(E->ReorderIndices);
7037       VecValue = ShuffleBuilder.finalize(VecValue);
7038 
7039       Value *ScalarPtr = SI->getPointerOperand();
7040       Value *VecPtr = Builder.CreateBitCast(
7041           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7042       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
7043                                                  SI->getAlign());
7044 
7045       // The pointer operand uses an in-tree scalar, so add the new BitCast to
7046       // ExternalUses to make sure that an extract will be generated in the
7047       // future.
7048       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7049         // Find which lane we need to extract.
7050         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7051         ExternalUses.push_back(
7052             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
7053       }
7054 
7055       Value *V = propagateMetadata(ST, E->Scalars);
7056 
7057       E->VectorizedValue = V;
7058       ++NumVectorInstructions;
7059       return V;
7060     }
7061     case Instruction::GetElementPtr: {
7062       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7063       setInsertPointAfterBundle(E);
7064 
7065       Value *Op0 = vectorizeTree(E->getOperand(0));
7066 
7067       SmallVector<Value *> OpVecs;
7068       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7069         Value *OpVec = vectorizeTree(E->getOperand(J));
7070         OpVecs.push_back(OpVec);
7071       }
7072 
7073       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7074       if (Instruction *I = dyn_cast<Instruction>(V))
7075         V = propagateMetadata(I, E->Scalars);
7076 
7077       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7078       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7079       V = ShuffleBuilder.finalize(V);
7080 
7081       E->VectorizedValue = V;
7082       ++NumVectorInstructions;
7083 
7084       return V;
7085     }
7086     case Instruction::Call: {
7087       CallInst *CI = cast<CallInst>(VL0);
7088       setInsertPointAfterBundle(E);
7089 
7090       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7091       if (Function *FI = CI->getCalledFunction())
7092         IID = FI->getIntrinsicID();
7093 
7094       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7095 
7096       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7097       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7098                           VecCallCosts.first <= VecCallCosts.second;
7099 
7100       Value *ScalarArg = nullptr;
7101       std::vector<Value *> OpVecs;
7102       SmallVector<Type *, 2> TysForDecl =
7103           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7104       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7105         ValueList OpVL;
7106         // Some intrinsics have scalar arguments. This argument should not be
7107         // vectorized.
7108         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7109           CallInst *CEI = cast<CallInst>(VL0);
7110           ScalarArg = CEI->getArgOperand(j);
7111           OpVecs.push_back(CEI->getArgOperand(j));
7112           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7113             TysForDecl.push_back(ScalarArg->getType());
7114           continue;
7115         }
7116 
7117         Value *OpVec = vectorizeTree(E->getOperand(j));
7118         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7119         OpVecs.push_back(OpVec);
7120       }
7121 
7122       Function *CF;
7123       if (!UseIntrinsic) {
7124         VFShape Shape =
7125             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7126                                   VecTy->getNumElements())),
7127                          false /*HasGlobalPred*/);
7128         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7129       } else {
7130         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7131       }
7132 
7133       SmallVector<OperandBundleDef, 1> OpBundles;
7134       CI->getOperandBundlesAsDefs(OpBundles);
7135       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7136 
7137       // The scalar argument uses an in-tree scalar so we add the new vectorized
7138       // call to ExternalUses list to make sure that an extract will be
7139       // generated in the future.
7140       if (ScalarArg) {
7141         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7142           // Find which lane we need to extract.
7143           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7144           ExternalUses.push_back(
7145               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7146         }
7147       }
7148 
7149       propagateIRFlags(V, E->Scalars, VL0);
7150       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7151       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7152       V = ShuffleBuilder.finalize(V);
7153 
7154       E->VectorizedValue = V;
7155       ++NumVectorInstructions;
7156       return V;
7157     }
7158     case Instruction::ShuffleVector: {
7159       assert(E->isAltShuffle() &&
7160              ((Instruction::isBinaryOp(E->getOpcode()) &&
7161                Instruction::isBinaryOp(E->getAltOpcode())) ||
7162               (Instruction::isCast(E->getOpcode()) &&
7163                Instruction::isCast(E->getAltOpcode())) ||
7164               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7165              "Invalid Shuffle Vector Operand");
7166 
7167       Value *LHS = nullptr, *RHS = nullptr;
7168       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7169         setInsertPointAfterBundle(E);
7170         LHS = vectorizeTree(E->getOperand(0));
7171         RHS = vectorizeTree(E->getOperand(1));
7172       } else {
7173         setInsertPointAfterBundle(E);
7174         LHS = vectorizeTree(E->getOperand(0));
7175       }
7176 
7177       if (E->VectorizedValue) {
7178         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7179         return E->VectorizedValue;
7180       }
7181 
7182       Value *V0, *V1;
7183       if (Instruction::isBinaryOp(E->getOpcode())) {
7184         V0 = Builder.CreateBinOp(
7185             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7186         V1 = Builder.CreateBinOp(
7187             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7188       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7189         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7190         auto *AltCI = cast<CmpInst>(E->getAltOp());
7191         CmpInst::Predicate AltPred = AltCI->getPredicate();
7192         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7193       } else {
7194         V0 = Builder.CreateCast(
7195             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7196         V1 = Builder.CreateCast(
7197             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7198       }
7199       // Add V0 and V1 to later analysis to try to find and remove matching
7200       // instruction, if any.
7201       for (Value *V : {V0, V1}) {
7202         if (auto *I = dyn_cast<Instruction>(V)) {
7203           GatherShuffleSeq.insert(I);
7204           CSEBlocks.insert(I->getParent());
7205         }
7206       }
7207 
7208       // Create shuffle to take alternate operations from the vector.
7209       // Also, gather up main and alt scalar ops to propagate IR flags to
7210       // each vector operation.
7211       ValueList OpScalars, AltScalars;
7212       SmallVector<int> Mask;
7213       buildShuffleEntryMask(
7214           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7215           [E](Instruction *I) {
7216             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7217             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7218           },
7219           Mask, &OpScalars, &AltScalars);
7220 
7221       propagateIRFlags(V0, OpScalars);
7222       propagateIRFlags(V1, AltScalars);
7223 
7224       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7225       if (auto *I = dyn_cast<Instruction>(V)) {
7226         V = propagateMetadata(I, E->Scalars);
7227         GatherShuffleSeq.insert(I);
7228         CSEBlocks.insert(I->getParent());
7229       }
7230       V = ShuffleBuilder.finalize(V);
7231 
7232       E->VectorizedValue = V;
7233       ++NumVectorInstructions;
7234 
7235       return V;
7236     }
7237     default:
7238     llvm_unreachable("unknown inst");
7239   }
7240   return nullptr;
7241 }
7242 
7243 Value *BoUpSLP::vectorizeTree() {
7244   ExtraValueToDebugLocsMap ExternallyUsedValues;
7245   return vectorizeTree(ExternallyUsedValues);
7246 }
7247 
7248 Value *
7249 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7250   // All blocks must be scheduled before any instructions are inserted.
7251   for (auto &BSIter : BlocksSchedules) {
7252     scheduleBlock(BSIter.second.get());
7253   }
7254 
7255   Builder.SetInsertPoint(&F->getEntryBlock().front());
7256   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7257 
7258   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7259   // vectorized root. InstCombine will then rewrite the entire expression. We
7260   // sign extend the extracted values below.
7261   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7262   if (MinBWs.count(ScalarRoot)) {
7263     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7264       // If current instr is a phi and not the last phi, insert it after the
7265       // last phi node.
7266       if (isa<PHINode>(I))
7267         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7268       else
7269         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7270     }
7271     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7272     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7273     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7274     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7275     VectorizableTree[0]->VectorizedValue = Trunc;
7276   }
7277 
7278   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7279                     << " values .\n");
7280 
7281   // Extract all of the elements with the external uses.
7282   for (const auto &ExternalUse : ExternalUses) {
7283     Value *Scalar = ExternalUse.Scalar;
7284     llvm::User *User = ExternalUse.User;
7285 
7286     // Skip users that we already RAUW. This happens when one instruction
7287     // has multiple uses of the same value.
7288     if (User && !is_contained(Scalar->users(), User))
7289       continue;
7290     TreeEntry *E = getTreeEntry(Scalar);
7291     assert(E && "Invalid scalar");
7292     assert(E->State != TreeEntry::NeedToGather &&
7293            "Extracting from a gather list");
7294 
7295     Value *Vec = E->VectorizedValue;
7296     assert(Vec && "Can't find vectorizable value");
7297 
7298     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7299     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7300       if (Scalar->getType() != Vec->getType()) {
7301         Value *Ex;
7302         // "Reuse" the existing extract to improve final codegen.
7303         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7304           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7305                                             ES->getOperand(1));
7306         } else {
7307           Ex = Builder.CreateExtractElement(Vec, Lane);
7308         }
7309         // If necessary, sign-extend or zero-extend ScalarRoot
7310         // to the larger type.
7311         if (!MinBWs.count(ScalarRoot))
7312           return Ex;
7313         if (MinBWs[ScalarRoot].second)
7314           return Builder.CreateSExt(Ex, Scalar->getType());
7315         return Builder.CreateZExt(Ex, Scalar->getType());
7316       }
7317       assert(isa<FixedVectorType>(Scalar->getType()) &&
7318              isa<InsertElementInst>(Scalar) &&
7319              "In-tree scalar of vector type is not insertelement?");
7320       return Vec;
7321     };
7322     // If User == nullptr, the Scalar is used as extra arg. Generate
7323     // ExtractElement instruction and update the record for this scalar in
7324     // ExternallyUsedValues.
7325     if (!User) {
7326       assert(ExternallyUsedValues.count(Scalar) &&
7327              "Scalar with nullptr as an external user must be registered in "
7328              "ExternallyUsedValues map");
7329       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7330         Builder.SetInsertPoint(VecI->getParent(),
7331                                std::next(VecI->getIterator()));
7332       } else {
7333         Builder.SetInsertPoint(&F->getEntryBlock().front());
7334       }
7335       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7336       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7337       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7338       auto It = ExternallyUsedValues.find(Scalar);
7339       assert(It != ExternallyUsedValues.end() &&
7340              "Externally used scalar is not found in ExternallyUsedValues");
7341       NewInstLocs.append(It->second);
7342       ExternallyUsedValues.erase(Scalar);
7343       // Required to update internally referenced instructions.
7344       Scalar->replaceAllUsesWith(NewInst);
7345       continue;
7346     }
7347 
7348     // Generate extracts for out-of-tree users.
7349     // Find the insertion point for the extractelement lane.
7350     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7351       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7352         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7353           if (PH->getIncomingValue(i) == Scalar) {
7354             Instruction *IncomingTerminator =
7355                 PH->getIncomingBlock(i)->getTerminator();
7356             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7357               Builder.SetInsertPoint(VecI->getParent(),
7358                                      std::next(VecI->getIterator()));
7359             } else {
7360               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7361             }
7362             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7363             CSEBlocks.insert(PH->getIncomingBlock(i));
7364             PH->setOperand(i, NewInst);
7365           }
7366         }
7367       } else {
7368         Builder.SetInsertPoint(cast<Instruction>(User));
7369         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7370         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7371         User->replaceUsesOfWith(Scalar, NewInst);
7372       }
7373     } else {
7374       Builder.SetInsertPoint(&F->getEntryBlock().front());
7375       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7376       CSEBlocks.insert(&F->getEntryBlock());
7377       User->replaceUsesOfWith(Scalar, NewInst);
7378     }
7379 
7380     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7381   }
7382 
7383   // For each vectorized value:
7384   for (auto &TEPtr : VectorizableTree) {
7385     TreeEntry *Entry = TEPtr.get();
7386 
7387     // No need to handle users of gathered values.
7388     if (Entry->State == TreeEntry::NeedToGather)
7389       continue;
7390 
7391     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7392 
7393     // For each lane:
7394     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7395       Value *Scalar = Entry->Scalars[Lane];
7396 
7397 #ifndef NDEBUG
7398       Type *Ty = Scalar->getType();
7399       if (!Ty->isVoidTy()) {
7400         for (User *U : Scalar->users()) {
7401           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7402 
7403           // It is legal to delete users in the ignorelist.
7404           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7405                   (isa_and_nonnull<Instruction>(U) &&
7406                    isDeleted(cast<Instruction>(U)))) &&
7407                  "Deleting out-of-tree value");
7408         }
7409       }
7410 #endif
7411       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7412       eraseInstruction(cast<Instruction>(Scalar));
7413     }
7414   }
7415 
7416   Builder.ClearInsertionPoint();
7417   InstrElementSize.clear();
7418 
7419   return VectorizableTree[0]->VectorizedValue;
7420 }
7421 
7422 void BoUpSLP::optimizeGatherSequence() {
7423   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7424                     << " gather sequences instructions.\n");
7425   // LICM InsertElementInst sequences.
7426   for (Instruction *I : GatherShuffleSeq) {
7427     if (isDeleted(I))
7428       continue;
7429 
7430     // Check if this block is inside a loop.
7431     Loop *L = LI->getLoopFor(I->getParent());
7432     if (!L)
7433       continue;
7434 
7435     // Check if it has a preheader.
7436     BasicBlock *PreHeader = L->getLoopPreheader();
7437     if (!PreHeader)
7438       continue;
7439 
7440     // If the vector or the element that we insert into it are
7441     // instructions that are defined in this basic block then we can't
7442     // hoist this instruction.
7443     if (any_of(I->operands(), [L](Value *V) {
7444           auto *OpI = dyn_cast<Instruction>(V);
7445           return OpI && L->contains(OpI);
7446         }))
7447       continue;
7448 
7449     // We can hoist this instruction. Move it to the pre-header.
7450     I->moveBefore(PreHeader->getTerminator());
7451   }
7452 
7453   // Make a list of all reachable blocks in our CSE queue.
7454   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7455   CSEWorkList.reserve(CSEBlocks.size());
7456   for (BasicBlock *BB : CSEBlocks)
7457     if (DomTreeNode *N = DT->getNode(BB)) {
7458       assert(DT->isReachableFromEntry(N));
7459       CSEWorkList.push_back(N);
7460     }
7461 
7462   // Sort blocks by domination. This ensures we visit a block after all blocks
7463   // dominating it are visited.
7464   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7465     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7466            "Different nodes should have different DFS numbers");
7467     return A->getDFSNumIn() < B->getDFSNumIn();
7468   });
7469 
7470   // Less defined shuffles can be replaced by the more defined copies.
7471   // Between two shuffles one is less defined if it has the same vector operands
7472   // and its mask indeces are the same as in the first one or undefs. E.g.
7473   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7474   // poison, <0, 0, 0, 0>.
7475   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7476                                            SmallVectorImpl<int> &NewMask) {
7477     if (I1->getType() != I2->getType())
7478       return false;
7479     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7480     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7481     if (!SI1 || !SI2)
7482       return I1->isIdenticalTo(I2);
7483     if (SI1->isIdenticalTo(SI2))
7484       return true;
7485     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7486       if (SI1->getOperand(I) != SI2->getOperand(I))
7487         return false;
7488     // Check if the second instruction is more defined than the first one.
7489     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7490     ArrayRef<int> SM1 = SI1->getShuffleMask();
7491     // Count trailing undefs in the mask to check the final number of used
7492     // registers.
7493     unsigned LastUndefsCnt = 0;
7494     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7495       if (SM1[I] == UndefMaskElem)
7496         ++LastUndefsCnt;
7497       else
7498         LastUndefsCnt = 0;
7499       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7500           NewMask[I] != SM1[I])
7501         return false;
7502       if (NewMask[I] == UndefMaskElem)
7503         NewMask[I] = SM1[I];
7504     }
7505     // Check if the last undefs actually change the final number of used vector
7506     // registers.
7507     return SM1.size() - LastUndefsCnt > 1 &&
7508            TTI->getNumberOfParts(SI1->getType()) ==
7509                TTI->getNumberOfParts(
7510                    FixedVectorType::get(SI1->getType()->getElementType(),
7511                                         SM1.size() - LastUndefsCnt));
7512   };
7513   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7514   // instructions. TODO: We can further optimize this scan if we split the
7515   // instructions into different buckets based on the insert lane.
7516   SmallVector<Instruction *, 16> Visited;
7517   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7518     assert(*I &&
7519            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7520            "Worklist not sorted properly!");
7521     BasicBlock *BB = (*I)->getBlock();
7522     // For all instructions in blocks containing gather sequences:
7523     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7524       if (isDeleted(&In))
7525         continue;
7526       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7527           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7528         continue;
7529 
7530       // Check if we can replace this instruction with any of the
7531       // visited instructions.
7532       bool Replaced = false;
7533       for (Instruction *&V : Visited) {
7534         SmallVector<int> NewMask;
7535         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7536             DT->dominates(V->getParent(), In.getParent())) {
7537           In.replaceAllUsesWith(V);
7538           eraseInstruction(&In);
7539           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7540             if (!NewMask.empty())
7541               SI->setShuffleMask(NewMask);
7542           Replaced = true;
7543           break;
7544         }
7545         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7546             GatherShuffleSeq.contains(V) &&
7547             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7548             DT->dominates(In.getParent(), V->getParent())) {
7549           In.moveAfter(V);
7550           V->replaceAllUsesWith(&In);
7551           eraseInstruction(V);
7552           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7553             if (!NewMask.empty())
7554               SI->setShuffleMask(NewMask);
7555           V = &In;
7556           Replaced = true;
7557           break;
7558         }
7559       }
7560       if (!Replaced) {
7561         assert(!is_contained(Visited, &In));
7562         Visited.push_back(&In);
7563       }
7564     }
7565   }
7566   CSEBlocks.clear();
7567   GatherShuffleSeq.clear();
7568 }
7569 
7570 BoUpSLP::ScheduleData *
7571 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7572   ScheduleData *Bundle = nullptr;
7573   ScheduleData *PrevInBundle = nullptr;
7574   for (Value *V : VL) {
7575     ScheduleData *BundleMember = getScheduleData(V);
7576     assert(BundleMember &&
7577            "no ScheduleData for bundle member "
7578            "(maybe not in same basic block)");
7579     assert(BundleMember->isSchedulingEntity() &&
7580            "bundle member already part of other bundle");
7581     if (PrevInBundle) {
7582       PrevInBundle->NextInBundle = BundleMember;
7583     } else {
7584       Bundle = BundleMember;
7585     }
7586 
7587     // Group the instructions to a bundle.
7588     BundleMember->FirstInBundle = Bundle;
7589     PrevInBundle = BundleMember;
7590   }
7591   assert(Bundle && "Failed to find schedule bundle");
7592   return Bundle;
7593 }
7594 
7595 // Groups the instructions to a bundle (which is then a single scheduling entity)
7596 // and schedules instructions until the bundle gets ready.
7597 Optional<BoUpSLP::ScheduleData *>
7598 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7599                                             const InstructionsState &S) {
7600   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7601   // instructions.
7602   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7603     return nullptr;
7604 
7605   // Initialize the instruction bundle.
7606   Instruction *OldScheduleEnd = ScheduleEnd;
7607   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7608 
7609   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7610                                                          ScheduleData *Bundle) {
7611     // The scheduling region got new instructions at the lower end (or it is a
7612     // new region for the first bundle). This makes it necessary to
7613     // recalculate all dependencies.
7614     // It is seldom that this needs to be done a second time after adding the
7615     // initial bundle to the region.
7616     if (ScheduleEnd != OldScheduleEnd) {
7617       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7618         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7619       ReSchedule = true;
7620     }
7621     if (Bundle) {
7622       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7623                         << " in block " << BB->getName() << "\n");
7624       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7625     }
7626 
7627     if (ReSchedule) {
7628       resetSchedule();
7629       initialFillReadyList(ReadyInsts);
7630     }
7631 
7632     // Now try to schedule the new bundle or (if no bundle) just calculate
7633     // dependencies. As soon as the bundle is "ready" it means that there are no
7634     // cyclic dependencies and we can schedule it. Note that's important that we
7635     // don't "schedule" the bundle yet (see cancelScheduling).
7636     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7637            !ReadyInsts.empty()) {
7638       ScheduleData *Picked = ReadyInsts.pop_back_val();
7639       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7640              "must be ready to schedule");
7641       schedule(Picked, ReadyInsts);
7642     }
7643   };
7644 
7645   // Make sure that the scheduling region contains all
7646   // instructions of the bundle.
7647   for (Value *V : VL) {
7648     if (!extendSchedulingRegion(V, S)) {
7649       // If the scheduling region got new instructions at the lower end (or it
7650       // is a new region for the first bundle). This makes it necessary to
7651       // recalculate all dependencies.
7652       // Otherwise the compiler may crash trying to incorrectly calculate
7653       // dependencies and emit instruction in the wrong order at the actual
7654       // scheduling.
7655       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7656       return None;
7657     }
7658   }
7659 
7660   bool ReSchedule = false;
7661   for (Value *V : VL) {
7662     ScheduleData *BundleMember = getScheduleData(V);
7663     assert(BundleMember &&
7664            "no ScheduleData for bundle member (maybe not in same basic block)");
7665 
7666     // Make sure we don't leave the pieces of the bundle in the ready list when
7667     // whole bundle might not be ready.
7668     ReadyInsts.remove(BundleMember);
7669 
7670     if (!BundleMember->IsScheduled)
7671       continue;
7672     // A bundle member was scheduled as single instruction before and now
7673     // needs to be scheduled as part of the bundle. We just get rid of the
7674     // existing schedule.
7675     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7676                       << " was already scheduled\n");
7677     ReSchedule = true;
7678   }
7679 
7680   auto *Bundle = buildBundle(VL);
7681   TryScheduleBundleImpl(ReSchedule, Bundle);
7682   if (!Bundle->isReady()) {
7683     cancelScheduling(VL, S.OpValue);
7684     return None;
7685   }
7686   return Bundle;
7687 }
7688 
7689 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7690                                                 Value *OpValue) {
7691   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7692     return;
7693 
7694   ScheduleData *Bundle = getScheduleData(OpValue);
7695   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7696   assert(!Bundle->IsScheduled &&
7697          "Can't cancel bundle which is already scheduled");
7698   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7699          "tried to unbundle something which is not a bundle");
7700 
7701   // Remove the bundle from the ready list.
7702   if (Bundle->isReady())
7703     ReadyInsts.remove(Bundle);
7704 
7705   // Un-bundle: make single instructions out of the bundle.
7706   ScheduleData *BundleMember = Bundle;
7707   while (BundleMember) {
7708     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7709     BundleMember->FirstInBundle = BundleMember;
7710     ScheduleData *Next = BundleMember->NextInBundle;
7711     BundleMember->NextInBundle = nullptr;
7712     if (BundleMember->unscheduledDepsInBundle() == 0) {
7713       ReadyInsts.insert(BundleMember);
7714     }
7715     BundleMember = Next;
7716   }
7717 }
7718 
7719 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7720   // Allocate a new ScheduleData for the instruction.
7721   if (ChunkPos >= ChunkSize) {
7722     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7723     ChunkPos = 0;
7724   }
7725   return &(ScheduleDataChunks.back()[ChunkPos++]);
7726 }
7727 
7728 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7729                                                       const InstructionsState &S) {
7730   if (getScheduleData(V, isOneOf(S, V)))
7731     return true;
7732   Instruction *I = dyn_cast<Instruction>(V);
7733   assert(I && "bundle member must be an instruction");
7734   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7735          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7736          "be scheduled");
7737   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7738     ScheduleData *ISD = getScheduleData(I);
7739     if (!ISD)
7740       return false;
7741     assert(isInSchedulingRegion(ISD) &&
7742            "ScheduleData not in scheduling region");
7743     ScheduleData *SD = allocateScheduleDataChunks();
7744     SD->Inst = I;
7745     SD->init(SchedulingRegionID, S.OpValue);
7746     ExtraScheduleDataMap[I][S.OpValue] = SD;
7747     return true;
7748   };
7749   if (CheckSheduleForI(I))
7750     return true;
7751   if (!ScheduleStart) {
7752     // It's the first instruction in the new region.
7753     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7754     ScheduleStart = I;
7755     ScheduleEnd = I->getNextNode();
7756     if (isOneOf(S, I) != I)
7757       CheckSheduleForI(I);
7758     assert(ScheduleEnd && "tried to vectorize a terminator?");
7759     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7760     return true;
7761   }
7762   // Search up and down at the same time, because we don't know if the new
7763   // instruction is above or below the existing scheduling region.
7764   BasicBlock::reverse_iterator UpIter =
7765       ++ScheduleStart->getIterator().getReverse();
7766   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7767   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7768   BasicBlock::iterator LowerEnd = BB->end();
7769   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7770          &*DownIter != I) {
7771     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7772       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7773       return false;
7774     }
7775 
7776     ++UpIter;
7777     ++DownIter;
7778   }
7779   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7780     assert(I->getParent() == ScheduleStart->getParent() &&
7781            "Instruction is in wrong basic block.");
7782     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7783     ScheduleStart = I;
7784     if (isOneOf(S, I) != I)
7785       CheckSheduleForI(I);
7786     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7787                       << "\n");
7788     return true;
7789   }
7790   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7791          "Expected to reach top of the basic block or instruction down the "
7792          "lower end.");
7793   assert(I->getParent() == ScheduleEnd->getParent() &&
7794          "Instruction is in wrong basic block.");
7795   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7796                    nullptr);
7797   ScheduleEnd = I->getNextNode();
7798   if (isOneOf(S, I) != I)
7799     CheckSheduleForI(I);
7800   assert(ScheduleEnd && "tried to vectorize a terminator?");
7801   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7802   return true;
7803 }
7804 
7805 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7806                                                 Instruction *ToI,
7807                                                 ScheduleData *PrevLoadStore,
7808                                                 ScheduleData *NextLoadStore) {
7809   ScheduleData *CurrentLoadStore = PrevLoadStore;
7810   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7811     ScheduleData *SD = ScheduleDataMap[I];
7812     if (!SD) {
7813       SD = allocateScheduleDataChunks();
7814       ScheduleDataMap[I] = SD;
7815       SD->Inst = I;
7816     }
7817     assert(!isInSchedulingRegion(SD) &&
7818            "new ScheduleData already in scheduling region");
7819     SD->init(SchedulingRegionID, I);
7820 
7821     if (I->mayReadOrWriteMemory() &&
7822         (!isa<IntrinsicInst>(I) ||
7823          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7824           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7825               Intrinsic::pseudoprobe))) {
7826       // Update the linked list of memory accessing instructions.
7827       if (CurrentLoadStore) {
7828         CurrentLoadStore->NextLoadStore = SD;
7829       } else {
7830         FirstLoadStoreInRegion = SD;
7831       }
7832       CurrentLoadStore = SD;
7833     }
7834   }
7835   if (NextLoadStore) {
7836     if (CurrentLoadStore)
7837       CurrentLoadStore->NextLoadStore = NextLoadStore;
7838   } else {
7839     LastLoadStoreInRegion = CurrentLoadStore;
7840   }
7841 }
7842 
7843 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7844                                                      bool InsertInReadyList,
7845                                                      BoUpSLP *SLP) {
7846   assert(SD->isSchedulingEntity());
7847 
7848   SmallVector<ScheduleData *, 10> WorkList;
7849   WorkList.push_back(SD);
7850 
7851   while (!WorkList.empty()) {
7852     ScheduleData *SD = WorkList.pop_back_val();
7853     for (ScheduleData *BundleMember = SD; BundleMember;
7854          BundleMember = BundleMember->NextInBundle) {
7855       assert(isInSchedulingRegion(BundleMember));
7856       if (BundleMember->hasValidDependencies())
7857         continue;
7858 
7859       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7860                  << "\n");
7861       BundleMember->Dependencies = 0;
7862       BundleMember->resetUnscheduledDeps();
7863 
7864       // Handle def-use chain dependencies.
7865       if (BundleMember->OpValue != BundleMember->Inst) {
7866         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
7867           BundleMember->Dependencies++;
7868           ScheduleData *DestBundle = UseSD->FirstInBundle;
7869           if (!DestBundle->IsScheduled)
7870             BundleMember->incrementUnscheduledDeps(1);
7871           if (!DestBundle->hasValidDependencies())
7872             WorkList.push_back(DestBundle);
7873         }
7874       } else {
7875         for (User *U : BundleMember->Inst->users()) {
7876           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
7877             BundleMember->Dependencies++;
7878             ScheduleData *DestBundle = UseSD->FirstInBundle;
7879             if (!DestBundle->IsScheduled)
7880               BundleMember->incrementUnscheduledDeps(1);
7881             if (!DestBundle->hasValidDependencies())
7882               WorkList.push_back(DestBundle);
7883           }
7884         }
7885       }
7886 
7887       // Handle the memory dependencies (if any).
7888       ScheduleData *DepDest = BundleMember->NextLoadStore;
7889       if (!DepDest)
7890         continue;
7891       Instruction *SrcInst = BundleMember->Inst;
7892       assert(SrcInst->mayReadOrWriteMemory() &&
7893              "NextLoadStore list for non memory effecting bundle?");
7894       MemoryLocation SrcLoc = getLocation(SrcInst);
7895       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7896       unsigned numAliased = 0;
7897       unsigned DistToSrc = 1;
7898 
7899       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7900         assert(isInSchedulingRegion(DepDest));
7901 
7902         // We have two limits to reduce the complexity:
7903         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7904         //    SLP->isAliased (which is the expensive part in this loop).
7905         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7906         //    the whole loop (even if the loop is fast, it's quadratic).
7907         //    It's important for the loop break condition (see below) to
7908         //    check this limit even between two read-only instructions.
7909         if (DistToSrc >= MaxMemDepDistance ||
7910             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7911              (numAliased >= AliasedCheckLimit ||
7912               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7913 
7914           // We increment the counter only if the locations are aliased
7915           // (instead of counting all alias checks). This gives a better
7916           // balance between reduced runtime and accurate dependencies.
7917           numAliased++;
7918 
7919           DepDest->MemoryDependencies.push_back(BundleMember);
7920           BundleMember->Dependencies++;
7921           ScheduleData *DestBundle = DepDest->FirstInBundle;
7922           if (!DestBundle->IsScheduled) {
7923             BundleMember->incrementUnscheduledDeps(1);
7924           }
7925           if (!DestBundle->hasValidDependencies()) {
7926             WorkList.push_back(DestBundle);
7927           }
7928         }
7929 
7930         // Example, explaining the loop break condition: Let's assume our
7931         // starting instruction is i0 and MaxMemDepDistance = 3.
7932         //
7933         //                      +--------v--v--v
7934         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7935         //             +--------^--^--^
7936         //
7937         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7938         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7939         // Previously we already added dependencies from i3 to i6,i7,i8
7940         // (because of MaxMemDepDistance). As we added a dependency from
7941         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7942         // and we can abort this loop at i6.
7943         if (DistToSrc >= 2 * MaxMemDepDistance)
7944           break;
7945         DistToSrc++;
7946       }
7947     }
7948     if (InsertInReadyList && SD->isReady()) {
7949       ReadyInsts.insert(SD);
7950       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7951                         << "\n");
7952     }
7953   }
7954 }
7955 
7956 void BoUpSLP::BlockScheduling::resetSchedule() {
7957   assert(ScheduleStart &&
7958          "tried to reset schedule on block which has not been scheduled");
7959   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7960     doForAllOpcodes(I, [&](ScheduleData *SD) {
7961       assert(isInSchedulingRegion(SD) &&
7962              "ScheduleData not in scheduling region");
7963       SD->IsScheduled = false;
7964       SD->resetUnscheduledDeps();
7965     });
7966   }
7967   ReadyInsts.clear();
7968 }
7969 
7970 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7971   if (!BS->ScheduleStart)
7972     return;
7973 
7974   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7975 
7976   BS->resetSchedule();
7977 
7978   // For the real scheduling we use a more sophisticated ready-list: it is
7979   // sorted by the original instruction location. This lets the final schedule
7980   // be as  close as possible to the original instruction order.
7981   struct ScheduleDataCompare {
7982     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7983       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7984     }
7985   };
7986   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7987 
7988   // Ensure that all dependency data is updated and fill the ready-list with
7989   // initial instructions.
7990   int Idx = 0;
7991   int NumToSchedule = 0;
7992   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7993        I = I->getNextNode()) {
7994     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7995       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7996               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7997              "scheduler and vectorizer bundle mismatch");
7998       SD->FirstInBundle->SchedulingPriority = Idx++;
7999       if (SD->isSchedulingEntity()) {
8000         BS->calculateDependencies(SD, false, this);
8001         NumToSchedule++;
8002       }
8003     });
8004   }
8005   BS->initialFillReadyList(ReadyInsts);
8006 
8007   Instruction *LastScheduledInst = BS->ScheduleEnd;
8008 
8009   // Do the "real" scheduling.
8010   while (!ReadyInsts.empty()) {
8011     ScheduleData *picked = *ReadyInsts.begin();
8012     ReadyInsts.erase(ReadyInsts.begin());
8013 
8014     // Move the scheduled instruction(s) to their dedicated places, if not
8015     // there yet.
8016     for (ScheduleData *BundleMember = picked; BundleMember;
8017          BundleMember = BundleMember->NextInBundle) {
8018       Instruction *pickedInst = BundleMember->Inst;
8019       if (pickedInst->getNextNode() != LastScheduledInst)
8020         pickedInst->moveBefore(LastScheduledInst);
8021       LastScheduledInst = pickedInst;
8022     }
8023 
8024     BS->schedule(picked, ReadyInsts);
8025     NumToSchedule--;
8026   }
8027   assert(NumToSchedule == 0 && "could not schedule all instructions");
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