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